text
stringlengths
38
1.54M
# Generated by Django 3.0.5 on 2020-10-30 10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0039_auto_20201030_1007'), ] operations = [ migrations.AlterField( model_name='attendance', name='date', ...
from KnuthAlgorithmR import knuthR from MitchellGenerate import genDeBruijn from MitchellGenerate import doublepuncture class iterbruijn: def __init__(self, n): self.n = n def __iter__(self): return iterbruijn_iter(self.n) class iterbruijn_iter: def __init__(self, n): if n % 2 =...
"""area_n_points.py: """ __author__ = "Dilawar Singh" __copyright__ = "Copyright 2017-, Dilawar Singh" __version__ = "1.0.0" __maintainer__ = "Dilawar Singh" __email__ = "dilawars@ncbs.res.in" __status__ = "Development" import sys import os import numpy as np...
# Author: Melanie Huynh # Date: 27 January 2021 # Description: This program uses a binary search to find a target. If the target # is not found, it raises an exception. def bin_except(a_list, target): """ Searches a_list for an occurrence of target If found, returns the index of its position in the list ...
# get the data needed to plot the TEP with a quiver plot on top of it import numpy as np #import pickle import os import pandas as pd import csv from scipy.interpolate import interp1d import sys sys.path.insert(0,'../../functions') # so I can import the functions from cycle_funcs import calc_fitness, calc_dfitness, s...
""" This script is used """ from sqlalchemy import create_engine import pandas as pd import numpy as np import time # reminder: dont store your credentials like this, this is only for illustrative purpose connect_string = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format("root", "MyP4ssword123!", "34.65.173.67"...
personas={} n = int(input()) for i in range(n):#numero que se van ha solicitar los datos n=3 nombre = input("Nombre: ") fecha = input("Fecha Nac.:") personas[nombre]=fecha print(personas)
from tkinter import * from random import (choice) SIZE = 20 KEY = str("") EX, EY = 0, 0 DELAY = 100 SNAKE = [] COORD = [] class Jogo: def __init__(self): self.window = Tk() self.window.geometry("500x500+400+100") self.window.bind("<KeyPress>", self.keypress) self.m...
import metrics as mt import dippykit as dip import matplotlib.pyplot as plt import skfuzzy as fuzz import skimage import exposure import matlab.engine import numpy as np ''' def mu1(x,fh2): return np.exp(-((255-x)**2)/(2*fh2)) def mu2(x,a,ex): gamma = (10*(ex-0.5))**1.1 return 0.99*((x-a)/(255-a))**gamm...
if __name__ == '__main__': str = "ASDqweASD" new_str = "" for i in range(len(str)): if ord(str[i]) >= 65 | ord(str[i]) <= 90 : new_str += str[i] print(new_str)
import time start_time = time.time() # ---------------------------------------------------------------- # http://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python # As the challenge here is not about finding prime numbers, I'll be using a nice clean option. def is_prime(a): retur...
from flask import request, jsonify, json from flask_restful import Resource from flask_jwt import jwt_required, current_identity from flasgger import swag_from import pyexcel as p from flask import make_response, jsonify from services.report_service import ReportService from utils.util import model_to_dict class Repo...
import os import mala import numpy as np from mala.datahandling.data_repo import data_repo_path data_path = os.path.join(data_repo_path, "Be2") """ Shows how MALA can be used to optimize descriptor parameters based on the ACSD analysis (see hyperparameter paper in the documentation for mathematical details). """ ##...
from django.test import TestCase class TestSuiteRunsTestCase(TestCase): def test_suite_should_run(self): # This test verifies, if the application even runs - ie. if it is # executed correctly, we didn't have any syntax errors, import # errors etc. pass
# Copyright (c) 2019-present, HuggingFace Inc. # All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. import os from argparse import ArgumentParser import torch import torch.nn.functional as F from model import BertModel from...
''' Author: Guanghan Ning E-mail: guanghan.ning@jd.com October 22th, 2018 Unit test for data preparation ''' import sys, os sys.path.append(os.path.abspath("../utils/")) from keypoints_to_graph import * import pickle def test_load_data_for_gcn_train(): dataset_str = "posetrack_18" dataset_spli...
import datetime from isoweek import Week import calendar def get_week(timestamp): timestamp = datetime.datetime.utcfromtimestamp(float(timestamp)) date = timestamp.date() iso_info = date.isocalendar() week = iso_info[1] - 1 return week def get_week_timestamp(year, week): d = Week(year, week)....
# -*- coding: UTF-8 -*- from pluginsinterface.PluginLoader import on_message, Session, on_preprocessor, on_plugloaded from pluginsinterface.PluginLoader import PlugMsgReturn, plugRegistered, PlugMsgTypeEnum, PluginsManage from pluginsinterface.PluginLoader import PlugArgFilter from pluginsinterface.PermissionGroup imp...
# -- coding: utf8 -- __author__ = 'elmira' import MySQLdb as mdb from heritage_corpus.settings import DATABASES USER = DATABASES['default']['USER'] PASSWORD = DATABASES['default']['PASSWORD'] NAME = DATABASES['default']['NAME'] class Database(object): """Класс для общения с базой данных MySQL""" def ...
i=int(input()) n=len(str(i)) e=0 j=i while(j>0): e=e+(j%10)**n j=j//10 if (i==e): print("yes") else: print("no")
import pyodbc import sys import os.path import csv def csvInternalObject(inFile): mapFile=open(inFile, 'rb') mapDict=csv.DictReader(mapFile) csvList=[] for row in mapDict: rowDict={} for i in mapDict.fieldnames: rowDict[i]=row[i] csvList.append(rowDict) ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2018-07-28 20:11 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('operation', '0003_usercomment_add_time'), ('course', '0011_bannercourse'), ] operati...
from typing import List from collections import defaultdict class Solution: def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: if source == destination: return True edge_dict = defaultdict(set) for u, v in edges: edge_dict[u...
# Copyright (c) 2020, NVIDIA CORPORATION. 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.0 # # Unless required by appli...
import torch import torch.nn as nn import torch.nn.functional as F class Bottleneck(nn.Module): def __init__(self, last_planes, in_planes, out_planes, dense_depth, stride, first_layer): super(Bottleneck, self).__init__() self.out_planes = out_planes self.dense_depth = dense_depth ...
# coding: utf8 # Author: Wing Yung Chan (~wy) # Date: 2017 #26 - Reciprocal Cycles #Learnt some new maths here import itertools #finds the first number in the sequence (9,99,...) that is divisible by x def find_divisible_repunit(x): assert x%2!=0 and x%5 != 0 for i in itertools.count(1): repunit = int...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.python.framework import ops from keras.engine.topology import Layer import keras.backend as K from keras.layers import Activation from keras.utils.ge...
def lengthOfLongestSubstring(s: str) -> int: length = len(s) right = 0 left = 0 ans = 0 letters = {} while left < length and right < length: element = s[right] if element in letters: left = max(left, letters[element] + 1) letters[element] = right ans ...
import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values """# Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_spli...
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
import numpy as np import sync_generator as syncgen import sbm_generator as sbmgen import noise_generator as gen import burer_monteiro as bm from sklearn import cluster import aux def _spectral_gap(A, z): """ Returns dual spectral gap given observation A and ground truth z. """ gap = aux.laplacian_ei...
# Program symulujący działania czujnika wilgotności: print("Program symulujący czujnik wilgotności!") # Wektor temperatur: humidities = [76.5, 79.4, 80.6, 81.0, 82.8, 83.7, 86.7, 60.8, 68.9, 70.1] iter = 0 # Importuj bibliotekę Redis do obsługi bazy danych: import redis # Połącz się z bazą Redis: r = redis.Redis() ...
from wpilib.command import CommandGroup from .open_claw import OpenClaw from .set_wrist_setpoint import SetWristSetpoint from .set_elevator_setpoint import SetElevatorSetpoint class Place(CommandGroup): """Place a held soda can onto the platform.""" def __init__(self, robot): super().__init__() ...
# from vnpy.trader.ui import QtGui from PyQt5 import QtGui WHITE_COLOR = (255, 255, 255) BLACK_COLOR = (0, 0, 0) GREY_COLOR = (100, 100, 100) UP_COLOR = (178,34,34) DOWN_COLOR = (0,255,255) CURSOR_COLOR = (255, 245, 162) PEN_WIDTH = 1 BAR_WIDTH = 0.4 AXIS_WIDTH = 0.8 NORMAL_FONT = QtGui.QFont("Arial", 9) # def to...
from Crypto.Util.number import * m = "flag{Gr34t!_y0u_h4v3_d0n3_it!!}" p = getPrime(512) q = getPrime(512) n = p*q e = 65537 phin = (p-1)*(q-1) def egcd(a,b): if b == 0: return a else: return egcd(b,a%b) def mod_inv(a,b,x1,x2,y1,y2): gcd = egcd(p,q) if gcd == 1: if b == 0: return x1 else: x = (x1...
from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import UserManager # Create your models here. class Tag(models.Model): name = models.CharField(max_length=200, null=True) class BlogPost(models.Model): titl...
#!/usr/bin/env python """ Calculate the density of low redshift objects in magnitude space of SVA1 GOLD galaxies using COSMOS photo-z's. """ from multiprocessing import Pool import itertools import time import numpy as np import os from astropy.io import ascii,fits import matplotlib.pyplot as plt num_threads = 4 hom...
import sys n = int(sys.stdin.readline()) def find(): d = [0 for _ in range(n + 1)] for k in range(2, n+1): d[k] = d[k-1] + 1 if k % 3 == 0: d[k] = min(d[k//3] + 1, d[k]) if k % 2 == 0: d[k] = min(d[k//2] + 1, d[k]) print(d[n]) find()
import math import numpy as np import random def sigmoid(x, derivative=False): if derivative: return 1 / (1 + math.e ** -x) * (1 - 1 / (1 + math.e ** -x)) else: return 1 / (1 + math.e ** -x) def relu(X, derivative=False): if derivative: X[X <= 0] = 0 X[X > 0] = 1 else...
import os import sys import datetime import configparser from flask import Flask, render_template, request, flash, session, redirect, url_for import mysql.connector # Read configuration from file. config = configparser.ConfigParser() config.read('config.ini') # Set up application server. app = Flask(__name__) app.sec...
# -*- coding: utf-8 -*- """ Demonstrates common image analysis tools. Many of the features demonstrated here are already provided by the ImageView widget, but here we present a lower-level approach that provides finer control over the user interface. """ import initExample ## Add path to library (just for examples; yo...
from pycloudia.packages.interfaces import IEncoder from pycloudia.packages.exceptions import InvalidEncodingError class Encoder(object, IEncoder): encoding = None content_delimiter = None headers_delimiter = None def encode(self, package): assert isinstance(package.content, str) asser...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 3 17:09:46 2020 @author: rohitmathew and guoyichen """ # make sure to install these packages before running: # pip install sodapy import pandas as pd from sodapy import Socrata from datetime import datetime,date import matplotlib.pyplot as plt #...
import cv2 from fdet import io, RetinaFace BATCH_SIZE = 10 detector = RetinaFace(backbone='MOBILENET', cuda_devices=[0]) vid_cap = cv2.VideoCapture('test_video.mp4') video_face_detections = [] # list to store all video face detections image_buffer = [] # buffer to store the batch while True: success, frame =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """mergeBedGraphs.py This script can be used to merge BED graphs produced by bismark_SE/PE.sh and bamToBedGraph.sh and a sample annotation file (see below) into a single long-format table (for lm() in R). NOTE: minCov >= 5, maxCov <= 100, and minGroupCount >= 2 are hard-co...
import sys from .. import SetWallpaper class DarwinSetWallpaper(SetWallpaper): @staticmethod def platform_check(config): return sys.platform == 'darwin' @staticmethod def set(config): import subprocess DARWIN_SCRIPT = """/usr/bin/osascript << END tell application "Finder" set...
#!/usr/bin/env python #ATTENTION: DO NOT MODIFY THIS CODE WITHOUT FIRST CONSULTING CARTER SHEAN #(at least until Bruin 2 is finished) #----------------------------------------------------------------- #Python file for managing the GUI for the Bruin 2 Robot #using PyQT5 modules and QT designer paired with the Pyuic co...
""" 申万行业指数:训练数据生成 """ import urllib.request import json import re as regex from datetime import datetime, timedelta import numpy as np import pandas as pd from earnmi.chart.KPattern2 import KPattern2 from earnmi.data.SWImpl import SWImpl from earnmi.chart.Indicator import Indicator def generateSWTrainData(kPatterns...
''' Created on 2017年7月16日 @author: jack ''' # encoding=utf-8 import smtplib from threading import Timer from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from Tools import MyDataBase class MailSender(): def __init__(self): self.smtpServer = "smtp.126.com" self.us...
import sys import getopt import os import operator from math import log from collections import defaultdict class NaiveBayes: class TrainSplit: """ Set of training and testing data """ def __init__(self): self.train = [] self.test = [] class Document: ...
# http://stackoverflow.com/questions/12507274/how-to-get-bounds-of-a-google-static-map import math MERCATOR_RANGE = 256 def bound(value, opt_min, opt_max): if opt_min is not None: value = max(value, opt_min) if opt_max is not None: value = min(value, opt_max) return value ...
""" Commonly-used queries """ from sqlalchemy.exc import SQLAlchemyError from setup import Category, Item import bleach def getCategories(session): """ Retrieve all categories. :param session: (DBSession) SQLAlchemy session :return: List of Category objects. """ try: categories = (...
from selenium.webdriver.common.by import By """以下为联系人功能配置信息""" add_contacts_button = By.ID, "com.android.contacts:id/floating_action_button" input_name = By.XPATH, "//*[@text='姓名']" input_phone_number = By.XPATH, "//*[@text='电话']" """以下为短信功能配置信息""" new_message = By.ID, "com.android.mms:id/action_compose_new" message_...
from pyrefinebio import ( annotation as prb_annotation, computed_file as prb_computed_file, processor as prb_processor, transcriptome_index as prb_transcriptome_index, ) from pyrefinebio.api_interface import get_by_endpoint from pyrefinebio.base import Base from pyrefinebio.util import create_paginated_...
# import import timm import torch from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR from src.project_parameters import ProjectParameters from pytorch_lightning import LightningModule import torch.nn as nn from torchmetrics import Accuracy, ConfusionMatrix import pandas as pd import numpy as np from src.uti...
# MorseCodeWriter - Morse code visualisation on LED (RGB) # Timing: https://en.wikipedia.org/wiki/Morse_code#Transmission import RPi.GPIO as GPIO import time # LED setup red = 18 green = 24 blue = 23 # Settings selectedColor = green # Selected color of LED timeUnit = 0.1 # Duration of one time unit [s] # Morse co...
import cv2 import numpy as np from enum import Enum class Color(Enum): RED = 1 GREEN = 2 YELLOW = 3 BLUE = 4 MIX = 0 def get(self): if Color(self.value) == Color.RED: return np.array([[[0,0,255]]]) elif Color(self.value) == Color.GREEN: return np.arr...
import pandas as pd import numpy as np import json import re import copy import itertools import math import re, string import sqlite3 from collections import OrderedDict from quantipy.core.helpers.constants import DTYPE_MAP from quantipy.core.helpers.constants import MAPPED_PATTERN from itertools import product from ...
products = input().split() searched_products = input().split() product_dict = {} for i in range(0, len(products), 2): product = products[i] quantity = products[i + 1] product_dict[product] = int(quantity) for product in searched_products: if product in product_dict: print(f"We have {product_dict...
#Squeeze with Pytorch #Squeeze : 원소가 1인 차원을 제거 #Squeeze(dim = n): n차원을 제거 import torch import numpy as np ft = torch.FloatTensor([[0], [1], [2]]) print(ft) print(ft.shape) print(ft.squeeze()) print(ft.squeeze().shape)
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect, Http404 from .models import Article, Comment from django.urls import reverse def index(request): latest_articles_list = Article.objects.order_by('-pub_date')[:5] return render(request, 'firstApp/list.html', {'latest_artic...
import unittest.mock from slack import WebClient from programy.clients.polling.slack.client import SlackBotClient from programy.clients.polling.slack.config import SlackConfiguration from programy.clients.render.text import TextRenderer from programytest.clients.arguments import MockArgumentParser class MockSlackCl...
# Contributors: Matt Ware import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() class arrayinfo(object): def __init__(self,name,array): self.name = name self.shape = array.shape self.dtype = array.dtype class small(object): def __...
import serial import socket import time import struct from threading import Thread from openctrl import Packet, checksum class Bus(object): def __init__(self,ser): self.packet = Packet() self.ser = ser def send_welcome(self,recv_packet): self.packet.src = [1,1] self.packet.dst...
from kivymd.app import MDApp from usermapviewv2 import UserMapView import sqlite3 from searchpopupmenuv2 import SearchPopupMenu class MainApp(MDApp): connection = None cursor = None search_menu = None def on_start(self): #init gps #connect to db self.connection = sqlite3.connect("store.db") self.cursor =...
from django.shortcuts import render from django.http import HttpResponse,Http404 from .models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'firs...
def part_1(): with open('input/day2_input') as f: s = 0 for line in f: row = [int(x) for x in line.split('\t')] s += (max(row) - min(row)) print('Part 1: {}'.format(s)) def part_2(): with open('input/day2_input') as f: s = 0 for line in f: ...
# -*- coding: utf-8 -*- """ xyz_parser.py: Functions to preprocess dataset. """ import os import networkx as nx import numpy as np from rdkit import Chem from rdkit.Chem import ChemicalFeatures from rdkit import RDConfig def init_graph(prop): prop = prop.split() g_tag = prop[0] g_index = int(prop[1]) g_...
ops = set(("ARRAY-INIT", "NULL", "ASSIGN", "UPDATE", "BLOCK", "BREAK", "CONTINUE", "CALL", "CASE", "CATCH", "GUARDED-CATCH", "CATCH", "COMMA", "DEBUGGER", "DEFAULT", "DEFAULT", "DELETE", "TYPEOF", "NEW", "UNARY_MINUS", "NOT", "VOID", "BITWISE_NOT", "UNARY_PLUS", "DO", "DO-WHILE", "DOT", "ATTRIBUTE", "FUNCTION", "DEF-F...
# Write a function that takes in an array of unique integers and returns # an array of all permutations of those integers in no particular order def getPermutations(array): permutations = [] permutationsHelper(array, [], permutations) return permutations def permutationsHelper(array, currentPermutation, permuta...
# -*- coding: utf-8 -*- import os import re from functions import * is_shifted = lambda path: isNotNone(re.match(r'^.*\.zs$', path)) is_deconvoluted = lambda path: isNotNone(re.match(r'^.*\.dv_decon.*$|^.*_D4D\.dv.*$', path)) class ImageFile: def __init__(self, path): self._path = path self._base...
########################################################################### # TASK 1 type_list = [int(1), str("python"), bool(None), float(0.35), {0, 1, 2, 3}, tuple()] print(type_list) print(type(type_list)) print(type(type_list[0])) print(type(type_list[1])) print(type(type_list[2])) print(type(type_list[3])) print...
import os import tempfile from subprocess import Popen from tkinter import * from tkinter import ttk from tkinter import filedialog import barcode from barcode.writer import ImageWriter tmp_path = 'BarcodeGenerator.png' def generate_barcode(event): global tmp_path delete_temp_image() barcode_txt = ent_ba...
#!/usr/bin/env python # -- coding: utf-8 --# # @Time : 2020/4/14 13:01 # @Author : Aries # @Site : # @File : numbers.py # @Software: PyCharm ''' 一些数字相关的算法 ''' from typing import List import sys def merge(intervals: List[List[int]]) -> List[List[int]]: ''' 给出一个区间的集合,请合并所有重叠的区间。 示例 1: 输入: [[1,3],[...
import redis # 保持跟数据库的链接,当超过数量时,就等着 # # 解码 pool = redis.ConnectionPool(host="127.0.0.1", port=6379, decode_responses=True, max_connections=10) conn = redis.Redis(connection_pool=pool) ret = conn.get("n1") print(ret)
from django.db import models # Create your models here. ''' Models for questions ''' class Question(models.Model): '''text feild for question''' '''user=models.ForeignKey(User)''' question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') '''for string convertion of questi...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() setup( name='plasma', description='Plasma MVP', long_description=readme, author='David Knott', author_email='', license=license, packages=find_packages(exclude=('tests')...
from flask import Blueprint, render_template, session, redirect, url_for, \ request, flash, g, jsonify, abort from gui.utils import do_create_mag, do_get_paginated_mag, do_get_mag, do_logout import json mod = Blueprint('mags', __name__) @mod.route('/mags/') def index(): if not g.logged_in: return re...
import pickle import math import ROOT #What to read pileups = [200] ss = ["Nu_PU200_aged3000","Nu_PU200_aged1000","Nu_PU200"] samples = {"Nu_PU200_aged3000":ROOT.kBlue,"Nu_PU200_aged1000":ROOT.kRed,"Nu_PU200":ROOT.kBlack} tags = {"Nu_PU200_aged1000":"1000 fb^{-1} Aging","Nu_PU200_aged3000":"3000 fb^{-1} Aging","Nu_...
import sys from datetime import date, timedelta def main(): """ Args: year: year of start date month: month of start date day: day of start date instruction_days: number of weekly meetings (2 or 3) - debug mode: any additional parameter (optional) """ year = int...
from .fact import Fact class Rule: def __init__(self, left_side, conclusion_op, right_side): self.left_side = left_side self.conclusion_op = conclusion_op self.right_side = right_side self.full_rule = ' '.join(map(str, self.left_side + [self.conclusion_op] + self.right_side)) ...
# coding:utf-8 #! /usr/bin/env python from scapy.all import * import random import datetime ifaceNames = ["enp0s31f6","docker0"] linkSrcAddr = "fe80::437f:2137:3e16:b6ea" linkDstAddr = "ff02::1:ff21:41f" macSrcAddr = "8c:ec:4b:73:25:8d" macOtherSrcAddr = "7c:76:35:de:0c:79" macMultiAddr = "33:33:ff:e4:89:00" def s...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Jan 8 14:04:43 2017 @author: firojalam """ import optparse import datetime import aidrtokenize; from gensim.models import Word2Vec from nltk.corpus import stopwords from gensim.similarities.docsim import WmdSimilarity import warnings import datetime im...
""" Created by lgc on 2020/2/5 15:05. 微信公众号:泉头活水 """ import pytest,os import allure from time import sleep from Api.cloudparking_service import cloudparking_service from Api.information_service.information import Information from Api.sentry_service.carInOutHandle import CarInOutHandle from common.BaseCase import Bas...
import os import json path = r"../data_proc/raw_skeletons/numbered/" f= open("../data_proc/raw_skeletons/skeletons_info.txt", 'w+') Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, ...
import matplotlib.image as mpimg from PIL import Image import numpy as np import os import shutil NUM = 5 mypath = '/Users/zhangjunwei/Downloads/AerialImageDataset/' test_img = mypath + 'train/images/' #test_img = mypath + 'test/images/' tests_img = mypath + 'test_small/images/' tests_img_eg = mypath + 'test_small_e...
import urllib.request import re url = "http://www.pythonchallenge.com/pc/def/equality.html" response = urllib.request.urlopen(url) html = response.read() # print(html) ss = str(html) print(ss[:2000]) f = re.findall(r'[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]', ss) print(f) new_ss = "" for i in f: new_...
# -*- coding: utf-8 -*- """ Administration classes for the presidencies application. """ # standard library # django from django.contrib import admin from django.urls import reverse from django.shortcuts import redirect # parler from parler.admin import TranslatableAdmin from institutions.admin import GovernmentStru...
# import subprocess # # import os # with open('a.txt','a')as f: # t = subprocess.Popen('curl -X POST -k -L www.baidu.com ' # '',stdout=f) # # t = subprocess.Popen('ls', stdout=f) # # tl = t.split('\n') # # print tl # # print t a = 2.25 s = "%.2fG%.1fG"%(a,a) u = 1.00 t = "Your Storage...
from __future__ import print_function from builtins import input import numpy as np import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.spatial import ConvexHull, Delaunay import random # from sklearn import metrics import ensure_segmappy_is_installed from segmappy import Datas...
from Tollapp.models import main import datetime a = "2017-02-10" b = "2017-02-24" c = a.split('-') start = int(c[0]),int(c[1]),int(c[2]) d = b.split('-') end = int(d[0]),int(d[1]),int(d[2]) f = main.objects.filter(timestamp__gte = datetime.date(start),timestamp__lte = datetime.date(end),vehicle_status = "permit").count...
import unittest from unique_occurrences import unique_occurrences class TestUnique_Occurrences(unittest.TestCase): def test_unique_occurrences(self): self.assertEqual(unique_occurrences([1, 2, 2, 1, 1, 3]), True) self.assertEqual(unique_occurrences([1, 2]), False) self.assertEqual(unique_...
from __future__ import absolute_import import argparse import logging import pkg_resources import sys import textwrap from workspace.commands.bump import Bump from workspace.commands.checkout import Checkout from workspace.commands.clean import Clean from workspace.commands.commit import Commit from workspace.commands...
# -*- coding: utf-8 -*- """ Created on 2018 @author: """ # #######text data 前提################ # #输入原始数据 # # # # 此处理是将中文语料输入 训练,并并保存模型 # # # #输出是.... # #使用方法:python word2vec_train.py std_zh_wiki_00 # # # # import os import sys import multiprocessing import logging import gensim #from gens...
from Router import * from PyQt4 import QtCore class yRouter(Router): device_type="yRouter" def __init__(self): Interfaceable.__init__(self) self.setProperty("WLAN", "False") self.setProperty("mac_type", "MAC 802.11 DCF") self.lightPoint = QPoint(-14,15)
import os import sys import json import argparse import numpy as np import pandas as pd from copy import copy import warnings import utils.general_functions as gn from sklearn.linear_model import LinearRegression from sklearn import metrics from utils.data_preprocess_version_control import generate_version_params from ...
import datetime from DataPoints import * def generateDataPoints(startTime): points = [] i = 0 file = open("./tweepyData", "r") line = file.readline() while "*" not in line: if "#" in line: i += 1 else: points.append(subclassList[i]((float(line)-startTime)//...
import pyaudio import numpy import scipy p = pyaudio.PyAudio() host_api_count = p.get_host_api_count() print "Number of available Host API: %d" % host_api_count for i in range(host_api_count): host_api = p.get_host_api_info_by_index (i) if host_api['deviceCount'] != pyaudio.paNoDevice: if 'defaultOu...
""" Figure 11: Why dictionaries are needed """ from weakref import WeakKeyDictionary class NonNegative(object): """A descriptor that forbids negative values""" def __init__(self, default): self.default = default self.data = WeakKeyDictionary() def __get__(self, instance, owner): #...
from __future__ import division import serial import time from array_devices import array3710 __author__ = 'JoeSacher' """ This is a crude script to play with PC baud rates while the load is set to a fixed baud rate. """ load_addr = 1 # This should match load base_baud_rate = 9600 serial_conn = serial.Serial('COM4'...