text
stringlengths
38
1.54M
import sys; import os; from math import log def per_classify(): f = open("per_model.txt", "r", encoding="latin1"); HamSpamWeights = {} bias=0 count=0 for line in f: count += 1 if count == 1: bias = int(line) else: splitted = line.split() ...
def solution(lottos, win_nums): answer = [] removed_n = lottos.count(0) pre = set(win_nums).intersection(set(lottos)) max_ = min(6, len(pre)+removed_n) min_ = len(pre) answer = [min(6, 7-max_), min(6, 7-min_)] return answer
import time import smtpUtils import systems import utils class iplanet: badBytes = [0x0, 0xa, 0xd] nAttempts = 1 def buildBaseBuffer(self, imtaBase): filler = utils.buildBuffer(self.baseBufLen, self.badBytes) baseBuf = filler[0x0:] return baseBuf def buildBounceBuffer(self): imtaB...
from flask import Flask app = Flask(__name__) @app.route('/') def main(): return "My first flask app" app.run(port=8000)
import os # the commission cost per trade COMMISSION = 10 # the default maximum dollar amount to allocate for a trade MAX_AMOUNT = 5000 # the number of steps for scaling out of a position SCALE_OUT_LEVELS = 2 # sell half of quantity half way to the target price and the other half at the target price ##############...
import threading from time import sleep from datetime import datetime loops=[4,2] format_str='%y-%m-%d %H:%M:%S' # 用于输出一个指定格式的时间函数 def date_time_str(date_time): return datetime.strftime(date_time,format_str) def loop(n_loop,n_sec): print('线程(',n_loop,')开始执行',date_time_str(datetime.now()),'先休眠',n_se...
from django import test from django.core.urlresolvers import reverse from django.http import HttpRequest from mobile_detector import is_mobile, use_mobile, no_mobile_cookie from mobile_detector import get_mobile_cookie_name from mobile_detector.context_processors import detect_mobile __all__ = ( 'MobileUtilities...
import time from time import sleep import random import sys import os import re from imp import load_module,find_module from camera_logcat import * #Debug = True Debug = False testcaseids=[7] #TestTimes = 2000 TestTimes = 1 testStartTime = time.time(); def DeleteFile(dirName): """ delete the all dirs/files ...
# Samuel Rivera # Jan 20, 2016 # This script is meant for generating switch flurps/jalets from PIL import Image, ImageDraw from collections import OrderedDict import os from jalets import * if __name__ == '__main__': # make output folder outFolder= 'FlurpJaletSwitch/' if not os.path.exists( outFo...
from __future__ import division from otree.common import safe_json from . import models from ._builtin import Page from .models import Constants import random, time from otree.api import Currency as c # *****************************************************************************************************************...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Pre build plugin which changes source registry """ from atomic_reactor.plugin import PreBuildPlugin class ChangeSourceRegistryPlugin(PreBuildP...
import datetime from datetime import timedelta from apps.libro.models import Reserva class PruebaMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_v...
from z3 import * v = BitVec("v0", 64) S = Solver() v2 = (v & 1) + 2 v3 = v + 0x21a3937 S.add(v1 << v2 == v3) if S.check() == sat: print(S.model())
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017-18 Richard Hull and contributors # See LICENSE.rst for details. """ Tests for the :py:class:`luma.core.interface.serial.bitbang` class. """ from unittest.mock import Mock, call from luma.core.interface.serial import bitbang import luma.core.error imp...
""" The command pattern is handy in situations when, for some reason, we need to start by preparing what will be executed and then to execute it when needed. The advantage is that encapsulating actions in such a way enables Python developers to add additional functionalities related to the executed actions, such as ...
# Generated by Django 3.1.4 on 2020-12-28 16:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('teachers', '0003_auto_20201228_2153'), ('schedule', '0006_auto_20201228_2153'), ] operations = [ migrations.AlterUniqueTogether( ...
from src import tokens import re class LexicalAnalyzer(): isComment = False file = None reserved = None table = [] def __init__(self, file, reserved): self.file = file self.reserved = reserved def tete(self): self.delComments() self.splitTokens() def isIn...
# 4.4.5.translate_stop_1.py from Bio.Seq import Seq mRNA = Seq("AUGAACUAAGUUUAGAAU") ptn = mRNA.translate() print(ptn) ## MN*V*N
#Search in a Rotated Sorted Array class Solution(object): def search(self, nums, target): def pivotpoint(nums): for i in range(len(nums)-1): if nums[i] > nums[i+1]: return i+1 return -1 def bin(nums,targe...
#5-1 conditinal test housemates = ["jasmine","elyse","steve","john","zack","brock","christina"] while True: search_name = input("please enter the name of your housemates : ") if search_name == 'done': print("good-bye!") break if search_name in housemates: print(search_name + ", is your hous...
import random playerScore = 0 compScore = 0 def computerPlay(): compSelections = ["rock", "paper", "scissors"] compSelection = random.choice(compSelections) return compSelection def userPlay(): while True: playerSelection = input("Please enter Rock, Paper, or Scissors: ").lower() if...
# -*- coding: utf-8 -*- # # Copyright 2012 Zuza Software Foundation # # This file is part of Pootle. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at y...
import urllib.request as ur import json import logging, time, os from logging.handlers import TimedRotatingFileHandler from threading import Thread from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path # Logger to handle rotating log files logger = logging.getLogger("scraper") logger.setL...
import zerorpc import logging logging.basicConfig() c = zerorpc.Client() c.connect("tcp://127.0.0.1:4242") print c.hello("RPC")
# -*- coding: utf-8 -*- # lenet_mnist.py import numpy as np import matplotlib.pyplot as plt from keras import backend as K from keras.optimizers import SGD from sklearn import datasets from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.preprocessing imp...
import threading import socket import random from os.path import join import json with open(join("server", "parameters.json")) as file: parametros = json.load(file) class AdminJuego(): # def __init__(self): # # CLIENTES # # el turno_actual parte asi dado al funcionamiento de la funcion cam...
import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): ## Add Liquor Button self.hi_there = tk.Button(self) self.hi_there["text"] = "Add Liquor...
from tkinter import * from shared import * from snake import * import time class SnakeGame(Tk): def __init__(self): super().__init__() self.title('Snake Game') self.gameover_screen = GameoverScreen(self, Shared.WIDTH, Shared.HEIGHT) self.gameover_screen.grid(row=0, column=0, sticky...
""" This problem was asked by Microsoft. Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down. For example, given the following matrix: [['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ...
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
def valid_ip(ip_address): # This is needed if the user enters an IP address with an invalid syntax. octets = ip_address.split(".") if len(octets) != 4: return False # Convert octet list entries to Integers for i, octet in enumerate(octets): try: octets[i] = int(octet...
from cod_pilha import Pilha from cod_pilha import StackUnderflow @given('o tamanho da pilha sendo {tam:d}') # {tam:d} = Variavel tam com um decimal def Tamanho_da_pilha(context, tam): # Variavel deve constar aqui context.tamanho = tam @when('crio uma pilha') def Cria_pilha(context): context.pilha = Pilha(...
from identifier.models import Musics from django.http import HttpResponse from googleapiclient.discovery import build import json import datetime # REST from rest_framework.decorators import api_view from rest_framework.response import Response from django.shortcuts import render, redirect from django.http import Http...
# _*_ coding:utf-8 _*_ # --------------------------- # Python_Version 3.6.3 # Author: zizle # Created: 2020-05-18 # --------------------------- import os from PyQt5.QtCore import QUrl, QRectF, Qt, QSize, QTimer, QPropertyAnimation,\ QPointF, pyqtProperty from PyQt5.QtGui import QPixmap, QColor, QPainter, QPainterP...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script for measure work timings (benchmarking) any number of CMS backends (data storage) as MySQL, MongoDB, ZODB (3.9.7). """ __author__ = 'Cheltsov Ivan (civ@ploha.ru)' __copyright__ = 'Copyright 2012, Cheltsov Ivan' __version__ = '0.1.0' __license__ = 'LGPL' ...
try: from setuptools import setup except ImportError: from distutils.core import setup # Get the long description from the README file try: long_description = open('README.md', 'r').read() except Exception as e: raise e DEPENDENCIES = [ 'pymove>=2.6.1', 'osmnx>=1.0.0' ] setup( name='pymov...
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.get_title, name='get_title'), url(r'^search/(?P<pk>[0-9]+)/$', views.paper_detail, name='paper_detail'), url(r'^journals/$', views.journal_list, ...
import Gyro as gyro import miniPiTFT as tft import SandDisplay as display import RotaryEncoder as rotery import time class SandGlass: max_time = 15 coe = 0.5 mid = 64 right_amount = 0 prev_time = None # direction: -1, 0, 1 prev_direction = 0 prev_vertical = 1 def __init__(self):...
# -*- coding: utf-8 -*- from odoo import api, models, fields class CertSunat(models.Model): _name = "cert.sunat" key_public = fields.Text("Cert. PUBLIC",required=True) key_private = fields.Text("Cert. PRIVATE",required=True) expiration_date = fields.Date(string='Fecha de expiración',required=True) ...
Dictionry={"Gandhar Acharya": "Meaning: The Best Boss" , "Gulshan" : "Meaning: Popat Laal" , "Aansh" : "Meaning: Best Friend"} Name=input("Enter Word:") print (Dictionry[Name])
# Generated by Django 2.2.3 on 2020-05-19 14:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tabulation', '0001_initial'), ] operations = [ migrations.AlterField( model_name='hatchrecord', name='out_machine', ...
#!/usr/bin/env python3 import requests from requests_ntlm2 import HttpNtlmAuth from base64 import b64encode as be, b64decode as bd import argparse from time import sleep, time from datetime import datetime import urllib3 import base64 import re urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) from...
# -*- coding: UTF-8 -*- import sys import math import operator from __future__ import division # 避免整数相除 # sys.path.append("../util") import com.py.ml.mooc_begin_with_rec_alg.util.reader as reader def transfer_user_click(user_click): """ get item by user_click :param user_click: dict key:user_id, value:i...
#!/usr/bin/python3 x=1 while x!=7: # x!=0 condition doesnt execute else if x%7==0: break print(x) x+=1 else: print("Else of while")
#Birthday Paradox Simulator from random import * from math import * def BDSim(N=100): ppl2BD = [] for iterval in range(N): ppl2BD.append(0) BDList = [] matchFound = False while not matchFound: #add a Bday BDList.append(floor(365*random())) ppl2BD[iterval] += 1 #Check for a match with new day ...
import bs4 as bs import urllib.request import re import nltk import spacy from spacy import displacy from collections import Counter import en_core_web_sm #function that give the part of speech!!! def return_parts_of_speech(word): nlp = spacy.load("en") doc = nlp(word) for token in doc: ...
print("Example: For positive numbers") # Python program to calculate the square root num = float(input("Enter a number: ")) num_sqrt = num ** 0.5 print("The square root of %0.3f is %0.3f"%(num, num_sqrt)) print("\n\nSource code: For real or complex numbers") # Find square root of real or complex numbers # Importing...
# # @lc app=leetcode id=131 lang=python3 # # [131] Palindrome Partitioning # from typing import List # @lc code=start class Solution: def partition(self, s: str) -> List[List[str]]: # step 1: do a DP to find out all the palindromes size = len(s) dp = [[0 for _ in range(size)] for _ in ran...
from itertools import combinations class FoxAndSouvenirTheNext(object): def __init__(self): object.__init__(self) def ableToSplit(self, value): cntOfSouvenir = len(value) if cntOfSouvenir % 2 != 0: return 'Impossible' cntOfHalfSouvenir = cntOfSouvenir / 2 ...
def unrootedTreeCount(taxa): if taxa <=0: return 1 else: return taxa * unrootedTreeCount(taxa-2) taxafile = open('C:/Users/Rajesh/PycharmProjects/CountUnrootTreesPb43/rosalind_cunr.txt', 'r') for n in taxafile: unrootedTrees = unrootedTreeCount(2*int(n)-5)%1000000 print("Distinct Unroot...
def imprime_matriz(matriz): a = len(matriz) l = len(matriz[0]) for i in range(a): for j in range(l): if not j == l - 1: print(matriz[i][j], end=' ') else: print(matriz[i][j])
import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self, context_shape, latent_shape): super(Model, self).__init__() self.LReLU = nn.LeakyReLU(0.01) #self.linear_c1 = nn.Linear(context_shape, context_shape - int((context_shape - latent_s...
import sys DEBUG = False def money(amount): rounded = round(amount, 2) short = str(rounded).index('.') > len(str(rounded)) - 3 if short: rounded = str(rounded) + '0' return '$' + str(rounded) plans = ['0', '40', '80', '100', '160', '220', 'Premium'] plan_prices = {'0': 0.0, '40': 518.0, '80': 1039.0, '100': 12...
############################ # Código desenvolvido por # # Rafael Almada # # github.com/slimkaki # # Engenharia da Computação # # Insper - 6o Sem - 2020.2 # ############################ import datetime, requests, json, sys def client(url, loop=True): print("====================================") ...
from __future__ import division import numpy as np # 线生成函数 def line(p1, p2): A = (p1[1] - p2[1]) B = (p2[0] - p1[0]) C = (p1[0]*p2[1] - p2[0]*p1[1]) return A, B, -C # 计算两条直线之间的交点 def intersection(L1, L2): D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * ...
def GetFruits(): myfile = open("fruits.txt", "r") fruits = myfile.read() myfile.close() return fruits print(GetFruits())
import numpy as np import math import matplotlib.pyplot as plt #################################################### # Parameters #################################################### k_phi = 1 #positive constant that represent the weight of phi with respect to r. k_delta = 1 #positive constant tha...
from django.shortcuts import render, redirect from .models import Admin from attendance.models import Attendance # Create your views here. isLoggedIn = False def admin_login(request): global isLoggedIn attendance = Attendance.objects.all() context = { 'attendance': attendance } if request...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import find_packages, setup # Where the magic happens: setup( name='led-control', version='1.0.0', description='WS2812 LED strip controller with web interface for Raspberry Pi', long_description=open('README.md').read(), long_descriptio...
import flask import settings # Views from main import Main from login import Login from remote import Remote from music import Music from about import About from contact import Contact from index import Index app = flask.Flask(__name__) app.secret_key = settings.secret_key # Routes login_view_func = Login.as_vie...
from django.shortcuts import render from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from .forms import RegistrationForm, EditProfileForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.aut...
import hatch_hash from binascii import unhexlify, hexlify import unittest # hatch block #1 # getblockhash 1 # 000008920bf22af181d6fbb50ab127408e8546964902467de1c21e8c011baa8e # getblock 000008920bf22af181d6fbb50ab127408e8546964902467de1c21e8c011baa8e # { # "hash": "000008920bf22af181d6fbb50ab127408e8546964902467de1...
import unittest import time, sys, os import ESCMotor, MPL3115A2, MPU9250, PCF8523 import mainPayload, mainRocket, payloadState, rocketState import pigpio import csv import random class TestESCMotor(unittest.TestCase): def test_init(self): piggy = pigpio.pi() m1 = ESCMotor.Motor(pi=piggy,...
# Pedir la nota de 9 alumnos y que diga cuantos han aprobado y cuantos suspendidos contador_aprobados = 0 contador_supendidos = 0 for cont in range(1, 10): nota = int(input(f"Escribe la nota del alumno {cont}: ")) if nota >= 5 and nota < 11: contador_aprobados += 1 elif nota < 5 and nota > 0: ...
from bluedot.btcomm import BluetoothServer from PIL import Image import pyqrcode from bluedot.btcomm import BluetoothAdapter from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 from cryptography import exceptions import base64 import time import os from signal import pause #def of global const...
# Altered and used as a base from: https://github.com/mhostetter/nhl import requests import boxscore as bs import nhl_parser as parse BASE = "https://statsapi.web.nhl.com/api/v1" RECORDS_BASE = "https://records.nhl.com/site/api" STAT_LEADERS_BASE = "https://api.nhle.com/stats/rest/en/skater/summary?isAggregate=false...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: zhangxin # Date: 2021/3/1 # Desc: # Param: # Function: class ListNode: def __init__(self,x): self.val = x self.next = None # 非递归版本 # class Solution: # # 返回合并后列表 # def Merge(self, pHead1, pHead2): # # write code here # ...
""" 传入微博url,进行解析 author:mmciel time:2019年2月9日21:07:39 """ # -*- coding:utf-8 -*- import json import re import requests def get_download_url(url): """ 传入微博url,进行解析 :param url: 传入分享链接 :return: 解析后的链接 """ # get 请求 weibo_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64;...
for number in range(3) : print("-------------------------------------------") print("I am outer loop iteration "+str(number)) # Inner loop for another_number in range(4): print("****************************") print("I am inner loop iteration "+str(another_number)) # task : Write a Pyth...
import thread # ClientList -- maintain a list of items, with access protected by a lock class Clients: def __init__( self ): self.list = [] self.lock = thread.allocate_lock() def __len__( self ): self.lock.acquire() n = len( self.list ) self.lock.release() return n def __getitem__( self, index ): ...
from flask import Flask, request, jsonify import base64 from PIL import Image from io import BytesIO from LeNet import lenet_cpu, lenet_fpga app = Flask(__name__) @app.route('/') def hello_world(): return "Hello world!" @app.route('/predict', methods=['GET', 'POST']) def get_predict_cpu_lenet(): net = request....
# Generated by Django 2.2.24 on 2021-10-30 14:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('todo', '0040_auto_20211029_1237'), ] operations = [ migrations.AddField( model_name='tasklog', name='taskCompNum', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 24 21:30:50 2020 @author: kali """ from newsapi import NewsApiClient import requests from selenium import webdriver from datetime import timedelta # from datetime import date import datetime import sys current_date = datetime.datetime.now() to_d...
from django.conf.urls import url import pickle def getPickleData(pickled): ''' Return deserialized data '''
#!/usr/bin/python """ HCE project, Python bindings, Processor Manager application. Event objects definitions. @package: dc @file crawling-optimiser.py @author Oleksii <developers.hce@gmail.com> @link: http://hierarchical-cluster-engine.com/ @copyright: Copyright &copy; 2013-2014 IOIX Ukraine @licen...
curr = 1 prev = 1 next = 0 solution = 2 while len(str(curr)) < 1000: next = curr + prev prev = curr curr = next solution += 1 print solution
S = input() def k(S): for i in range(len(S)//2): if S[i] != S[-i-1]: return False return True if k(S) and k(S[:int((len(S)-1)/2)]) and k(S[int((len(S)+3)/2)-1:]): print("Yes") else: print("No")
########################################################################## # CS 101 # Program : 6 Language quiz # Name Erik Marquez # Email eemxr9@mail.umkc.edu # PROBLEM : Lamguage quiz # ALGORITHM : # 1. Ask user for a file to open # 2. Validate the input # 3. Create two files to save to # 4. Take the data fr...
import re from source_updater_master import generate_source_regexes def test_generate_source_regexes(): test_source = lambda source_str, test_str: any(r.search(test_str) for r in generate_source_regexes(source_str)) # Match entire word assert test_source("98/1-3", "98/1-3") == True assert test_source("...
import logging from datetime import datetime logs_dir = "logs" celery_logs = "proj/logs" downloads_dir = "downloads" log_config = {"level": logging.DEBUG, "filename": ("%s/logs_%s.log" % (logs_dir, datetime.now().strftime("%Y-%m-%d"))), "format": (logging ...
from tkinter import* main = Tk() main.geometry("700x440") main.title("MyDecoder") alphabet=[] ans=[] lib = {"00":"a", "01":"b", "02":"c", "03":"d", "04":"e", "05":"f", "06":"g", "07":"h", "08":"q", "09":"w", "10":"s", "11"...
"""Includes distance utility functions This module includes the following distance utility functions: jaccard_index(cluster1,cluster2) euclidean_distance(cluster1,cluster2) standardised_euclidean_distance(data,cluster1,cluster2) chi_square_distance(data,cluster1,cluster2) Each function takes two different clusters a...
"""The matrix module.""" from random import randrange def make_random_matrix(size): """Make a quadratic matrix of a given size with random elements, where there is a single random position containing zero. size -- the size of the matrix """ if size < 0: raise ValueError('Size must ...
from django.conf.urls import url from django.urls import reverse from django.contrib import admin from changuito import views urlpatterns = [ url(r'^buy', views.add_to_cart, name='cart-add'), url(r'^remove/(?P<item_id>[-\w]+)', views.remove_from_cart, name='cart-remove'), url(r'retrieve', views.get...
import requests r=requests.get('http://openapi.seoul.go.kr:8088/58795458696a6273393255484a5249/json/InfoTrdhlSelng/1/500/201606') d=r.json() Tues=[] for index, data1 in enumerate(d['InfoTrdhlSelng']['row']): Tues.append(data1['TUES_SELNG_RATE']) import matplotlib.pyplot as plt plt.title('Tuesday sales') plt...
import os import pickle from conf import sttings # 保存数据 def save_data(obj): # 1.获取对象的保存文件路径 # 以类名当中文件夹的名字 class_name = obj.__class__.__name__ # __class__ 获取当前的类,__name__获取当前类的名字 user_dir_path = os.path.join( sttings.DB_PATH, class_name ) # 2.判断文件夹是否存在,不存在则创建文件夹 if ...
import multiprocessing as mp import numpy as np import itertools import math import os import sys import time import commp as cp from sdii import sdii from msa import msa def init(): if len(sys.argv) < 5: print 'Usage: python mp_ce_sdii_rcrr.py MSATitle weight.file targetVar order' print 'Example...
#! /usr/bin/python # Simple implementation of a token bucket algorithm. # Solves this question: Write a function that returns false if it has been # called n times or more in the last m seconds and returns true otherwise. # # For explanation on Token Bucket: http://en.wikipedia.org/wiki/Token_bucket import time n = ...
from KNN import KNN import numpy as np import data if __name__ == "__main__": print("start to load data.") x, y = data.load_data_mnist("train.csv") x_train, y_train, x_test, y_test, x_val, y_val = data.prepareData(x, y) print("data loading finished.") model = KNN(x_train, y_train) kk, temp_acc = 0, 0...
#exercicio 1 numero = float(input('digite um numero: ')) def nume(): if numero <= 0: return 'negativo' elif numero >= 1: return 'positivo' num = nume() print(num) #exercicio 2 t = float(input('digite a taxa de imposto: ')) c = float(input('digite o custo do produto: ')) def...
from tracker.tracker import track def parse_args(): import argparse parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description= """ =================================================================== Script for downbeat and beat tracking ===========...
import tensorflow as tf import sys; sys.path.append("../") import argparse from src.u_net import create_conv_net as unet from src.get_batch import Batch import numpy as np import os def main(args): os.environ["CUDA_VISIBLE_DEVICES"] = "" sess = tf.Session() net_in = tf.placeholder(tf.float32, shape=[1, ...
# -*- coding: utf-8 -*- import pymysql def getconn(): config = { 'host': '127.0.0.1', 'port': 3306, 'db': 'shop', 'user': 'root', 'passwd': '067116', 'charset': 'utf8', } conn = pymysql.connect(**config) return conn class TMallPipeline(object): ...
##### Writer : "Atia" ###### Importign the Library import os import pandas as pd import numpy as np pd.set_option('display.max_columns', 500) pd.set_option('display.width', 20) import matplotlib.pyplot as plt os.chdir("/Users/macbook/Documents/pyhton/portfolio/Two_Line_Diagram") #### reading the reference list path...
# -*- coding: utf-8 -*- """ Created on Fri Nov 18 13:58:05 2016 @author: Brainerd D. Cruz """ import pandas as pd #import numpy as np from datetime import timedelta as td from datetime import datetime as dt import analysis.querydb as qdb import matplotlib.pyplot as plt import analysis.subsurface.filterda...
import os from dotenv import load_dotenv load_dotenv() class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY', 'THIS IS THE DEFAULT KEY')
# -*- coding: UTF-8 -*- import re import download from pyquery import PyQuery query_start_date = '2010.01.01' query_end_date = '2015.06.30' # there you need alert query date, selected, one of num* and pageNow form_data = { 'showType': '1', 'strWord': "公开(公告)日=BETWEEN['{0}','{1}'] and 地址='上海市'".format(query_s...
# -*- coding: utf-8 -*- import json import os import unittest from xoxzo.cloudpy import XoxzoClient class TestXoxzoClient(unittest.TestCase): def setUp(self): self.test_recipient = os.environ.get("XOXZO_API_TEST_RECIPIENT") self.test_sender = "814512345678" self.test_mp3_url = os.environ....
import random import timeit from collections import Counter # k: k-mer length # generate sequence of length k def generate_sequence(k, bases='ACGT'): return ''.join([random.choice(bases) for i in range(k)]) # n: how many to generate # k: k-mer length # this function mutates given consensus string # then generate...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.result = None def searchKeysSubtrees(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNod...