text
stringlengths
38
1.54M
# 1이 될 떄까지 # N, K <= 100,000 이므로 시간복잡도 O(X lgX) 예상 N, K = map(int, input().rstrip().split()) # 내 풀이 # > 이 풀이가 필요한 경우 # 1. 나눗셈 할 수 있는 수가 2개 이상 # 이 경우는 아님 # 1. 뺄셈 할 수 있는 수가 2개 이상 # # d의 각 원소를 그래프의 정점으로, 나눗셈 또는 뺄셈으로 수가 변화하는 것을 간선으로 생각하면, 최적 경로를 구하는데 memoization, 재귀함수, for반복문 등 요소 중 무엇이 필요한 지 알 수 있다. d = [0]*(N + 1) def ...
import pandas as pd import numpy as np from Classwork import Basic_stats salary = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52] bs = Basic_stats() b = bs.bs_median(salary) print(b) print(bs.bs_outliers(salary))
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, exceptions, fields, models, _ from odoo.addons.phone_validation.tools import phone_validation class MassSMSTest(models.TransientModel): _name = 'mailing.sms.test' _description = 'Test SMS ...
from unittest import TestCase, skip from configparser import ConfigParser import os import ticketpy from ticketpy.client import ApiException from math import radians, cos, sin, asin, sqrt def haversine(latlon1, latlon2): """ Calculate the great circle distance between two points on the earth (specified i...
from django.contrib import admin from .models import Schoola # Register your models here. admin.site.register(Schoola)
""" judgement.py -- A flask-based ratings list """ # Remaining to do: Update a rating, clean up the interface and only allow logged in users to submit a rating #Added session, url_for, escape for username login and g for global variables # adding request is accessing the request object and same for redirect from flask...
import numpy as np import time import thread import rospy from std_msgs.msg import Float32MultiArray def input_thread(a_list): raw_input() a_list.append(True) if __name__=="__main__": pub = rospy.Publisher("/sim/move", Float32MultiArray, queue_size=10) rospy.init_node("move") start = time.time()...
import sys import usb import time import struct import array import math class DeviceDescriptor(object) : def __init__(self, vendor_id, product_id, interface_id) : self.vendor_id = vendor_id self.product_id = product_id self.interface_id = interface_id def getDevice(self) : """...
import sys n = int(sys.stdin.readline()) a = [[int(i) for i in sys.stdin.readline().strip().split()] for _ in range(2)] if n == 1: print(a[0][0] + a[1][0]) else: import itertools top_accum = list(itertools.accumulate(a[0])) bottom_accum_reverse = list(reversed(list(itertools.accumulate(reversed(a[1]))...
import cv2 import pytesseract import numpy as np from PIL import ImageGrab import time pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\\tesseract.exe' img2 = cv2.imread('dtu.PNG') img1=cv2.resize(img2,(512,512)) img = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) #print(pytesseract....
# -*- coding: utf-8 -*- """ Created on Fri Mar 27 20:19:50 2020 @author: Nick Strandwitz """ ### Plots LEIS profile from ascii file output of IONTof Qtac ### Created 2/29/2020 by Strandwitz; Last modified 2/29/2020 by Strandwitz ### ### TO DO: create stable loop for overlaying multiple scans ### Some...
import ffmpeg, re, os import os.path as path if __name__ == "__main__": clip_dir = path.relpath("..\\tripartito\\clips") clip = path.join(clip_dir, 'set01\\monster_S01E01_SQ0010_SH0010_V001.mp4') output = path.join(clip_dir, 'shrinkydink.mp4') ( ffmpeg .input(clip) .fi...
import pygame class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, direction, bullet_img, SCREEN_WIDTH): pygame.sprite.Sprite.__init__(self) self.speed = 10 self.image = bullet_img self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = ...
# Generated by Django 2.0.3 on 2019-07-09 13:46 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('watchlist', '0002_remove_watchlist_date'), ] operations = [ migrations.AddField( model_name='watchl...
import random from threading import Thread import datetime import socket from errno import EAGAIN, EWOULDBLOCK from sys import exit HEADER = 10 IP = socket.gethostbyname(socket.gethostname()) PORT = 5050 main_client = "Sensor" client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) now = datetime.datetime....
import os from application import app import unittest import json class FlaskrTestCase(unittest.TestCase): def setUp(self): print "WHAT" self.app = app.test_client() self.base_url = '/ams' self.token = None print "WHAT EVEN" def tearDown(self): pass def get(self,url,args=Non...
import tornado.ioloop import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self): self.write("This is the index context route") class HelloWorld(tornado.web.RequestHandler): def get(self): self.write("Hello World, fellow pythonistas!") app = tornado.web.Application([ ...
from __future__ import print_function, absolute_import, division from numpy import * from scipy import linalg from scipy import sparse class BuilderAndSolver: use_sparse_matrices = False '''ATTENTION!! this builder and solver assumes elements to be written IN RESIDUAL FORM and hence solves FOR A COR...
import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore",category=FutureWarning) import logging log = logging.getLogger('werkzeug') import os import librosa import numpy as np import scipy from os import path from pydub import AudioSegment import matplotlib.pyplot as p...
#Uses python3 import sys, os import queue def bfs(adj, x, q, shortest): q.append(x) while len(q): x = q.pop(0) for i in adj[x]: if shortest[i] >= (int)(2e9): q.append(i) shortest[i] = shortest[x] + 1 def distance(adj, s, t): #write you...
from typing import Optional from unittest import TestCase from hummingbot.connector.exchange.btc_markets import btc_markets_constants as CONSTANTS from hummingbot.connector.exchange.btc_markets.btc_markets_order_book import BtcMarketsOrderBook from hummingbot.core.data_type.common import TradeType from hummingbot.core...
import os import sys # Make it run more easily outside of VSCode sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) import costreport.data.db_session as db_session from costreport.data.costcodes import Costcode def main(): init_db() while True: insert_a_costcode...
# ------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Austin # # Created: 13/10/2014 # Copyright: (c) Austin 2014 # Licence: <your licence> # ------------------------------------------------------------------------------...
import sys import os import argparse import struct import math, csv import numpy as np riboseqDir = os.path.dirname(os.path.realpath(__file__)) ## add current directory as rootDir sys.path.append(riboseqDir) import rphelper as rph # Workflow to get E, P, A sites occupancy on ribosomes # density files are riboshifted ...
import copy def loadDataSet(FilePath): fd = open(FilePath, "r", encoding='utf-8') dataSet = [] prMap = {} for line in fd: personName = line.split("\t")[0] list =line.split("\t")[1] pr = float(list.split("#")[0]) dataSet.append(personName) prMap[personN...
import csv import re import requests from bs4 import BeautifulSoup from datetime import datetime, timedelta import pymysql headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application' '/signed-exchange;v=b3;q=0.9', 'user-agent'...
import pya # Load technology file tech = pya.Technology() tech.load(tech_file) layoutOptions = tech.load_layout_options # Load def file main_layout = pya.Layout() main_layout.read(in_def, layoutOptions) # Clear cells top_cell_index = main_layout.cell(design_name).cell_index() print("INFO: Clearing cells...") for i ...
class GameStats: """Track statistics for rocket_game""" def __init__(self, r_game): self.settings = r_game.settings self.reset_stats() # Start Rocket Game in an inactive state. self.game_active = False # High score should not be reset with open("highscore.txt")...
import pygame from pygame.draw import * pygame.init() FPS = 30 screen = pygame.display.set_mode((800, 625)) # golo i telo circle(screen, (255, 213, 0), (400, 650), 160) circle(screen, (218, 195, 195), (400, 400), 150) # nos kista polygon(screen, (67, 37, 37), [(385, 385), (415, 385), (400, 415)]) polygon(screen, (0...
# coding=utf-8 """ DATE: 2021/5/18 AUTHOR: Yanxi Li """ import time import random # 这个不用 def random_time_v2(): a1 = (2021, 5, 16, 0, 0, 0, 0, 0, 0) # 设置开始日期时间元组(2020-04-12 00:00:00) a2 = (2021, 5, 18, 0, 0, 0, 0, 0, 0) # 设置结束日期时间元组(2020-04-13 00:00:00) start = time.mktime(a1) # 生成开始时...
#!/usr/bin/env python #_*_ coding:utf-8 _*_ ''' Created on 2018年3月24日 @author: yangxu ''' ''' DriverStatus : [ [u'Pool Name', u'docker-8:2-407767-pool'], [u'Pool Blocksize', u'65.54kB'], [u'Base Device Size', u'10.74GB'], [u'Backing Filesystem', u'xfs'], [u'Udev Sync Supported', u'...
# utf-8 # Author: ilikewind ''' extract patches from trainset to validateset. ''' import os import shutil from tqdm import tqdm from util_defined import config, hp trainset_path = [config.NORMAL_PATCHES, config.TUMOR_PATCHES] valset_path = [config.VAL_NORMAL_PATCHES, config.VAL_TUMOR_PATCHES] val_wsi_name = ['normal5...
import subprocess class Telegram: def __init__(tg_loc): self.tgcli_location = tg_loc def start(self): subprocess.Popen(self.tgcli_location
#!/usr/bin/env python import csv import pprint import sys import argparse from collections import OrderedDict import json import copy pp = pprint.PrettyPrinter(indent=0) parser = argparse.ArgumentParser(description='Format input data into a gff file.') parser.add_argument('csv_file_name', help="File for the origina...
class MonthTime: def __init__(self,year=None,month=None,time_str=None): self.year = year self.month = month if time_str is not None: self.year,self.month,_ = time_str.split('/') self.year, self.month = int(self.year),int(self.month) def __lt__(self,other): if ...
#!/usr/local/bin/python from __future__ import print_function import serial class dlmsError(Exception): def __init__(self, reason): self.reason = reason def __str__(self): return repr(self.reason) class dlms(object): def __init__(self, serial_port = "/dev/cuaU3"): self.ser = serial.Serial( port = seria...
# %% Some preparations import shutil as sh import os from datetime import date from pprint import pprint import numpy as np import plot_helper as ph import mav_log_helper as mlh Ts = 0.04 # Most probably base_dir = "/home/slovak/fishbot/test/water_tank/" test_day_dir = "fishbot/logs/" + date.today().strftime("%Y-%...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_core.actions.action import Action from rasa_core.events import SlotSet import sqlite3 class ActionSearchFaculty(Action): def name(self): ...
# -*- coding: utf-8 -*- """ Created on Sat Sep 14 09:18:05 2019 @author: jose """ def squareRootExhaustive(x, epsilon): """Assumes x and epsilon are positive floats & epsilon < 1 Returns y such that y*y is within epsilon of x""" step = epsilon**2 ans = 0.0 while abs(ans**2 - x) >= epsilon and ans*...
import hmac import sqlite3 import datetime from flask_cors import CORS from flask import Flask, request, jsonify from flask_jwt import JWT, jwt_required, current_identity class User(object): def __init__(self, id, username, password): self.id = id self.username = username self.password ...
#!/usr/bin/python import sys import re import os import numpy as np from scipy import optimize import math from bs4 import BeautifulSoup import requests from tabulate import tabulate import matplotlib.pyplot as plt from matplotlib import animation from matplotlib.ticker import AutoMinorLocator, MultipleLocator, LogLoca...
# Importing required modules from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time # Opening website chrome = webdriver.Chrome() chrome.get('https://www.livechatinc.com/typing-speed-test/#/') #Wait while website opens chrome.implicitly_wait(5) #Set timeout time f...
#! /usr/bin/env python import rospy import random from math import sqrt from threading import Thread from functools import reduce from centralized_dashboard.msg import NavigationMsg from centralized_dashboard.msg import Drive stop_flag = False class NavData: def __init__(self, topic_name='/nav_data', frequenc...
import os from tkinter import Tk, Menu, Label, Button from tkinter.filedialog import askopenfilenames from tkinter.messagebox import showinfo # from 实用主义学Python.抠图.抠除背景 import remove_bg from removebg import RemoveBg rmbg = RemoveBg('GiQrvx9AuuS6DH2Svh3JBfVK', 'error.log') def remove_bg(img_path): rmbg.remove_ba...
''' Discovery server database interface Created on Oct 19, 2016 @author: riaps ''' import typing import re import sys import functools import copy import threading import os from os.path import join from threading import RLock import parse import sched,time from Cryptodome.PublicKey import RSA from Cryptodome.Cipher...
import unittest from data_structures.queue.queue import Queue class TestQueue(unittest.TestCase): def test_has_more(self): capacity = 10 q = Queue(capacity=capacity) self.assertEqual(False, q.has_more()) for i in range(capacity): q.enqueue(i) self.assertEqu...
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2016, A...
import cv2 he='/home/zrj/Object_detection/hgo3.0/test1.jpg' he2='/home/zrj/Object_detection/hgo3.0/test2.jpg' test=cv2.imread(he) print(test.shape) test2=cv2.imread(he2) print(test2.shape) # cv2.imshow('test',test) # 166.03738 || 257.6172 || 253.83871 || 378.84848 # 1 label: c score: tensor(...
from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/$', views.admin), url(r'^search/', views.search_parts, name='search'), url(r'^contact/$', views.contact, name='contact'), url(r'^new/$', views.new_...
from django.db import models from django.utils import timezone from datetime import datetime from searchapp.custom import path_and_rename from django.dispatch import receiver from django.db.models.signals import pre_delete, post_save # Create Models here. Basic ones should be research paper(Paper), (Author), (User) # J...
import pathlib import subprocess import typer from mirumon.cli.groups.core import DEFAULT_ATTEMPTS, DEFAULT_DELAY from mirumon.cli.helpers import create_logs_dir, current_dir current_path = pathlib.Path().absolute() NSSM_PATH = current_path / "thirdparty" / "nssm.exe" SERVICE_NAME = "mirumon" group = typer.Typer()...
#!/usr/bin/env python3 import sys def main(s): # Sort the list numerically nums = [int(x) for x in s] nums.sort() print(1 if nums[-1] >= 2 * nums[-2] else -1) if __name__ == '__main__': main(sys.argv[1:])
def counting_sheep(num): base=set(['0','1','2','3','4','5','6','7','8','9']) compare=set() for i in range(100): result=str(int(num)*(i+1)) for digit in result: if digit not in compare: compare.add(digit) if compare==base: return result el...
def get_int_in_range(low,high): val=int(input()) while val<low or val>high: print("val is out of range try again") val= int(input()) return val def create_list(n,min,max): result=[] while n>0: print("enter integer in the range{}...{}:".format(min,max)) result.appe...
class DBConnectionError(BaseException): def __init__(self): self.message = "[ERROR] Connection failed. Try later" class InvalidSignInParamError(BaseException): def __init__(self): self.message = "[ERROR] Wrong mail or password. check it again" class InvalidPasswordError(BaseException): def __init__(self): ...
# -*- coding: utf-8-*- import datetime import re from client.app_utils import getTimezone from semantic.dates import DateService from chatterbot import ChatBot WORDS = ["CHAT"] def handle(text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- u...
#! /usr/bin/python __author__="Yue Luo <yl4003@columbia.edu>" __date__ ="$Feb 16, 2019" import sys from collections import defaultdict import math from count_freqs import sentence_iterator,simple_conll_corpus_iterator import numpy as np import time """ Implement the Modified Viterbi Algorithm and runs it on the ner_...
#-*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch from PIL import Image, ImageDraw import torch.utils.data as data import numpy as np import random from utils.augmentations import process_rotation_multiscale def tensor_rot_...
import fbprophet # print version number print('Prophet %s' % fbprophet.__version__) import pandas as pd import numpy as np from pandas import read_csv, to_datetime # load data train_path = '/opt/ml/processing/input/energy-train.csv' df = read_csv(train_path, header=0)[["Date", "Load"]] # summarize shape print(df.shap...
import win32com import win32com.client def makePPT(path): ppt = win32com.client.Dispatch("PowerPoint.Appplication") ppt.Visible = True #增加一个文件 pptFile = ppt.Presentations.Add() #创建页 page1 = pptFile.Slides.Add(1,1) t1 = page1.Shapes[0].TextFrame.TextRange t1.Text = "tracy" t2 = pag...
from django.db import models from django.db.models.base import Model from django.db.models.fields import EmailField from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.shortcuts import render from django.views import View from django.views.decorators.csrf impor...
from flask.cli import AppGroup from .users import seed_users, undo_users from .stories import seed_stories, undo_stories from .micro_stories import seed_micro_stories from .formats import seed_formats, undo_formats from app.models import db # Creates a seed group to hold our commands # So we can type `flask seed --hel...
from pioneer_sdk import Pioneer import numpy as np import cv2 import time pioneer_mini = Pioneer() def img_decorate_with_text(image, text, org=(50, 50,)): font = cv2.QT_FONT_NORMAL font_scale = 1 color = (0, 255, 0) thickness = 1 image = cv2.putText(image, text, org, font, font_scale, color, thickness, cv2.LI...
# -*- coding: utf-8 -*- from flask import Flask,session,g,render_template,request,redirect,url_for,escape import sqlite3 import hashlib from werkzeug import secure_filename app = Flask(__name__) DATABASE = './test.db' app.secret_key = 'a' def get_db(): db = getattr(g,'_database',None) if db is None: ...
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC # 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 above copyright notice, # this list...
# coding: utf-8 # Writer: bao # Date: 2018-11-30 import json import requests import re import pymysql from bs4 import BeautifulSoup import time try: conn = pymysql.connect(host='localhost', user='root', passwd='mysql1820', db='bilibili', use_unicode=True, charset="utf8") except Exceptio...
import os import reframe.utility.sanity as sn from reframe.core.pipeline import RunOnlyRegressionTest class OpenfoamExtendBaseTest(RunOnlyRegressionTest): def __init__(self, check_name, check_descr, **kwargs): super().__init__('OpenfoamExtend_%s' % (check_name), os.path.dirname(_...
class Node: def __init__(self,data, nxt=None): self.data = data self.nxt = nxt class linkedList: def __init__(self,head=None): self.head = Node(head) def insert_head(self, val): newNode = Node(val,self.head) self.head = newNode def insert_tail(self,val): ...
#!/usr/bin/env python # # Name: gendershosts.py # Desc: Splunk search command for parameterizing searches based on Genders queries # # Quickly hacked together by Wil Cooley <wcooley@pdx.edu> # import re import sys from subprocess import PIPE, STDOUT import subprocess def err(msg="Undetermined error"): print "ERRO...
def checkio(text, word): text=text.lower() l = len(word) first_letter= word[0] text_list = [[c for c in l.replace(" ", "")] for l in text.split("\n")] rows = len(text_list) for i in range(rows): for j in range(len(text_list[i])): if text_list[i][j] == first_letter: ...
import pytest from astropy.io import fits from astropy.utils.data import download_file from jdaviz.utils import PRIHDR_KEY @pytest.mark.remote_data def test_2d_parser_jwst(specviz2d_helper): fn = download_file('https://stsci.box.com/shared/static/exnkul627fcuhy5akf2gswytud5tazmw.fits', cache=True) # no...
# To do: Briefs, Parameters and beta test """ Problem: https://en.wikipedia.org/wiki/Convex_hull Solutions: Brute force DnC """ from typing import Iterable, List, Set, Union class Point: """ Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) ...
""" Contains the Game Interface class. """ import sys import pygame as pg from game import * """ Import Multiple AIs """ total_trial = 1000 class Game_Count(Game): def __init__(self): super().__init__(mute = True) def reset(self): self.close = False self.winner = None self...
# Cette programme prends les résultats d'un vote comme données et retourne le résultat: # unanimité, majorité claire, majorité simple, la motion ne passe pas. Un fonction est # utiliser pour calculer le pourcentage et les conditions détermine la résultat. def vote_pourcentage(ch): ''' paramètres (un chaîne des cha...
import turtle colors=["red","blue","purple","green","orange","pink"] t=turtle.Pen() turtle.bgcolor("black") for x in range(360): t.pencolor(colors[x%len(colors)]) t.width(x/100+1) t.forward(x) t.left(59)
# Generated by Django 3.0.3 on 2020-10-25 01:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bagel_site', '0012_auto_20201025_0036'), ] operations = [ migrations.AlterField( model_name='li...
import codecs n = 10**8 primes = [] for i in codecs.open('prime.txt', 'r', 'utf-8'): if int(i.strip()) < n: primes.append(int(i)) else: break print ('read primes over') d = {} for i, p in enumerate(primes): if i % 100 == 0: print (i, p) k = 0 for kk in range(p, n+1, p): ...
# -*- coding: utf-8 -*- """ Created on Sun Aug 19 22:19:10 2018 @author: brown """ def closest_power(base, num): ''' base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base**exponent is closest to num. Note that the bas...
import struct import sys offset = struct.pack("Q", 0x7fffffffe5e0) shellcode = b"\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05" payload = [ b"\x90"*49, shellcode, b"\x90"*60, offset ] payload = ...
import httplib httpconn = httplib.HTTPConnection("www-130.ibm.com") httpconn.request("GET", "/developerworks/index.html") resp = httpconn.getresponse() if resp.reason == "OK": resp_data = resp.read() print resp_data httpconn.close()
#!/usr/bin/python3 """ A simple LSP server for "efree", written on pygls, which provides a framework for writing LSP servers. efree identifies lower-case "e" in a document and highlights it. """ # ------------------------------------------------------------------------------- # Imports # -----------------------------...
#coding:utf-8 ''' 0 4位数年 2008 1 月 1 到 12 2 日 1到31 3 小时 0到23 4 分钟 5 秒 0到61 (60或61 是闰秒) 6 一周的第几日 0到6 (0是周一) 7 一年的第几日 1到366 (儒略历) 8 夏令时 -1, 0, 1, -1是决定是否为夏令时的旗帜 0 tm_year 2008 1 tm_mon 1 到 12 2 tm_mday 1 到 31 3 tm_hour 0 到 23 4 tm_min 0 到 59 5 tm_sec 0 到 61 (60或61 是闰秒) 6 tm_wday 0到6 (0是周一) 7 tm_yd...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KoubeiMarketingCampaignRetailDmSetModel(object): def __init__(self): self._campaign_end_time = None self._content_id = None self._operate_type = None @property de...
""" Multi-file config parser for any library. Not usually to be used alone, usually you ready from the parser into a settings file. Changes can be made by creating / updating a ~/.{{file_name}} in your home directory or an /etc/.{{file_name}} file for system wide settings. Imports are in the following order: 1. Home ...
import telnetlib import getpass host = '192.168.122.10' user = input('Enter the username:') #it will ask for the password without echoing it at the console #the script must be run at the console and not in PyCharm or IDLE #password = 'cisco' password = getpass.getpass('Enter the password:') tn = telnetlib.T...
#Nick Zapata - Daily lesson - 2/8/18 for counter in(1, 20): if (counter % 3 == 0) and (counter % 5 == 0): print('usb device') elif (counter % 3 == 0): print('usb') elif (counter % 5 == 0): print('device') else: print(counter)
''' Created on Mar 27, 2014 do: binarize label feature -> init name @author: cx ''' import site import pickle site.addsitedir('/bos/usr0/cx/PyCode/Geektools') site.addsitedir('/bos/usr0/cx/PyCode/cxPyLib') site.addsitedir('/bos/usr0/cx/PyCode/QueryExpansion') site.addsitedir('/bos/usr0/cx/PyCode/Supervised...
from datetime import datetime from sqlalchemy import Column, Integer, String, ForeignKey, Text, Boolean, \ DateTime, MetaData from sqlalchemy.orm import relationship from app import db convention = { "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # class Solution: # def addTwoNumbers(self, l1, l2): # # """ # :type l1: ListNode # :type l2: ListNode # :rtype: ListNode # """ # # len1 = le...
import dash from dash import html, dcc from dash.dependencies import Input, Output, State, MATCH, ALL import dash_bootstrap_components as dbc # conda install -c conda-forge dash-bootstrap-components import pandas as pd import numpy as np import plotly.graph_objects as go import random from Mother import Mother from Da...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import torch import torch.nn.functional as F import math from .utils import TensorProperties, convert_to_tensors_and_broadcast def diffuse(normals, color, direction) -> torch.Tensor: """ Calculate the diffuse component of...
## imports from EnzymePh import * import pandas as pd import argparse import string import numpy as np import pickle import joblib import string from sklearn.ensemble import RandomForestRegressor,ExtraTreesRegressor ## argumnet parser parser = argparse.ArgumentParser() parser.add_argument('--input_csv', default='inp...
import pandas as pd import numpy as np import sklearn from sklearn import linear_model import matplotlib.pyplot as plt #from matplotlib import style #import seaborn as sns data = pd.read_csv("data.csv") print(len(data)) data = data[ ["danceability", "energy", "acousticness", "duration_ms", "popularity", "tempo",...
""" datafiles.py ============ This module provides functions to load data from csv and csv-like files into memory for easy manipulation. It makes no assumptions about downstream processing. (e.g. whether the data is intended to be used with scikit-learn). """ from collections import defaultdict import cPickle as pic...
#! /usr/bin/env python import argparse, sys, os, errno import logging logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] [%(levelname)s] %(name)s: %(message)s') def annotate_structure_diagram(args): import re pat_nucleotide = re.compile(r'^\([AUGCT]\) ([0-9\.\-]+) ([0-9\.\-]+) lwstring$') prol...
"""WS channels.""" import asyncio import hashlib import json import logging import sys from time import monotonic from typing import Callable, Dict, List import aiohttp if sys.version_info >= (3, 7): from contextlib import asynccontextmanager else: # For python3.6 from ambra_sdk.async_context_manager imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 6 23:09:27 2018 @author: gjxhlan """ # Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') year = dataset.iloc[:,:-1]...
import tensorflow as tf import numpy as np import os, time from crnn_SVNH import CRNN from dataset import Dataset from common import config def train(prev_model_path=None): # prepare dataset dataset_train = Dataset('train') dataset_test = Dataset('test') # define computing graph model = CRNN() ...
import numpy as np import matplotlib.pyplot as plt import math f = open("track_points_3.txt", "r") x = [] y = [] x_rail_1 = [] y_rail_1 = [] x_rail_2 = [] y_rail_2 = [] x_subset = [] y_subset = [] count = 0 buf = 0.8 for i in f: a = i.split() #print(a); x.append(-1*float(a[0])) #to show figure as gazebo y.appen...
# Generated by Django 3.1.4 on 2021-01-08 00:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Campus', fields=[ ...