text
stringlengths
38
1.54M
# -*- coding: utf8 -*- from __future__ import unicode_literals import time from datetime import datetime from eulxml import xmlmap def windows_to_unix_timestamp(windows_timestamp): """ Converts a Windows timestamp to Unix one :param windows_timestamp: Windows timestamp :type windows_timestamp: int ...
market=input("enter your place") name=input("enter your name") if market=="name": print("we will go to market") else: print("we will not go to market")
import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import numpy as np import datasets import models as models import matplotlib.pyplot as plt import torchvision.models as torch_m...
# test json import sys from urllib.request import Request, urlopen # 모듈 from datetime import * import json ''' url = 'http://www.naver.com' request = Request(url) # url요청 resp = urlopen(request) #url열기 resp_body = resp.read().decode("utf-8") #utf-8로 인코딩 print(resp_body)#body출력 ''' #에러 try:#예외처리 url = 'http://kick...
# -*- coding: utf-8 -*- """ Created on Fri Dec 7 21:19:11 2018 @author: initial-h """ import numpy as np import copy from operator import itemgetter from collections import defaultdict def rollout_policy_fn(board): """ a coarse, fast version of policy_fn used in the rollout phase. """ action_probs ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 20 13:04:39 2019 @author: root """ import numpy as np import matplotlib.pyplot as plt import cv2 import openslide as opsl import sys import os import glob from keras.models import load_model os.environ['CUDA_VISIBLE_DEVICES']='0' resnet_model = loa...
length_unit = "mm" torque_unit = "nm" def get_torque( drive_shaft_diameter=5, drive_shaft_torque=0.2, gear_small_diameter=15, gear_large_diameter=55, ): drive_shaft_radius = drive_shaft_diameter * 0.5 gear_large_radius = gear_large_diameter * 0.5 gear_small_radius = gear_small_diameter * 0...
import re import datetime from requests import ConnectionError from ..exceptions import ( APIError, RaceCardError, InvalidResponse, ) from ..utils import check_status_code from .baseendpoint import BaseEndpoint from .. import resources class RaceCard(BaseEndpoint): """ RaceCard operations. ""...
#visualize light curves import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os from definitions import PNG_FOLDER def chart_curves(kepid,tce_plnt_num,global_curve,local_curve,koi_disposition): fig,axes=plt.subplots(1,2,figsize=(20,6)) gv=sns.scatterplot(data=global_curve,ax=axes[0...
import cv2 import numpy as np from matplotlib import pyplot as plt def histeq(im,nbr_bins=256): """ Histogram equalization of a grayscale image. """ #get image histogram imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * c...
from bspump import BSPumpApplication, Pipeline import bspump.trigger import bspump.common import bspump.mongodb import logging ## L = logging.getLogger(__name__) ## class MyApplication(BSPumpApplication): def __init__(self): super().__init__() svc = self.get_service("bspump.PumpService") svc.add_connection(...
#----------------------------------------------------------------------------# # # # Copyright (C) 2009 Department of Arts and Culture, # # Republic of South Africa # # ...
#! /usr/bin/env python # util.py # Created on 2017-09-14. import os import argparse import importlib import importlib.util import sys import json import shutil import re """ For reference, the pipelines that are functional are the following: gclass_ase_pipeline gclass_oosase_pipeline gc...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return '' s = strs[0] minLen = min(map(len, strs)) i = 0 res = [] while i < minLen: char =...
from random import shuffle from PIL import Image, ImageOps, ImageDraw from math import floor, ceil, modf def stepped_range(end,steps): t = 0 while t<end: yield t t+=1/steps def agent_to_col(agent,pixel_type=0): return tuple(eval(agent.name) + [pixel_type]) def name_from_pixel(pixel): ...
# deguwedurl = 'https://weather.naver.com/today/06110101' # 날씨1 주소 # deguwed1 = requests.get(deguwedurl) # deguwed1.raise_for_status() # deguwedso1 = BeautifulSoup(deguwed1.text, 'lxml') # deguwedurl1 = 'https://weather.naver.com/today/06140530' # 날씨2 주소 # deguwed11 = requests.get(deguwedurl1) # deguwed11.raise_for_st...
from DNA import * overlap_length = 3 strands = read_fasta_file() suffixes = {} prefixes = {} for strand in strands: suffix = strand.sequence[-overlap_length:] prefix = strand.sequence[:overlap_length] if suffix in suffixes: suffixes[suffix] = suffixes[suffix] + [strand.title] else: ...
data = input('Data de nascimento: ') dia, mes, ano = data.split('/') meses = {1: 'Janeiro', 2: 'Fevereiro', 3: 'Março', 4: 'Abril', 5: 'Maio', 6: 'Junho', 7: 'Julho', 8: 'Agosto', 9: 'Setembro', 10: 'Outubro', 11: 'Novembro', 12: 'Dezembro'} print ('Você nasceu em:') print ('%s de %s de %s' % (dia, ...
""" This file opens, converts and compresses the wav file into a usable MFCC for our application. """ import librosa def mfcc(wav_file): # Read out audio range and sample rate of wav file audio_range, sample_rate = librosa.load(path=wav_file, sr=None) hop_length = 256 #this value is based on the KI1-Lab w...
#!/usr/bin/env python3 #----------------------------------------------------- # original author: Andrea Lucaroni # Revision: $Revision: 1.3 $ # Last update: $Date: 2012/05/22 08:22:04 $ # by: $Author: taroni $ #----------------------------------------------------- from __future__ import print_...
print("CALCOLO SISTEMI CON IL METODO DI CRAMER") print() print("numero di incognite:") m = input() if m == "2": while True: #valori dell'eq cx1 = int(input("inserire coeff di x (prima eq.)")) cy1 = int(input("inserire coeff di y (prima eq.)")) tn1 = int(input("inserire coeff noto (prima eq.)")) cx2 = int(in...
class Animal: def __init__(self, name, legs): self._hunger = 5 self.name = name self.legs = legs def breathe(self): print("Breathing in ...") print("Breathing out...") self._hunger += 0.1 def eat(self): print("Nom nom nom") self._hunger = 8 ...
""" #README Some information on running the computer vision algorithm ------------------------------------------------------------------- RUNNING of the program The program is setup in such a way that it should be trivial to run, and even adapt for new sets of images. 1. Make sure the set of...
#enter the values total1 = float(input("Enter the total cost: ")) total2 = float(input("Enter the amount of money you paid: ")) c = float(total2 - total1) c1 = c*100 c2 = round(c1/5.0)*5.0 n = c2//200 r1 = c2%200 n2 = (r1//100) r2 = r1%100 n3 = (r2//25) r3 = r2%25 n4 = (r3//10) r4 = r3%10 n5 = (r4//5) #print v...
# -*- coding: utf-8 -*- import sys from twilio.rest import Client class SmsSend(): def sendSms(self,smstext): self.account_sid = "ACd4d865c7dd7d7a6e74713d94aec45659" self.auth_token = "6145c0d0768e989245b210dbe75c2888" self.client = Client(self.account_sid, self.auth_token...
#set creating from list x=[1,1,1,2,2,2,2,3,3,3,3,3,4,5] set(x) #union y={1,2,3,22,23,24,25,26} xy-x | y #intersection xxyy=x $ y #minus z=x-y #x^y z1=x^y
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('round_robin.views', url(r'round_robin/(?P<robin_id>[0-9])$', 'round_robin'), )
# -*- coding: utf-8 -*- # Copyright (C) 2013 Yahoo! Inc. All Rights Reserved. # # 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...
import paho.mqtt.client as mqtt import os def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected success") else: print("Connected fail with code",{rc}) client = mqtt.Client() client.username_pw_set(username="perri",password="sabor4") client.on_connect = on_connect port = str...
import torch import numpy as np def train_cam(loader, victim_model, attack_model, optimizer, criterion, lambda_, device): victim_model.eval() attack_model.train() corrects = 0 for x, y in loader: x = x.to(device).float() y = y.to(device).long() optimizer.zero_grad() v...
from flask import Flask, url_for, redirect, render_template, request import requests import json import hashlib, binascii, time app = Flask(__name__) @app.route('/') def show_index(): return redirect("/static/index.html", code=302) @app.route('/car') def request_car(): carId = request.args.get('carId') i...
# Numeric data types - # int, float, complex, Decimal # int - numbers without fractions, significantly faster computations compared to float # float - numbers with fractional parts # int - there's no limit the size of values you can store in Python int # float - max float value is limited and also for it's min value...
import random from enum import Enum, unique @unique class Weather(Enum): SUNNY = 1 CLOUDY = 2 RAINY = 3 def __str__(self): return self.name @staticmethod def pick_random(): return random.choice(list(Weather))
import pickle cars=["nano","bugatii","porche","bmw"] file="mycars.pkl" fileobj=open(file,'wb') pickle.dump(cars,fileobj) #how to depickle file="mycars.pkl" fileobj=open(file,'rb') mycar=pickle.load(fileobj) print(mycar)
import unittest from tensor import * class TestTensor(unittest.TestCase): """ basic operation test """ def test_select(self): data = np.array(range(0, 9)).reshape(3,3).astype('int') a = Tensor(data, autograd=True) b = a.select_index(0, 1) c = a.select_index(1, 1) ...
# -*- coding:utf-8 -*- import time, random, string, urllib2, cgi, hmac, hashlib class oauth(): oauth_params={} request_token_url = 'http://gdd-2010-quiz-japan.appspot.com/oauth/f769083a642cab4135939e68' def __init__(self): self.oauth_params = { "oauth_consumer_key": 'f769083a642c...
import time import requests from behave import * from configuration import CONFIGURATION from utils.enums.config import config from utils.enums.field_type import FieldType from utils.enums.payment_type import PaymentType from utils.enums.request_type import RequestType, request_type_response, request_type_applepay f...
n = input() a = map(int, raw_input().split()) a.sort() j = len(a) - 1 i = 0 sum1 = a[i] sum2 = a[j] if n > 1: while abs(i - j) != 1: if sum2 > sum1: i += 1 sum1 += a[i] else: j -= 1 sum2 += a[j] if sum2 > sum1: print n - j else: ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # SMGP v3.0 api file import sys import os import socket import struct import hashlib import binascii import time import datetime import select import MySQLdb as mysql import random import redis MEMBER_LEVEL_KEY = 'tyrant:L:%d' conn = mysql.connect("localhost",user="tyrant"...
import os from flask import Flask from flask_admin import Admin import models import views app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQL_ALCHEMY_CONNECTION', 'postgresql://localhost/campaign_finance') models.db.init_app(app) admin = Admin(app, url='/', name='Campaign Finance', templa...
# Define here specific loaders for your models # # See documentation in: # https://docs.scrapy.org/en/latest/topics/loaders.html from scrapy.loader import ItemLoader from itemloaders.processors import MapCompose, Compose, TakeFirst def select_spec(spec_list, loader_context): label = loader_context.get('label') ...
class TransitionDatapoint: def __init__(self, curr_obs, action, next_obs, y, curr_state, next_state, action_prob, policy_index, step, reward): """ :param curr_obs: Current observation on which action is taken :param action: Action that was taken on current observation :param next_ob...
# Initial List nums = [0, 0, 2, 3, 4, 4] # List of items to remove nums2 = [] # # a # for # if # previous = "a" for current in nums: if current == previous and previous != "a": nums2.append(current) previous = current # # # Removing items in nums2 from nums for i in nums2: nums.remove(i) print...
import logging from flowview.metadata_manager import MetadataException from flowview.shell_executor import ShellException from flowview_handler import FlowviewHandler logger = logging.getLogger(__name__) class CleanupHandler(FlowviewHandler): """ Handler fpr cleaning up Hive table, metadata, HDFS directories ...
import aiomas import asyncio import datetime import logging import pytz from common.config import config log = logging.getLogger('common.rpc') #CODEC = aiomas.codecs.MsgPack CODEC = aiomas.codecs.JSON EXTRA_SERIALIZERS = [ lambda: (datetime.datetime, lambda t: t.timestamp(), lambda t: datetime.datetime.fromtimestam...
n = int(input()) dp = [j for j in range(n + 1)] print(dp) for idx, value in enumerate(dp): if idx == 0: continue if idx == 1 or idx == 2: dp[idx] = 1 continue dp[idx] = dp[idx - 1] + dp[idx - 2] print(dp[n])
<li> It is a Syntax Error if HasDirectSuper of |MethodDefinition| is *true*. </li> <li> It is a Syntax Error if PropName of |MethodDefinition| is `"prototype"`. </li>
# -*- coding:utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import sys import types from io import StringIO from . import constants as C from . import utils class Config(object): def clone(self): ...
__author__ = 'danielk' import sys,re,zipfile,os import hashlib ############################################################################### # # This script should help build RPM zip file # ############################################################################### def ExtarctVer(FullPath): MatchPattern=re...
def nTerm(N): n = 0 if(N % 2 == 0): n = (N * N) - 1 else: n = (N * N) + 1 print(n); N = 9 nTerm(N)
# -*- coding: utf-8 -*- from odoo import models, fields, api class project_project(models.Model): _inherit = 'project.project' @api.model def _default_user_id(self): return [(4, self.env.uid)] # supervisior_id = fields.Many2one("res.users", "Supervisor") supervisor_id = fields.Many2many...
import os import numpy as np import matplotlib.pyplot as plt import Regression_Utils def get_lick_events(base_directory, preceeding_window=10, following_window=20): # Load Downsampled AI downsampled_ai_matrix = np.load(os.path.join(base_directory, "Downsampled_AI_Matrix_Framewise.npy")) number_of_frames...
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from sklearn.preprocessing import StandardScaler import glob from spatial_bin import bin_spatial # Color Feature from color import color_hist # Color Feature import pickle as pkl from get_hog import get_hog_features def e...
#!/bin/env python import unittest from budget import Budget import psycopg2 from pyyamlconfig import load_config class TestBudget(unittest.TestCase): @staticmethod def run_query(query): config = load_config('tests/test_config.yaml') with psycopg2.connect( dbname=config.get('databa...
""" O(n) prev 用来记录前一个range的结束位置 """ class Solution(object): def findMissingRanges(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: List[str] """ result = [] nums.append(upper+1) pre = lower - 1 ...
import os import requests from services import generateEncryptedData test_url = "https://core.newebpay.com/MPG/mpg_gateway" data = generateEncryptedData() MerchantID = os.getenv('MerchantID') session = requests.Session() r = session.post(test_url, data={"MerchantID": MerchantID, "...
import numpy as np import tensorflow as tf from DataUtil2 import DataUtil import copy class Fism: def __init__(self, adv = False, alpha = 0.5): self.user_num = 6040 self.item_num = 3706 self.K = 64 self.batch = 1024 self.max_len = 2313 self.l2_reg = 5e-6 self...
import jieba # # sentence = '我喜欢上海东方明珠' # # cut_all=True 全模式 # w1=jieba.cut(sentence,cut_all=True) #全模式、精准模式、搜索引擎模式 # for item in w1: # print(item) # print('-'*20) # # cut_all=False 精准模式,依赖分词的优先级 # w2=jieba.cut(sentence,cut_all=False) #全模式、精准模式、搜索引擎模式 # for item in w2: # print(item) # print('-'*20) # # 搜索引擎模式 ...
import datetime import sys import os.path from . import dsl from . import daterange from . import generate_timetable from . import parse_coursefile def parse_date(text): split = text.split('-') assert(len(split) == 3) return tuple(map(int, split)) def main(): args = sys.argv[1:] if len(args) > 2 and args[1] == ...
s=input() k=[] for i in s: if(i!='+'): k.append(int(i)) else: k.sort() r="" for i in k: r=r+str(i)+'+' else: print(r[:-1])
# Generated by Django 3.0.5 on 2021-06-26 16:51 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('ORM'...
#!/usr/bin/env python ''' Tornado server for Cesium map module Samuel Dudley Jan 2016 ''' import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import logging from config import SERVER_INTERFACE, SERVER_PORT, APP_SECRET_KEY, WEBSOCKET, BING_API_KEY, APP_DEBUG, APP_PREFIX ...
import os import numpy as np from scipy.interpolate import interp1d import sys sys.path.append('./baseTools') from plotClass import plotCLASS class sMsNormCalc(): def __init__(self, deBrogWL, scatAmpFolder, NpadBins): self.plc = plotCLASS() self.atomTypes = ["carbon", "nitrogen", "oxygen", "io...
from PyObjCTools import NibClassBuilder ''' FIXME: merge nib files or load differently. from https://pythonhosted.org/pyobjc/api/module-PyObjCTools.NibClassBuilder.html: Deprecated since version 2.4: Use of this module is deprecated because it cannot be used with modern versions of Xcode (starting at Xcode 4.0), and...
from tkinter import * import tkinter.ttk as ttk root = Tk() # Tk class 호출, 그 안의 함수 및 변수 사용 root.title("Nado GUI") # 타이틀 설정 root.geometry("640x480") # 프로그램 창 크기, 가로 * 세로, 등장 위치 좌표 # root.geometry("640x480+300+100") # 가로 * 세로 + x좌표 + y좌표 values = [str(i)+"일" for i in range(1,32)] combobox = ttk.Combobox(root, height=5,...
import cv2 import numpy as np def main(): img=np.zeros((512,512,3),np.uint8) img[np.where((img==[0,0,0]).all(axis=2))]=[0,255,255] cv2.putText(img,"''THANK YOU''",(50,250),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,0),10) cv2.imshow("word",img) cv2.waitKey(0) cv2.destroyWindow("word") cv...
import QuantLib as ql import pandas as pd import numpy as np import scipy from scipy import stats import scipy.integrate as integrate from numpy import exp, log, pi, sqrt, real import plotly.graph_objects as go import argparse from scipy.optimize import minimize, Bounds, least_squares, root import datetime class Hesto...
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Linear Algebra import numpy as np # Loading + Cleaning import pandas as pd pd.set_option('max_rows',5) # Visualization import seaborn as sns # ML from sklearn import linear_model # In[ ]: # We start by loading the data train_d = pd.read_csv('../input/train.csv') tr...
from django.db import models from django.contrib import admin # Create your models here. class Project(models.Model): title = models.CharField(max_length=200, help_text="the title of this project, usually the same as the book, e.g. Schaum's German Grammar") path = models.CharField(max_length=254, help_text="th...
# Script to display your Project Euler friends and the problems they've solved, in order of difficulty rating import sys import mechanize import time from bs4 import BeautifulSoup import xml.etree.ElementTree as ET import operator # Version if sign in, passing in the browser # so I can use the same sign in for othe...
#!/usr/bin/env python # coding: utf-8 import os import shutil import csv import cv2 import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument("datasetdir") parser.add_argument("dagmfolder") args = parser.parse_args() datasetdir = args.datasetdir # replace this with the dataset direc...
print('Criando um dicionario para armazenar os dados de um carro...') carro = { 'marca' : 'Hyndai', 'modelo' : 'HB20', 'ano' : 2015, 'motorização' : 'Automático', 'acessórios' : [], } print('Dicionarios criado!', carro) carro['ano'] = 2018 carro['modelo'] = 'Hb20 R-Spec' print('Troquei de carr...
import wpilib from wpilib.doublesolenoid import DoubleSolenoid class DualMotorGearbox(): def __init__(self, channel1, channel2): self.motor1 = wpilib.VictorSP(channel1) self.motor2 = wpilib.VictorSP(channel2) self.isInverted = False def pidWrite(self, output): self.mot...
import threading import time from environnement import * def AddBotToEnv(env,V): for bot,param in V.items(): # add here if new class are created if bot == "mirai0": Mirai=MiraiBot0(0) env.AddNewBot(Mirai,param[1]) if bot == "mirai1": Mirai=MiraiBot1(0) ...
""" #---------------------------------------------------------------------- # This file is part of "Soft Cluster EX" # and covered by a BSD-style license, check # LICENSE for detail. # # Author: Webber Huang # Contact: xracz.fx@gmail.com # Homepage: http://riggingtd.com #------------------...
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column from sqlalchemy.types import CHAR, Integer, String from sqlalchemy.ext.declarative import declarative_base Base=declarative_base() class Product(Base): __tablename__='Product' id = ...
'Nalanda', 'Patna Sahib', 'Pataliputra', 'Supaul ', 'Araria ', 'Kishanganj ', 'Katihar ', 'Purnia ', 'Madhepura ', 'Begusarai ', 'Khagaria ', 'Bhagalpur ', 'Banka ', 'Munger ', 'Valmiki Nagar ', 'Paschim Champaran', 'Purvi Champaran ', 'Sheohar ', 'Sitamarhi ', 'Madhubani ', 'Jhanjharpur ', 'Darbhanga ', 'Muzaffarpur '...
# default separator (whitespace) print("a b".rsplit()) #print(" a b ".rsplit(None)) #print(" a b ".rsplit(None, 1)) #print(" a b ".rsplit(None, 2)) #print(" a b c ".rsplit(None, 1)) #print(" a b c ".rsplit(None, 0)) #print(" a b c ".rsplit(None, -1)) # empty separator sh...
__author__ = 'ravi' info = dict(name='python', version='2.7', author='rossum') """ updating an element of the dict """ if 'version' in info: info['version'] = '3.3' """ add a new element to the dict """ info['release'] = 'spherical cow' print info.values() print info.keys() print info.items() """ for k in sorted...
import hashlib def hash(boxID, coin_name, public_key, private_key, webdev_key, amount, period, amountUSD, userID, language, iframeID, orderID, width, height): user_format = 'MANUAL' values_to_combine = [ str(boxID), coin_name, public_key, private_key, webdev_key, ...
import sys import site import os site.addsitedir(os.path.join(os.path.dirname(__file__), 'env/local/lib64/python3.4/site-packages/')) sys.path.insert(0, '/var/www/html/ClosingPage') activate_env = os.path.expanduser(os.path.join(os.path.dirname(__file__), 'env/bin/activate_this.py')) exec(open(activate_env).read(), d...
#-*- coding:utf-8 -*- import urllib.request letter = open('./letter.txt') letter_str = letter.read() letter.close() print(letter_str) connection = urllib.request.urlopen( 'https://activity.lagou.com/activityapi/basic/ifLogin') data = connection.read() connection.close() print(data.decode("utf8"))
from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier import pandas as pd def knncls(): """ knn预测用户签到位置 :return:None """ # 读取数据 data = pd.read_csv("./facebook-v-predicti...
# coding=utf-8 def sum2(nums): result = 0 if len(nums) == 0: result = 0 elif len(nums) < 2: result = nums[0] else: result = nums[0] + nums[1] return result
from django.shortcuts import render from django.views.generic.detail import DetailView from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from components.models import Component, Category from datetime import datetime def components_page(request): context = { ...
from rdkit import Chem from rdkit.Chem.Draw import IPythonConsole import numpy as np import pandas as pd def mol_adj_1(smiles_txt): mol = Chem.MolFromSmiles(smiles_txt) mol = Chem.AddHs(mol) atoms = [atom.GetSymbol()for atom in mol.GetAtoms()] adj_mt_1 = np.zeros((len(atoms),len(atoms))) ...
# -*- coding: utf-8 -*- """ Created on Sun Oct 26 17:22:37 2014 @author: francescocorea """ import cPickle as pickle import matplotlib.pyplot as plt import numpy as np with open('tokeniser_stats.pkl', 'rb') as pfile: results = pickle.load(pfile) #make a plot of the number of unique tokens in each method vals ...
from shared import exit_program, mqtt_client, mqtt_topic, send_message import signal import time properties = {"LOCK_MOVE_RELEASE1": [["LOCK # cz1", "car[#].cz1.lock"], ["MOVE # cz1", "car[#].move.cz1"], ...
from NetUtils import * import time sess = tf.Session() x = tf.placeholder(tf.float32, shape=[None, 224,224,3], name = "x") y = tf.placeholder(tf.float32, shape=[None], name = "y") #------------------------------------------------------------- h_conv = descriptorNet(x) h_avPool = tf.layers.average_pooli...
#coding:utf-8 ''' WebRequestUtils ---> WebRequest.py date:2021-06-23 Anchor:Levon ''' import requests from LoggerUtils.Logger import Logger class WebRequest(): def __init__(self): self.session = requests.session() self.logger = Logger() self.result = '' self.emsg = { '...
a=int(input()) for z in range(a): b=int(input()) d=[] for y in range(26): d.append(0) for y in range(10000): c=input().split() e=c[1] for x in range(len(e)): f=ord(e[x])-65 d[f]=d[f]+1 g=[] for y in range(26): if d[y]!=0: ...
from aiogram import types async def set_default_commands(dp): await dp.bot.set_my_commands( [ types.BotCommand("start", "Start bot🛫"), types.BotCommand("help", "Get help💁"), types.BotCommand("menu", "Get menu🛍"), types.BotCommand("test", "Start testing🤯"...
import re ''' 匹配边长的字符 .: 任意字符, 可以匹配任何单个字符 *: 任意个字符 +: 至少一个字符 {n}: 表示n个字符 {n,m}: 表示n-m个字符 精确匹配: \d: 匹配一个数字 \w: 匹配一个数字或字母 []: 表示范围 更精确的匹配: [0-9a-zA-Z\_]可以匹配一个数字、字母或者下划线; [0-9a-zA-Z\_]+可以匹配至少由一个数字、字母或者下划线组成的字符串,比如'a100','0_Z','Py3000'等等; [a-zA-Z\_][0-9a-zA-Z\_]*可以匹配由字母或下划线开头,后接任意个由一个数字、字母或者下划线组成的字符串, ...
# djangotemplates/crm/urls.py from django.conf.urls import url from . import views from django.urls import path from rest_framework import routers from rest_framework.urlpatterns import format_suffix_patterns from crm import views urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the...
def minimum_distance(array, n, x, y): min_distance = 999999999 for i in range(n): for j in range(i+1, n): if (x==array[i] and y==array[j]) or (y==array[i] and x==array[j]) and min_distance>abs(i-j): min_distance = abs(i-j) return min_distance arr = [3, 5, 4, 2, 6...
import argparse import timeit from build_in_methods_iterators.lesson.profiler_examples.utils import \ ( list_comprehension, generator_comprehension, generator_loop, loop_example ) def wrapper(func, *args, **kwargs): def wrapped(): return func(*args, **kwargs) return wrapped if __...
class Solution1: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) nums.sort() ans = list() # 枚举 a for first in range(n): # 需要和上一次枚举的数不相同 if first > 0 and nums[first] == nums[first - 1]: continue # c 对应的...
from django.urls import path, re_path from . import views app_name = 'manager' urlpatterns = [ re_path(r'^/?$', views.login_manager, name='login_manager'), re_path(r'^/logout/?$', views.logout_manager, name="logout_manager"), re_path(r'^/add_manager/?$', views.add_manager, name='add_manager'), re_path(r'^/add_doc...
''' requirements: pie height radius ''' #code end here BSCIT-01-0345/2018 height=int(input("Enter height of Cylinder ")) radius=int(input("Enter radius ")) pie=22/7 volume=pie*radius*radius*height print("Volume is: ") print (volume) #code end here BSCIT-01-0345/2018
# # @BEGIN LICENSE # # QCDB: quantum chemistry common driver and databases # # Copyright (c) 2007-2017 The QCDB Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of QCDB. # # QCDB is free software; you can redistribute it and/or modify # it ...