text
stringlengths
8
6.05M
import sys import time from threading import Thread, Lock from spinners import Spinners color_end = '\033[0;39m' status_symbols = { 'info': '{0}ℹ{1}'.format('\033[34m', color_end), 'success': '{0}✔{1}'.format('\033[32m', color_end), 'warning': '{0}⚠{1}'.format('\033[33m', color_end), 'error': '{0}✖{1}...
''' Created on Mar 30, 2011 @author: jason ''' import Users import simplejson import datetime import bson import tornado.web from Auth.AuthHandler import ajax_login_authentication from Map.BrowseTripHandler import BaseHandler class MessageHandler(BaseHandler): def Send(self, source_id, dest_id, message, type...
from dwave_qbsolv import QBSolv import matplotlib.pyplot as plt import numpy as np import minorminer import networkx as nx from dwave.system.composites import FixedEmbeddingComposite from dwave.system.composites import EmbeddingComposite from dwave.system.samplers import DWaveSampler # Functions def mapseq(F): ...
#!/usr/bin/env python # # (c) Grant Rotskoff, 2013 # maintainer: gmr1887@gmail.com # license: GPL-3 usage="./UmbrellaIntegrate.py metadata.txt path.dat mean-force.dat pmf.dat" ### parse the args ### from sys import argv try: import numpy as np except: print "You must have numpy to use this script! Try \">$ modu...
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'urlshot.views.home', name='home'), # url(r'^urlshot/', include('urlshot.foo.urls')),...
""" CCT 建模优化代码 求三角形面积,展示P2类的使用方法 作者:赵润晓 日期:2021年5月3日 """ # 因为要使用父目录的 cctpy 所以加入 from os import error, path import sys sys.path.append(path.dirname(path.abspath(path.dirname(__file__)))) from cctpy import * # 方法一:海伦公式 # 定义三角形三个顶点 A = P2(21, 8) B = P2(33, 28) C = P2(39, 6) # 求三条边的长度 AB_length = (A-B).length() AC_len...
#!/usr/bin/python import sys from ROOT import gROOT from ROOT import TFile from ROOT import TKey def GetKeyNames( self ): return [key.GetName() for key in MyFile.GetListOfKeys()] TFile.GetKeyNames = GetKeyNames MyFile=TFile("DeepSingle+DelphMET_NoPU_DiBoson_his.root") keyList = MyFile.GetKeyNames() print "\nKeys in ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # 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 ...
import chainer import chainer.functions as F import chainer.links as L class Generator(chainer.Chain): """docstring for Generator""" def __init__(self): super(Generator, self).__init__( l1=L.Linear(100,50*5*5), dcv1=L.Deconvolution2D(in_channels=50,out_channels=10,ksize=3,stride=3), dcv2...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
from flask import Flask, request, jsonify import requests from flask_cors import CORS from os import environ import json import pika import datetime import json from datetime import date app = Flask(__name__) CORS(app) def send_alert_message(info): return requests.post( "https://api.mailgun.net/v3/sandbox2...
"""Module for converting numbers to various numeral systems.""" from typing import Union def convert(number: Union[int, str], base_init: int, base_final: int) -> str: """Convert a number to another numeral system. :param number: the initial number :param base_init: a base of the initial number :para...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script daemonize runinng process """ import os import sys def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): # Run first fork try: pid = os.fork() if pid > 0: sys.exit(0) # First parent process closed ...
# Сериализаторы from rest_framework import filters from rest_framework import viewsets from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend # Права...
def solution(board, moves): answer = 0 row = [len(board) for i in range(len(board))] # 인형이 담겨 있는 행의 위치를 찾는다. for i in range(len(board)): for j in range(len(board[i])): if board[i][j] != 0 and row[j] == len(board): row[j] = i stack = [] for i in moves: ...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 from logging import Logger from abc import ABCMeta, abstractmethod from tonga.models.structs.store_record_type import StoreRecordType __all__ = [ 'BasePersistency' ] class BasePersistency(metaclass=ABCMeta): _initialize: bool = False _lo...
import json from mock import patch from grant.proposal.models import Proposal from grant.utils.enums import ProposalStatus from ..config import BaseProposalCreatorConfig from ..test_data import test_proposal, mock_blockchain_api_requests from ..mocks import mock_request class TestProposalContributionAPI(BaseProposal...
import numpy as np import cv2 class YCBCR: def __init__(self): pass def getShadow(self, image): h, w, c = image.shape image = cv2.resize(image,(320,240)) y_cb_cr_img = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb) binary_mask = np.zeros((y_cb_cr_img.shape[0],y_cb_cr_...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Any, Dict import gym from gym.core import Env from gym.envs.registration import register from mtenv.envs.hipbmdp.wrappers import framestack, sticky_observation def _build_env( domain_name: str, task_name: str, seed...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 13:15:55 2020 @author: shaun """ from numpy import loadtxt as lt from matplotlib import pyplot as plt #crates run average function to compute the running #average given a list of 11 points def runaverage(list5): r=5 a= 1/(2*r+1) sum5=0 for x in list5: ...
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='AuditRe...
import numpy as np import random import Hypothesis COLORS=['red', 'blue', 'green'] SHAPES=['rectangle', 'circle', 'triangle'] class Grammar(): def __init__(self): pass def produce_hypothesis(self): hypothesis=Hypothesis.Hypothesis() n_disj_terms=0 #set number of disjunctions while 1: if(np.random.b...
import uvicorn from app.database.crud import create_admin, create_post, get_user_by_username from app.database.redis import redis from app.database.sqlite import db from app.factory import create_app from app.utils.auth import get_password_hash main_app = create_app() @main_app.on_event('startup') async def startup...
import numpy as np import setup import gym import time import gym_airsim.envs import gym_airsim import argparse def test(): parser = argparse.ArgumentParser() parser.add_argument('--mode', choices=['train', 'test'], default='train') parser.add_argument('--env-name', type=str, default='AirSimEnv-v42') parser.add...
# -*- coding: utf-8 -*- """ Main script to train and export NN Forward models for the Ogden Material """ import numpy as np from random import seed import torch from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from time import time import PreProcess import Metamodels import PostProcess...
from .package_analyzer import PackageAnalyzer from xml.etree.cElementTree import parse from xml.etree.cElementTree import ParseError import logging class PackageXmlAnalyzer(PackageAnalyzer): """ Analyzer plug-in for ROS' package.xml files (catkin). """ def analyze_file(self, path: str, dependencies: d...
import pytest from flask import url_for """So far: Testing if the course routes are working create_course - is the course creation process working """ "Test if create course route by lecturer is working" def test_create_course(flask_app_client): client = flask_app_client request = client.get('...
import glob import sys import pyaudio import wave import numpy as np import tensorflow as tf import librosa from socket import * from header import * if len(sys.argv) < 4: print("Compile error : python main.py [nodeNum] [posX] [posY]") exit(1) FORMAT = pyaudio.paInt16 NODE = sys.argv[1] posX = sys.argv[2] pos...
import nltk from collections import Counter from nltk.stem import WordNetLemmatizer import fileinput from nltk.corpus import treebank lemmatiser = WordNetLemmatizer() verb_list = [] object_list = [] sentence_number = [] paragraph_number = [] with open('logapps_appendix.txt', "r") as test_words: fil...
import requests import csv from dagster import solid, DagsterType, OutputDefinition, InputDefinition, TypeCheck def is_list_of_dicts(_, value): return isinstance(value, list) and all( isinstance(element, dict) for element in value ) def less_simple_data_frame_type_check(_, value): if not isinst...
import numpy as np class suffix: def __init__(self): self.index = 0 self.rank = [0, 0] # This is the main function that takes a # string 'txt' of size n as an argument, # builds and return the suffix array for # the given string def buildSuffixArray(txt, n): # A structure to ...
from splinter import Browser from bs4 import BeautifulSoup as bs from webdriver_manager.chrome import ChromeDriverManager import pandas as pd def scrape(): executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable_path, headless=False) mars_data ...
import threading import time class Job(threading.Thread): def __init__(self, *args, **kwargs): super(Job, self).__init__(*args, **kwargs) self.__flag = threading.Event() self.__flag.set() self.__running = threading.Event() self.__running.set() def run(self): w...
from source.world import World from source.slam import SLAM2D import argparse parser = argparse.ArgumentParser() parser.add_argument('--steps', type=int) parser.add_argument('--num_landmarks', type=int) parser.add_argument('--world_size', type=int, default=100) parser.add_argument('--measurement_range', type=int, defa...
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import Flask from flask.ext.uwsgi_websocket import GeventWebSocket import subprocess import os.path from contextlib import closing from selenium.webdriver import PhantomJS # pip install selenium from selenium.webdriver.support.ui import WebDriverWait import urllib2 ...
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='Regression_theano', version='0.1', description='linear and logistic regression in Theano', long_description=readme(), classifiers=[ 'Development Status :: 3 - Alpha', 'Inte...
import sys if __name__ == "__main__": rate = [] for i in range(16): nums = list(map(float, sys.stdin.readline().strip().split())) rate.append(nums) finaleight = [0 for i in range(16)] finalfour = [0 for i in range(16)] finaltwo = [0 for i in range(16)] champion = [0 for i in ran...
#a 16-bit field that has the value 1010101010101010, indicating that this is an ACK packet. ACKmagicno = int('1010101010101010') #Read the information from the CMD import sys if(len(sys.args)!=3): print("Wrong Input") prob = float(sys.args[-1]) file = sys.args[-2] port = int(sys.args[-3]) seqno = 0 import socke...
# Unique Binary Search Trees # Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n ? # Explanation: We could use dictionary to save some look up time since many of recursive calls # hit the same n numbers # Run Time: O(n log(n)) since we don't repeat anything that h...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('basketball', '0014_game_winning_players'), ] operations = [ migrations.AlterModelOptions( name='game', ...
import commands import os import sys min_size = 10 def merge(file1, file2, main_file): f = open(main_file, 'w') f.close() f = open(main_file, 'a') f1 = open(file1, 'r') f2 = open(file2, 'r') arr1 = [line for line in f1.read().split('\n')] arr2 = [line for line in f2.read().split('\n')] ...
from random_numbers import * class Base_Account(): def __init__(self): self.account_number = ran_16_card_num() self.account_cards = [] self.account_balance = 0 def load(self,num,cards,bal): self.account_number = num self.account_cards = cards self.account_balanc...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-14 04:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PlayLi...
Zi = ["L", "Ma", "Mi", 'J', "Vi", "S", "D"] v = [1500, 2500, 3500, 4000, 4500, 5000, 0] print("venitul sapatamnal = ", sum(v)) print("media venitului zilnic = ", sum(v)//7) n= max(v) y = v.index(n) print("Ziua in care s-a obtinut cel mai mare venit este", Zi[y]) b = min(v) a = v.index(b) print("Ziua cu venitul...
from django.shortcuts import render, redirect, get_object_or_404 from .models import Book, Cart, BookOrder, Review from django.urls import reverse from django.utils import timezone from django.http import JsonResponse import paypalrestsdk import stripe from django.conf import settings from random import randint, choice...
div_amounts = {'BISHNUPUR': 100000, 'CHANDEL': 100000, 'CHURACHANDPUR': 100000, 'IED-II': 100000, 'IED-III': 100000, 'IED-IV': 100000, 'JIRIBAM': 100000, 'KAKCHING': 100000, 'KAMJONG': 100000, '...
import glob import sys import nltk from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import re import pdb import ujson import time import math # Create Co-occurrence tuple for wnd[-1] with all other wnd[i] # Get the expansion term for a word. def get_expan_terms(awor...
# 最终结果就是每个石头前面加 + / - # 直接分析成01背包 # 而且实际分析时只需考虑一边 class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: n, s = len(stones), sum(stones) t = s // 2 f = [0] * (t+1) for i in range(1, n+1): x = stones[i-1] for j in range(t, x-1, -1): ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np def hypothesisscatter(): adni = pd.read_csv("/Users/ariadnapuigventos/Documents/CURSOS/BRIDGE/DS_Ejercicios_Python/BootCamp_TheBridge/Alzheimers_Disease/Data/MCI_AD_CN_Final.csv", sep=",") adni['Visits_numbering'] = a...
import pickle from configparser import ConfigParser from pathlib import Path import keras from keras import Sequential from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense from sklearn.metrics import f1_score def train_dev_split(data, dev=.2): assert (0 <= dev <= 1) data_size = len(data) ...
"""Programs to calculate trajectory of projectiles or ratio of kinetic energy of projectiles at given angles of projection""" import math import matplotlib.pyplot as plt """Function to call for initial conditions depending on the program""" def initial_conditions(program): if program == 'TRAJECTORY': #...
from common.run_method import RunMethod import allure @allure.step("备课评价/新增评价") def courseWareEvaluateController_addEvaluate_post(params=None, body=None, header=None, return_json=True, **kwargs): ''' :param: url地址后面的参数 :body: 请求体 :return_json: 是否返回json格式的响应(默认是) :header: 请求的header :host: 请求的环...
import base64 import os import uuid import flask import flask_talisman import redis MAX_PLAN_SIZE_BYTES = 2 * 1024 * 1024 ONE_HOUR_SECONDS = 60 * 60 app = flask.Flask(__name__, template_folder="templates") # Use Talisman to redirect to HTTPS flask_talisman.Talisman(app, content_security_policy=None) # Keep a small ...
import os.path from install_utils import ProjectBuilder def main(): builder = ProjectBuilder.ProjectBuilder(ProjectBuilder.readConfigData()) builder.installProject() if __name__ == "__main__": main()
import numpy as np import random import tetris import neuralnetwork as NN import losses def cross(A, B): C = A ind = np.random.choice(B.shape[0], int(np.floor(len(B)/2)), replace=False) C[ind] = B[ind] ## take a random pick of dimension / 2 from A, the others from B return(C) def mutate(C): di...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, ValidationError from app.models import User, List, Item class ListCreationForm(FlaskForm): listname = StringField('Новый список', validators=[DataRequired()]) submit = SubmitField('С...
#Made by Andre Augusto Leite de Almeida import os import random import collections from PIL import Image, ImageDraw from numpy import array from skimage import img_as_float from skimage.measure import compare_ssim #Fast, but supports only one image on template class Basic_Meme: def __init__(self,folder): ...
#!/usr/bin/env python # # The imports import xarray as xr import time import dask # # The workers ask_workers=8 ask_memory='4GB' from dask_jobqueue import SLURMCluster from dask.distributed import Client cluster = SLURMCluster(cores=1,processes=1,name='pangeo',walltime='02:30:00', job_extra=...
from Classes.ServiceDAO import ServiceDAO class Service: def __init__(self): pass def add_service(self): print "Cadastrar novo servico" service = ServiceDAO() service.getData()
import numpy as np x = np.random.random(12).reshape(3,2,2) print(x)
# Copyright 2023 Pulser Development Team # # 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 applicable law or agreed to i...
import time from selenium.webdriver.common.by import By from Utilities.BasePage import BasePage from Utilities.TestData import TestData class MyGarage(BasePage): """By Locators""" MY_GARAGE_LINK = (By.LINK_TEXT, 'My Garage') PAGE_NUMBER_BUTTONS = (By.XPATH, "//li[@role='presentation']") FIRST_PAGE_BUT...
# From functools: https://hg.python.org/cpython/file/3.5/Lib/functools.py ''' >>> from functools import partial >>> p = partial(print, end=' ') >>> p.func <built-in function print> >>> p.args () >>> p.keywords {'end': ' '} >>> p1 = partial(p, sep='\t') >>> p1 functools.partial(functools.partial(<built-in function print...
# -*-coding:utf8-*- import logging import os import re import time import jieba import numpy as np import tensorflow as tf import tensorlayer as tl jieba.load_userdict(r"D:\PythonWorkstation\job_project\information_extraction\lib\dict.txt") def data_prepossessing(): sen_list = [] with open(r'D:\PythonWorks...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path from textwrap import dedent from pants.testutil.pants_integration_test import PantsResult, run_pants, setup_tmpdir def typecheck_file(path: str, filename: str) ...
# splits facebook messages from subjects given in args[1] separated by '|' # splits into groups given by args[3] # writes files to sampleSplit/args[2] import sys import os from os.path import isfile, join import re import shutil CONST_GROUPING_SIZE = int(sys.argv[3]) line_endings = ['.', ',', '?', '!', ':'...
""" The core addon is responsible for verifying core settings that are not checked by other addons. """ from mitmproxy import exceptions from mitmproxy import platform from mitmproxy.net import server_spec from mitmproxy.utils import human class CoreOptionValidation: def configure(self, opts, updated): ...
from flask import url_for from flask_login import current_user, logout_user from werkzeug.utils import redirect from util.logutils import loghelpers @loghelpers.log_decorator() def logout(): logout_user() return redirect( url_for( 'get_all_posts', # loggedin=current_user.is_au...
import os # # call "encrypt()" or "decrypt()" in the command line to run # def encrypt(): # read the file (to be encrypted) and write it into a temporary file fileName = input("Enter the name of your file: ") file = open(fileName,"r") temp = open("temp.txt","w") temp.write("") temp.close() ...
import argparse import os from cyvcf2 import VCF import random import pdb def getVCFlist(file_list, vcf_file, suffix): vcf_list = [] if (file_list == "-9" and vcf_file == "-9") or (file_list != "-9" and vcf_file != "-9"): print("Must provide either a vcf file (-v) and bam suffix (-s) or a file (-f) with paired e...
from sense_hat import SenseHat import time,datetime,logging,subprocess import ipdb from influxdb import InfluxDBClient '''initial var''' factor=1.356 difference=12 sleeptime=60 now = datetime.datetime.now() influxdb_user = 'pippo' influxdb_password = 'pippopassword' influxdb_db = 'TEMPERATURE' influxdb_host = 'rpi2' i...
import pyttsx3 import os file = open("english.txt","r").read().replace("\n","") engine = pyttsx3.init() engine.say(file) engine.save_to_file(file,"voice.mp3") os.system("play voice.mp3")
#!/usr/bin/env python3 #coding:utf-8 import os root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/' """ ------- 属性设置 ------- """ option_install = True """ awvs server awvs apikey """ awvs_server = 'https://127.0.0.1:13443/api/v1' awvs_apikey = '' """ nessus server nessus apikey """ nessus_ser...
# -*- encoding: utf-8 -*- # # Module Writen to OpenERP, Open Source Management Solution # # Copyright (c) 2012 Vauxoo - http://www.vauxoo.com # All Rights Reserved. # info@vauxoo.com # # Coded by: julio (julio@vauxoo.com) # # # This program is free software: you can redistribute it and/or modify # ...
class Carro: def __init__(self, marca, modelo, ano): self.__marca = marca self.__modelo = modelo self.__anoFabricacao = ano self.__velocidade = 0 #Encapsulamento #def getMarca(self): #return self.__marca #def setMarca(self, novaMarca): #self.__marca = nov...
#!/usr/bin/env python3 import progressbar import logging import logging.config import os import tensorflow as tf import numpy as np from model.resnet import ResNet from dataset.voc_loader import VOCLoader from dataset.instance_sampler import InstanceSampler from utils.utils_tf import fill_and_crop from configs.paths...
import unittest from katas.kyu_7.pauls_misery import paul class PaulTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(paul(['life', 'eating', 'life']), 'Super happy!') def test_equal_2(self): self.assertEqual(paul([ 'life', 'Petes kata', 'Petes kata', 'Petes k...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-07-26 13:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('gram', '0001_initial'), ] operations = [ mig...
import hashlib def to_short(url): return hashlib.md5(url).hexdigest()[:7]
#!/usr/bin/env python import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True import fastjet as fj import fjext import fjcontrib import fjtools import pythia8 import pythiafjext import pythiaext from heppy.pythiautils import configuration as pyconf # from tqdm.notebook import tqdm from tqdm import tqdm import arg...
import io import os import sys import csv import numpy as np import random if len(sys.argv) != 6: print 'Usage: create_random_lines.py input_file repmap_file:rep_hdr:sample_hdr num_rand rep_per_rand ctrl_sample' else: infile = sys.argv[1] outfile = infile[:-4] + '_rand' + infile[-4:] repmap_file, rep_...
import socket,os,shutil,sys from zipfile import ZipFile from PySide2 import QtCore, QtGui, QtWidgets from PySide2.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent) from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCurs...
from pathlib import Path from gammapy.datasets import ( Datasets, FluxPointsDataset, MapDataset, SpectrumDatasetOnOff, ) path = Path("$GAMMAPY_DATA") map_dataset = MapDataset.read( path / "cta-1dc-gc/cta-1dc-gc.fits.gz", name="map-dataset", ) spectrum_dataset = SpectrumDatasetOnOff.read( ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, Qt...
#encoding=utf-8 import sys import time from elbApi.elbClient import elbClient if __name__ == '__main__': client = elbClient() modid = int(sys.argv[1]) cmdid = int(sys.argv[2]) ret = client.apiRegister(modid, cmdid)#非必需使用的API if ret == -9998: print 'still no exist after register' for i...
import numpy as np import matplotlib.pyplot as plt import math from scipy import stats from scipy.stats import multivariate_normal def opentxt(filename):#读取文件 fp=open(filename,'r') a=fp.readlines() return a def div(a):#把信息存放在一个列表中,,第一个元素存放身高,第二个存放体重,第三个鞋码 c1=list() d1=list() e1=lis...
import json from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIRequestFactory from api.views import LaunchSiteViewSet, OperationalStatusViewSet, OrbitalStatusViewSet, SourceViewSet, CatalogEntryViewSet, TLEViewSet, DataSourceViewSet, ...
import unittest from zoomus import components, util import responses def suite(): """Define all the tests of the module.""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CustCreateV1TestCase)) return suite class CustCreateV1TestCase(unittest.TestCase): def setUp(self): s...
def tokenize(p): tokens = [] index = 0 while index < len(p): if index + 1 < len(p): if p[index + 1] == "*": tokens.append(p[index] + p[index+1]) index += 2 else: tokens.append(p[index]) index +=1 else: ...
from ..requests import get_news from . import main from flask import render_template, request from ..models import News_Article # Viewscategory=business category=science category=sports entertainment @main.route('/') def index(): business_news = get_news('business') science_news = get_news('science') ente...
import pandas IN_FILE_NAME = "gs://genomics-public-data/simons-genome-diversity-project/reports/Simons_Genome_Diversity_Project_sample_reference_results.csv" OUT_FILE_NAME = "results.parquet" def main(): # TODO use index column that comes from the CSV. frame = pandas.read_csv(IN_FILE_NAME) frame.to_parq...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms import FileField, IntegerField from wtforms.validators import DataRequired class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField...
from tkinter import* import time import datetime import pygame pygame.init() root = Tk() root.title("Music Box") root.geometry('1352x700+0+0') root.configure(background = 'white') ABC =Frame(root, bg="powder blue", bd=20, relief= RIDGE) ABC.grid() ABC1 =Frame(ABC, bg="powder blue", bd=20, relief= RIDGE...
import sys file_name=sys.argv[1] ifile = open(file_name) node_unique=[];node_outdegree=[];networks=[] for line in ifile: networks.append(line) temp = line.split() if temp[0] not in node_unique: node_unique.append(temp[0]) node_outdegree.append(1) else: node_outdegree[node_unique...
# Dependencies import pandas as pd import tweepy import time import json import random import config # Twitter API Keys consumer_key = config.consumer_key consumer_secret = config.consumer_secret access_token = config.access_token access_token_secret = config.access_token_secret # auth tweepy auth = tweepy.OAuthHandl...
#!/usr/bin/python # Copyright 2009-2011 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import optparse import sys import portage from portage import os def command_recompose(args): usage = "usage: recompose <binpkg_path> <metadata_dir>\n" if len(args) != 2: sys.stderr.write...
import ConfigParser from flask import Flask, request, jsonify import datetime import json import os config = ConfigParser.ConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/../../server.cfg') rd_email = config.get('RD', 'email') rd_phone = config.get('RD', 'phone') app = Flask(_...
class GlobalConfig: image_size = 1024 augment = True #model setting model_name = 'vfnet' config_file = 'configs/vfnet/vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' pretrain_url = 'https://openmmlab.oss-cn-hangzhou.aliyuncs.com/mmdetection/v2.0/vfnet/vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco/...
#Main file for Probot #Authors: Jonathan D'Alonzo & Stephen Canzanese #Rowan University Artifical Intelligence Semester Project
import pygame, sys import numpy as np import itertools import neurodot_present.present_lib as pl from neurodot_present.present_lib import Screen, FixationCross, CheckerBoardFlasher, UserEscape, run_start_sequence, run_stop_sequence pl.DEBUG = False ####################################################################...