text
stringlengths
8
6.05M
#!bin/python3 # coding=utf8 """ Firefox xpi 文件批量处理(修改最大版本号). """ import re, zipfile, os, sys maxversion = 100 ff_maxversion_reg = re.compile(br'(ec8030f7-c20a-464f-9b0e-13a3a9e97384.*?em:maxVersion.*?)([^>< ="/]+)', re.S+re.I) if __name__ == '__main__': if len(sys.argv) > 1: maxversion = int...
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- ''' 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符, 并返回它的位置, 如果没有则返回 -1(需要区分大小写). ''' class Solution: def FirstNotRepeatingChar(self, s): # write code here if (len(s) == 0): return -1 res = {} for i in s: if i in res.keys(): res...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-29 02:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user_dash', '0001_initial'), ] operations = [ ...
import pandas as pd ############################################# ### Supply label and channel information: ### ############################################# channels = ['F3','FC5','AF3','F7','T7','P7','O1','O2','P8','T8','F8','AF4','FC6','F4'] trial_labels = ['fleece', 'trap', 'sh', 'v', 'p', 'n', 'm', 'z', 'goose',...
from tkinter import * import mysqlFunctions import datetime from tkinter import messagebox from tkinter import ttk class AdminWindow(mysqlFunctions.Common): def __init__(self, master): mysqlFunctions.Common.__init__(self) self.master = master master.title("Admin control panel") mas...
# !/usr/bin/env python3 # coding: utf-8 # -*- coding: utf-8 -*- from PyQt5.QtWidgets import QFrame, QLineEdit, QTextEdit class Card(QFrame): def __init__(self, parent, id, has_text_field=True): super(Card, self).__init__() self.setParent(parent) self.id = id self.DEFAULT_COLOR = "...
# Send Email module
# 推导式 # 列表推导式 # 格式:[变量 for 变量 in 可迭代对象] # 创建一个包含0~9元素的列表,使用常见创建方式 # list1 = [] # for i in range(10): # list1.append(i) # print(list1) # 使用列表推导式 # list2 = [x for x in range(10)] # print(list2) # # list3 = [x for x in range(10)if x % 2 == 0] # 借助if判断 # print(list3) # # list4 = [x*x for x in range(5)] # ...
# simple HTTP to OSC routing import OSC import logging import time import datetime from flask import Flask, Response, jsonify, json, request app = Flask(__name__) c = OSC.OSCClient() file_handler = logging.FileHandler('oschttp'+str(datetime.datetime.today().date())+'.log') app.logger.addHandler(file_handler) app.logg...
from PIL import Image import math import colorsys import sys, os, struct def konwertuj(path): print path if (os.path.splitext(path)[1][1:] != "jpg" and os.path.splitext(path)[1][1:] != "png"): print("\tBledny format pliku") else: im = Image.open(path) img = im.convert('RGB') baseWidth, baseHeight = img.s...
# -*-coding:Utf-8 -* """Ce module contient la classe Labyrinthe.""" class Labyrinthe: """Classe représentant un labyrinthe. Qui permet de conserver la position du robot, la grille de jeu, la derniere instruction du joueur et son nombre de répétition.""" def __init__(self, map): self.robot_x ...
from django.shortcuts import render_to_response from django.db.models import Q from django.template import RequestContext from listing.models import Listing from accounts.models import UserProfile from geogeld.settings import DISPLAY_LISTINGS_PER_PAGE from django.core.paginator import Paginator, PageNotAnInteger, Empt...
import random import string import boto3 import time from collections import defaultdict region = 'us-west-2' def passwordGenerator(stringLength=20): """ Generates a random string of fixed length""" password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choic...
from django.shortcuts import render from django.http import HttpResponse from photo.models import MyPhoto # Create your views here. def photo_test(request): return HttpResponse('hello world!') def photo_view(request): photo_list = MyPhoto.objects.all() return render(request, 'photo/index.html', {'photo_lis...
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options import time import pandas as pd login_u...
import board import neopixel import time pixels = neopixel.NeoPixel(board.D18, 20) For i in range (4): pixels[i] = (255,0,0) For i in range (5, 20): pixels[i] = (0,0,10)
# @see https://adventofcode.com/2015/day/12 import json with open('day12_input.txt', 'r') as f: doc = json.loads(f.readline()) def calc_balance(d, acc: int = 0): if type(d) == int: acc += d elif type(d) == str: pass elif type(d) == list: for v in d: acc = calc_balance(v, acc) elif type...
PLATFORM_LIST = ['linux-x64', 'darwin-x64']
# Santosh Khadka ''' Python Set - Wont take any duplicate items ''' s1 = set() s1.add(4) # Takes only one argument s1.add(5) s1.add(4) # print(s1) # {4, 5} ; Did not add the duplicate 4 s1.add(1) s1.add(3) s1.add(10) # print(s1) # {1, 3, 4, 5, 10} ; Prints in order ''' Clear ''' s1.clear() # Makes empt...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Module for managing data packets. Useful for sending data to a microcontroller over a serial connection. This module adds control characters and a checksum to a list of integers. It returns the new list. Packet structure: Each packet consists of a start and end char, d...
import socket import threading from enum import Enum from datetime import datetime class UserInfo: def __init__(self, name, address, session_id): self.name = name self.address = address self.session_id = session_id self.last_ping = datetime.utcnow() self.messa...
from src.Utils import Pickler from src.Utils.logger import logger class SkuSingleton: __object = None def __init__(self): if SkuSingleton.__object is None: logger.info('UNPICKLING SKU MATCHING NOTEBOOK') SkuSingleton.__object = Pickler.unpickle_data('./src/sku_matchbook.pick...
from __future__ import print_function import sys import os import logging import json import copy from os.path import dirname from jsonschema import validate import importlib import pkgutil import tempfile import uuid from halocli.exception import HaloPluginException from halocli.util import Util logger = logging.getL...
__author__ = 'hassaankhan' import os import shapefile global basepath basepath = os.path.split(__file__)[0] global shapefile_folder shapefile_folder = 'data/shapefiles' def get_shapefile(filename): shp = shapefile.Reader(os.path.join(basepath, shapefile_folder, filename)) shp_obj = shp.shapeRecords() r...
t = int(input()) n, q = map(int, input().split()) s = input() result = set() for i in range (len (s)): temp = "" for j in range (i, len(s)): temp += s[j]; result.add (temp) result = sorted (result) print (result) for i in range (q): k = int(input()) if k <= len(result): print ...
coordinates = (4, 5) #coordinates[1] = 10 #tuples cannot be edited print(coordinates[1])
employees = dict() for _ in range(5): name = input("Enter name:") salary = int(input("Enter salary:")) employees[name] = salary best_three_salaries = sorted(employees.values())[-3:] for name in employees.keys(): salary = employees[name] if salary in best_three_salaries: print(sorted(name)) ...
""" Author : Lily Date : 2018-09-21 QQ : 339600718 酷动数码 Coodoo Coodoo-s 抓取思路:数据在页面上,需要翻页,但页面上最大页数,只能从下一页中拿到下一页的页数,再获取下一页的数据 当没有下一页这个标签时,停止抓取。 URL :http://www.coodoo.com.cn/Stores """ import re import datetime import requests from lxml import etree filename = "Coodoo-s" + re.sub('[^0-9]', '', str(datetime....
from django.contrib import admin from django.urls import path, include from rest_framework import routers from api import views from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView router = routers.DefaultRouter() router.register('users', views.UserViewSet) router.register('books', views.B...
from Base import * from Object import * ''' Esta funcao cria um objeto do tipo Chessboard e o retorna @PARAMETROS id_tex_livre - primeiro id de textura nao utilizado - passado como lista de tamanho 1 vertices_list - lista de coordenadas de vertices textures_coord_list - lista de coordenadas de textura ...
#coding = utf-8 import socket import threading import time global UID HOST = '127.0.0.1' PORT = 38557 UID = '' SUCCESS = 'succeed' class Receive(threading.Thread): global UID def __init__(self, conn): self.conn = conn self.is_receiving = True threading.Thread.__init__(self) def ...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
from pyramid.registry import Registry from kotti.testing import DummyRequest from kotti.testing import UnitTestBase class TestEvents(UnitTestBase): def setUp(self): # We're jumping through some hoops to allow the event handlers # to be able to do 'pyramid.threadlocal.get_current_request' #...
# -*- coding: utf-8 -*- # flake8: noqa from __future__ import unicode_literals from django.db import models, migrations import webplatformcompat.validators import webplatformcompat.fields import django_extensions.db.fields import django_extensions.db.fields.json import mptt.fields import sortedm2m.fields import django...
def fibonacci(n): n1 = 0 n2 = 1 i = 3 while i <= n: n3 = n1 + n2 n1 = n2 n2 = n3 i += 1 return n3 print(fibonacci(10)) print(fibonacci(11)) print(fibonacci(12)) # 檔名: exercise0807.py # 作者: Kaiching Chang # 時間: July, 2014
#!/usr/bin/env python from game.base.state import State from game.entities.camera import Camera from game.entities.terminal import Terminal from game.entities.ground import Ground from game.constants import GROUND_HEIGHT, CAMERA_OFFSET, SCRIPTS_DIR from game.scene import Scene from game.util import pg_color, random_rg...
# Sending mail using smtp. import smtplib import getpass session = smtplib.SMTP('smtp.gmail.com', 587) session.starttls() print('Gmail Login.') senderEmailId = input('Enter Gmail Id: ') password = getpass.getpass('Enter Password: ') try: session.login(senderEmailId, password) recipientEmailId = input('Enter sender Em...
import time inicio = time.perf_counter() def aDormir(): print("Iniciando función, voy a dormir 1 s") time.sleep(1) print("Paso un segundo, he despertado") #Ahora compararemos que pasa cuando ejecutamos 10 veces la función a for _ in range(10): aDormir() final = time.perf_counter() print(f"Código ejecutado en {f...
from datetime import datetime from xml_get import get_nodes, remove_non_ascii, get_node_text_value def get_time_from_short_path(itinerary, short_path): """ Time formatting :param itinerary: :param short_path: :return: """ # TODO : Fix/Add Timezones! # TODO ensure it doesn't break com...
import pandas as pd from data_paths import paths from glob import glob import matplotlib.pyplot as plt data_paths = glob(paths["salary"] + "/*") # Paths to training files training_features = pd.read_csv(data_paths[1]) training_target = pd.read_csv(data_paths[-1]) # Merge to form a single dataframe print "Dimensions ...
import thread import time import random def run_often(thread_nome, sleep_time): while True: time.sleep(sleep_time) print '%s' % thread_nome def run_less_often(thread_nome, sleep_time): while True: time.sleep(sleep_time) print '%s' % thread_nome def run_randomly(thread_nome, sleep_time): while True: time...
""" Django settings for thm project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import...
# # cogs/info/info.py # # mawabot - Maware's selfbot # Copyright (c) 2017 Ma-wa-re, Ammon Smith # # mawabot is available free of charge under the terms of the MIT # License. You are free to redistribute and/or modify it under those # terms. It is distributed in the hopes that it will be useful, but # WITHOUT ANY WARRAN...
Max = "Hello" print Max
# Generated by Django 3.2.3 on 2021-05-17 21:53 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('frontoffice', '0001_initial'), ] operations = [ migrations.AlterField( mod...
class punto(): def __init__(self, valor, izq = None, der = None): self.v= valor self.izq = izq self.der=der def preorden(arbol): if arbol!=None: return arbol.v+preorden(arbol.izq)+preorden(arbol.der) else: return "" def inorden(arbol): if arbol!=None...
t = int(input()) while t: t -= 1 n = int(input()) s = input() if(len(s) == 2): if(s[0] >= s[1]): print('NO') else: print('YES') print(2) print(s[0], s[1]) else: print('YES') print(2) print(s[0], s[1:])
# -*- coding:UTF-8 -*- import cookielib import urllib import urllib2 import commentURL #-- ''' ''' def login(userName, password): LOGIN_SUCCESS_FLAG = 'logout.php' cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) paramete...
class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: """ https://leetcode.com/problems/minimum-time-visiting-all-points/ """ dist = 0 for p in range(1, len(points)): x = abs(points[p][0] - points[p-1][0]) y = abs(points[p]...
import string import requests from bs4 import BeautifulSoup import re import matplotlib.pyplot as plt def findText(link): data = requests.get(link).text return data def getTop100BookLinks(): data = requests.get('https://www.gutenberg.org/browse/scores/top').text soup = BeautifulSoup(data, 'html5lib') ...
import csv import matplotlib.pyplot as plt def get_legend_from_file_path(file_path): return file_path.split(" ") def graph_x_and_y(x, y, legend): plt.plot(x, y, label=legend) def plotgraph(): plt.xlabel("Date") plt.ylabel("Cases") plt.xticks(rotation=90) plt.title("Covid Cases in New Jerse...
#!/usr/bin/env python #Bao Dang #Assignment 2 #Convert preorder to postorder def preorder_postorder(String): L = list(String) s = [] Operators = ['+','-','*','/'] for i in range(len(L)-1, -1, -2): if L[i] in Operators: op1 = s.pop() op2 = s.pop() ...
import json file_handle = open("app_data.json", "r") content = file_handle.read() file_handle.close() # muutetaan JSON-tieto dict city = json.loads(content) print(city) print(city["name"]) print(city["population"]) print(city["county"])
import boto3 from fabric import task @task def deploy(cli): key_id = input('AWS access key id? ') key = input('AWS secret access key? ') region = input('AWS default region? ') registry = input('ECR registry (without your repo name)? ') scm_id = input('SCM secret_id for db? ') cli.run('mkdir -p...
from __future__ import annotations import zipfile import tarfile import typing as T from pathlib import Path import tempfile try: import zstandard except ImportError: zstandard = None # type: ignore Pathlike = T.Union[str, Path] def extract_zst(archive: Pathlike, out_path: Pathlike): """extract .zst fi...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/pi/tanis/CodeBase/ros/src/angela/msg/motormsg.msg" services_str = "" pkg_name = "angela" dependencies_str = "std_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "angela;/home/pi/tanis/CodeBase/ros/src/angela/msg;std...
from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.TextField(max_le...
""" Point items. @author: Jason Cohen @author: Shaun Hamelin-Owens @author: Sasithra Thanabalan @author: Andrew Walker """ # Imports from GameItem import GameItem from display import DrawingGenerics class PointItem(GameItem): """ PointItem class. This class contains the methods used in the creation of any point ite...
a=str(input("請輸入字串:")) b=len(a) print("There are "+str(b)+" characters")
""" ------------------------------------------------------------------------------- | Copyright 2016 Esri | | 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/...
import pyglet from pyglet import clock ''' Ok, so the Tween stuff has been fixed. What I need to figure out now is how to make Frank moving around look good. I feel like I need to read the chapter again Why does frank move around in a jerky fasion? I want a smooth move between points ''' def ease_in_out_quad (t, b, ...
import dash_bootstrap_components as dbc from dash import html number_input = html.Div( [ html.P("Type a number outside the range 0-10"), dbc.Input(type="number", min=0, max=10, step=1), ], id="styled-numeric-input", )
class Graphs: def __init__(self): self.adjancy_list = {} def addVertex(self,vertex): if(self.adjancy_list.get(vertex) is not None): return self.adjancy_list[vertex]= [] def addEdge(self,first_vertex,second_vertex): if(self.adjancy_list.get(first_vertex) is None ...
# coding: utf-8 # In[9]: import lightgbm as lgb import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[23]: train = pd.read_csv('data/train.csv', index_col=0) X = train.drop('target', axis=1) y = train.target # ...
''' 1. check the list of infra habitations 2. check missing hh habitations if any 3. check hh numbers for all habs ''' ''' input file: macro field map: ''' from work.models import ProgressQty, Site import pandas as pd from work.controller import getSite, getHabID from work.controller import getSiteProgressdf from cons...
# -*- coding: utf-8 -*- #a=[] #for i in range(5): # a.append(eval(input())) # #sum=0.0 #for j in range(5): # sum=sum+a[j] #aver=sum/len(a) #print(a[0],a[1],a[2],a[3],a[4]) #print("Sum =",sum) #print("Average =",aver) a=eval(input()) b=eval(input()) c=eval(input()) d=eval(input()) e=eval(input()) sum=a+b+c+d+e av...
import os import commands cmd ='''curl -u root:Dis@init3 http://35.237.28.200/remote.php/dav/files/root/ -X PROPFIND --data '<?xml version="1.0" encoding="UTF-8"?><d:propfind xmlns:d="DAV:"><d:prop xmlns:oc="http://owncloud.org/ns"><d:getcontenttype/><oc:permissions/></d:prop></d:propfind>' ''' status,output = comm...
import pkg_resources pkg_resources.require("matplotlib==1.4.0") from pandas import * from ggplot import * import pprint import csv import itertools import ggplot as gg import numpy as np import pandas as pd from datetime import datetime, date, time import matplotlib.pyplot as plt turnstile_weather=panda...
#!/usr/bin/env python ''' ## Course Project ''' import sys import matplotlib matplotlib.use('TkAgg') from pylab import * import graph_properties as gp import networkx as nx import pycxsimulator import update_graph as ug import metric as met import data_store_ops as ds # -------------------------------------------...
from flask_wtf import FlaskForm from wtforms import StringField,SubmitField,SelectField from wtforms.validators import DataRequired,URL from flask_wtf.file import FileAllowed,FileField from project.utils import * class addeventsform(FlaskForm): def get_all_main_category(dct): all_main_category = [] ...
import pickle from sympy import sympify class Conjecture: def __init__(self, target, inequality, expression, family): self.target = target self.inequality = inequality self.expression = expression.split() self.family_name = family self.family = pickle.load(open(family, 'rb...
import numpy as np from constants import Action, move_action_to_deviation as action_to_deviation_map from utilities import euclidean_dist, manhattan_distance, sgn class State: def __init__(self, block_positions, selected_index, goal_config, screen_dims, block_size=50): """ :type block_positions:...
""" Write a python program to help an airport manager to generate few statistics based on the ticket details available for a day. Go through the below program and complete it based on the comments mentioned in it. Note: Perform case sensitive string comparisons wherever necessary. """ #PF-Assgn-55 #Sample ticket ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pants.option.option_types import BoolOption from pants.option.subsystem import Subsystem class SoapSubsystem(Subsystem): options_scope = "soa...
from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path("accounts/", include("allauth.urls")), path("home/", views.home, name="home"), ]
from unittest import TestCase from svtools.bedpe import Bedpe from svtools.cluster import Cluster class ClusterTests(TestCase): def test_can_add(self): bedpe = [ '1', '200', '300', '2', '300', '400', '777_1', '57', '+', '-', 'BND', 'PASS', 'MISSING', 'SVTYPE=BND;AF=0.2' ] b = Bedpe(bedpe) ...
from django.conf import settings def settings_context_processor(request): """ Processor adding django settings to context """ return {'settings': settings}
n = int(input()) arr = [] if n == 0: print(0) else: while(n != 0 ): rem = n%2 n //=2 arr.append(rem) arr.reverse() print(*arr,sep="")
import gi gi.require_version('Gtk', '3.0')
import dash_bootstrap_components as dbc from dash import html spinners = html.Div( [ dbc.Spinner(size="sm"), html.Hr(), dbc.Spinner(spinner_style={"width": "3rem", "height": "3rem"}), ] )
import torch from models.model import MyCNN from models.model import ExampleCNN from datasets.dataloader import make_test_dataloader import os from tqdm import tqdm def test(model_name, device, base_path, save_path): test_data_path = os.path.join(base_path, "data", "test") weight_path = os.path.join(save_path...
import pandas as pd import numpy as np import py_spatial import rsp_reader from weather import Weather_Station from cleanfirst import Vehicle_Cleaner class Vehicle(Vehicle_Cleaner): ''' This is the class where the bulk of the cleaning and merging of datafiles is performed. It is built on top of the class ...
import numpy as np def rle2mask(mask_rle, shape): ''' mask_rle: run-length as string formated (start length) shape: (width,height) of array to return Returns numpy array, 1 - mask, 0 - background ''' s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[...
# -*- coding: utf-8 -*- # Author: Simone Marsili <simomarsili@gmail.com> # License: BSD 3 clause """A little parser for alignments of biological sequences.""" import pkg_resources from lilbio.funcs import uppercase_only from lilbio.parser import parse, write project_name = 'little-bio-parser' __version__ = pkg_resou...
from flask import Flask,render_template,request,send_file import os from pymongo import MongoClient from flask_pymongo import PyMongo import csv client=MongoClient("mongodb+srv://HerokuUser:herokupassword@cluster0-cglnu.mongodb.net/test?retryWrites=true&w=majority") db=client.get_database("OflUsers") rec=db.f...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-20 01:57 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('water_watch_api', '0004_auto_20180307_1813'), ] operations = [ migrations.AlterModelO...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jun 20 15:19:45 2019 @author: matthew This script is written to replicate the function fft_meanspec written by Adam booth in matlab. as of 9/16, I'm still trying to figure out how to get this code working. When I ran it on the Non-landslide DEM it too...
""" SciKitOpt's Bayesian Optimization implementation from https://scikit-optimize.github.io/stable/auto_examples/bayesian-optimization.html """ from __future__ import print_function from collections import OrderedDict import numpy as np try: from skopt import gp_minimize from kernel_tuner import util baye...
from selenium import webdriver import time import random """driver=webdriver.Firefox() driver.get("https://www.baidu.com/") time.sleep(5) f=driver.current_window_handle driver.get("https://blog.csdn.net/u014801403/article/details/79085085") time.sleep(3) all=driver.window_handles for i in all: if not i==f: ...
import random class Card : def __init__(self, typeCard, mp, detail): self.typeCard = typeCard self.mp = mp self.detail = detail def show(self) : print ("[{}] Mp {} [ Detail : {} ]".format(self.typeCard, self.mp, self.detail)) class Deck : def __init__(self): ...
#raices import cmath num=float(input('escribe el número ')) num_sqrt=cmath.sqrt(num) print('la raíz de {0} es: {1}. parte entera: {2} Parte imaginaria: {3}'.format(num, num_sqrt,num_sqrt.real,num_sqrt.imag))
# coding=UTF-8 __author__ = 'zhengandy' # import MySQLdb import os import xlrd import sys import re import hashlib import simplejson import time from PreCondition import cfgValue import pymysql reload(sys) sys.setdefaultencoding('utf-8') # @UndefinedVariable def get_md5_value(src): ''' It will used for g...
"""empty message Revision ID: 783a4b75539d Revises: 8e9a1fd625aa Create Date: 2020-09-12 15:39:01.370992 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '783a4b75539d' down_revision = '8e9a1fd625aa' branch_labels = None depends_on = None def upgrade(): # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #外部ファイルから質問リストを読み込み辞書に保存するプログラム import math import sys from janome.tokenizer import Tokenizer import rospy from std_msgs.msg import String #text = String() t = Tokenizer() qa_dict = {} def get_Cos_up(v1, v2): sum=0 for word in v1: if word in v2: ...
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 20:17:24 2018 @author: user 共同科目 """ x=set() y=set() print("Enter group X's subjects:") while True: a=input() if a == "end": break else: x.add(a) print("Enter group Y's subjects:") while True: a=input() if a == "end": break...
class Plant: def __init__(self, name, type, actiontype, date, time): """Fields of a model Plant.""" self.name = name self.type = type self.actiontype = actiontype self.date = date self.time = time
import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import MinMaxScaler rating = pd.read_csv('data/ratings.csv') architect = pd.read_csv('data/architects.csv') user = pd.read_csv('data/users.csv'); architect_rating = pd.merge(rating, architect, on='architect_id') cols = ['Registra...
# Чтобы написать тест, мы должны определить функцию, имя которой начинается на test_ # после этого мы используем ключевое слово assert, которое проверят, является ли истинным значение сразу за ним def test_something(): assert True def test_equal_string(): greetings = "Hello, " + "world" ...
from glob import glob from os.path import join from pyrosetta import * from pyrosetta.rosetta.core.simple_metrics.metrics import TotalEnergyMetric, InteractionEnergyMetric from pyrosetta.rosetta.core.simple_metrics.per_residue_metrics import PerResidueEnergyMetric from pyrosetta.rosetta.core.select.residue_selecto...
import torch import torch.nn as nn class SetConvLayer(torch.nn.Module): def __init__(self, cfg, in_dim, out_dim): super(SetConvLayer, self).__init__() self.cfg = cfg self.fc = nn.Linear(in_dim, out_dim, bias=True) self.w = nn.Parameter(torch.ones(in_dim, out_dim), requires_grad=T...