text stringlengths 8 6.05M |
|---|
class Nodo:
def __init__(self, name="", weight =0, type='', data={}, len=0):
self.name = name
self.data = data
self.weight = weight
self.len = len
self.type = type
self.nodes = []
def addList(self, list):
for n in list:
self.nodes += [n]... |
# global imports
import os
import threading, queue
import multiprocessing as mp
import numpy as np
import tensorflow as tf
import time
import signal
# local imports
from centraltrainer.request_handler import RequestHandler
from centraltrainer.collector import Collector
from environment.environment import Environment
f... |
# Generated by Django 3.1.7 on 2021-05-04 21:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20210427_0001'),
('main', '0005_auto_20210427_2323'),
]
operations = [
]
|
from tkinter import Tk, Scale, Label, Entry, Button, font
from tkinter.constants import COMMAND
import serial
ventana = Tk()
ventana.title("Control de motor a pasos")
#ventana.geometry("400x300")
ventana.iconbitmap(r"D:\52556\Downloads\ejercicios_dia3\cas.ico")
ventana.config(bg = "#3498db")#azul
ventana.resizab... |
'''
Consigna: En lista Tweets tenemos el texto de 5 tweets.
Crear una nueva variable Lista_Palabras, del tipo lista, y colocar ahí los strings de todas las palabras que aparecen en los 5 Tweets.
Extra: Intentar que las palabras que aparecen repetidas en los tweets aparezcan una sola vez en la lista (es posible que t... |
#!/usr/bin/python3
"""
Outlook online calendar event popup notifications for the absent-minded
Requires O365, dateutil, and PyQt5 packages
Note: multiple-desktop users should configure their window manager to
make the popup appear on all desktops.
"""
import os, sys, time, datetime, pickle, threading
import dateu... |
A, B = map( int, input().split())
print( max([A+ A-1, B + A, B + B -1]))
|
current_users = ['aaA', 'bbb', 'ccc', 'ddd', 'eee']
new_users = ['qqq', 'aAa', 'www', 'BBB', 'ppp']
for new_user in new_users:
flag = 0
for current_user in current_users:
if new_user.lower() == current_user.lower():
flag = 1
break
if flag == 1:
print(new_user + " h... |
import requests
from credentials import client_id, client_secret
import urllib
from flask import Flask, request
from pprint import pprint
access_token_url = "https://github.com/login/oauth/access_token"
authorize_url = "https://github.com/login/oauth/authorize"
data = {
"client_id": client_id,
"redirect_uri": "htt... |
from nmt.modeling.transformer.multiheadattention import MultiHeadAttentionLayer
from nmt.modeling.transformer.positionwiseff import PositionwiseFeedforwardLayer
from nmt.modeling.transformer.encoder import Encoder
from nmt.modeling.transformer.decoder import Decoder
from nmt.modeling.transformer.transformer import Tran... |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(pre_seq, mid_seq, tree, left):
"""前序遍历第一个节点就是根节点,在中序遍历里面,1左边的节点都是左子树的节点,右边是右子树的节点
那么根据相应的前序遍历结果确定左子树和右子树,递归处理"""
if not pre_seq or not mid_seq:
... |
# coding:utf-8
# 轮盘赌算法
import numpy;
import random;
from calfitValue import calfitValue;
def gamble(pop):
temp = []
newfit_value = []
pop_len = len(pop)
# 适应度总和
for i in range(pop_len):
fit = calfitValue(pop[i])
temp.append(fit)
total_fit = sum(temp)
for i in range(len(temp)):
newfit_value.append(temp[i... |
from django.http import request
NAME = "PERPUSTAKAAN"
context = {
"name":NAME,
"request":request,
} |
from optparse import OptionParser
import os
import numpy as np
from itertools import product
from subprocess import call
def parse_args():
parser = OptionParser()
parser.set_defaults()
parser.add_option("--n_seeds", type="int", dest="n_seeds")
(options, args) = parser.parse_args()
... |
#!/usr/bin/python
import subprocess
import os
import sys
"""
This script attempts to disable hyperthreading by forcing offline all
hyperthreads on a each core except one.
"""
def disable(coreId):
os.system("/bin/echo 0 > /sys/devices/system/cpu/cpu{}/online".format(coreId))
print "Disabled Core {}.".format(c... |
"""
This example uses the distributed training aspect of Determined
to quickly and efficiently train a state-of-the-art architecture
for ImageNet found by a leading NAS method called GAEA:
https://arxiv.org/abs/2004.07802
We will add swish activation and squeeze-and-excite modules in this
model to further improve upon... |
# REST Framework
from rest_framework import generics, permissions, status
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.test import APIRequestFactory, APITestCase
# User class fr... |
from bs4 import BeautifulSoup as soup
import re
cpfs = []
with open(input("digite o nome dos dados: ")+'.txt','r') as arq:
arqui = arq.read().strip()
regex = re.findall('([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})',arqui)
for dados in rege... |
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
# database & migrations
migrate = Migrate()
db = SQLAlchemy()
class User(UserMixin, db.Model):
"""
User authentication
sou... |
##
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
# File: breaksolver.py
#
# Purpose: Show how to break a long-running task.
##
import sys
import mosek.fusion
from mosek.fusion import *
import random
import threading
import time
def main():
timeout = 5
n = 200 # num... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
try:
import pyqtgraph
except ImportError:
raise ImportError("Required package `pyqtgraph` not found. "
"Please install it to proceed.")
try:
import fabio
except ImportError:
raise ImportError("Required ... |
#=========================================================================
# pisa_jalr_test.py
#=========================================================================
import pytest
import random
import pisa_encoding
from pymtl import Bits
from PisaSim import PisaSim
from pisa_inst_test_utils import *
#--------... |
import queue
import threading
import time
class OrangeBall_Handler:
def __init__(self, queue_size):
#using a queue to store unfiltered data
self.ball_queue = queue.Queue(queue_size)
self.ball_data = queue.Queue(queue_size)
def put(self, message):
if(self.ball_queue.full()):
self.ball_queue.get(2)
sel... |
from django.contrib import admin
from task_management.models import TaskList
# Register your models here.
admin.site.register(TaskList)
|
# Generated by Django 3.2.3 on 2021-05-29 21:05
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Airport',... |
# Generated by Django 3.1.1 on 2020-09-20 15:38
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MovieDetails',
fields=[
('place', models.In... |
from flask import Flask, render_template, request
from werkzeug.debug import DebuggedApplication
from marvel_characters import character_info, character_images
import random
app = Flask(__name__)
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
heroes = character_images.keys()
real_name = character_images.value... |
from wtforms import Form,StringField,IntegerField
from wtforms.validators import Length,Regexp,EqualTo,ValidationError,InputRequired,Email
from utils.memcached import mc
from apps.models import OrderModel
from .models import UserModel
from flask import g
class Verify_regist(Form): ... |
#Sorting Contours
"""
Sorting Contours is quite useful when doing image processing
Sorting by Area can assist in Object Recognition (using contour area)
means firt the shape with largest area will be contoured and then it follows the decresing order
-Eliminate small contours that may be noise
-Extract the largest ... |
import prism.settings
from prism.server import Server
from prism.prism import Prism
prism.settings.init()
files_dict = prism.settings.prism.getFiles(\
prism.settings.prism.getVideos()['maluco'])
Server(5000, files_dict).start() |
# curriculum.py
#
# written by yuxq in 2018/9/15. all rights reserved.
class Info:
class_name = ""
holding_school = ""
teacher_name = ""
teacher_title = ""
population = 0
def get_full_teacher_name(self):
return self.teacher_name + " " + self.teacher_title
class Arrangement:
# 单次... |
# DEEP BELIEF NETWORK (DBN)
'''
One problem with traditional multilayer perceptrons/artificial neural networks is that backpropagation can
often lead to “local minima”. This is when your “error surface” contains multiple grooves and you fall into
a groove that is not lowest possible groove as you perform gradient d... |
"""
Implement Binary Search: given a sorted array and a target, return index of the target in the array or None is the target is not in the array.
Compare the target to the middle element of the array.
If target equals the middle element, return the index of the middle element.
If the target is less than t... |
from django.test import TestCase
from .models import Meeting, Resource, Meetingminutes, Event
from .views import getResource, getMeeting
from django.urls import reverse
from django.contrib.auth.models import User
# Create your tests here.
class MeetingTest(TestCase):
def test_string(self):
type=Meeting(me... |
import datetime
from sqlalchemy import func
from model import User, Meal, mealMedia, mealType, connect_to_db, db
from model import app
def load_users(user_filename):
for i, row in enumerate(open(user_filename)):
row = row.rstrip()
user_id, first_name, last_name, email, password = row.split("|") ... |
from fastapi import Depends, FastAPI
from fastapi_etag import add_exception_handler
from sqlalchemy.orm import Session
from . import models, schemas, deps
from .database import engine
from .routers import orders
models.Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Restbucks",
description="An AP... |
import networkx as nx
from networkx.drawing.nx_pydot import read_dot
G = nx.fast_gnp_random_graph(20,2/20.,directed=True)
print(G)
print(list(G.nodes()))
#nx.relabel_nodes(G,{u:int(u)-1 for u in G.nodes()},copy=False)
print(list(G.nodes()))
from networkx.readwrite import json_graph
import simplejson as json
data1 = ... |
import signal
import torch
from factory import create_scheduler, create_callbacks, create_model, create_loss, create_optimizer, \
create_train_dataloader, create_val_dataloader, create_device, create_metrics
from callbacks import Callback, StopAtStep
import logging
from collections import OrderedDict
from itertools... |
from __future__ import print_function
import os
import tensorflow as tf
import gym
from alg.PeterKovacs.ddpg import DDPG
import numpy as np
BASE_PATH = '../out/tests/'
RANDOM_SEED = 2016
def launch(proc, env_name, episodes=125000, steps=None, save_every_episodes=100, reuse_weights=False):
def func_name():
... |
GOOGLE_MAPS_KEY = 'AIzaSyB4tmlZXpBLzNF2x9Am6RjL5jOsIUwujd8'
|
from collections import namedtuple
import numpy as np
from colosseum.games import GameTracker
Move = namedtuple('Move', ['player', 'horizontal', 'row', 'col'])
class ImmutableArray:
"""
A wrapper for a numpy array that exposes acceesses but not modifications.
There will be ways to circumvent this through __get... |
# WRITTEN BY MILO HARTSOE (SOME CODE USED FROM STACKOVERFLOW)
from __future__ import print_function
import string
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
import matplotlib.image as mpimg
file_prefix = 'letter_data_'
width = 6
height = 8
def char_to_pixels(text, pat... |
#-*- coding:utf-8 -*-
import datetime
import time
import json
from celery import Task
from celery.task import task
from celery.task.sets import subtask
from django.conf import settings
from django.db.models import Sum,Max
from django.db import transaction
from django.db.models.query import QuerySet
from shopback ... |
import time; #引入time模块
ticks = time.time()
print("当前时间截至为:",ticks)
localtime = time.localtime(time.time())
print("本地时间为: ",localtime)
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为: ",localtime)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
print(time.strftime("%a %b %c %H:%M:%S %y... |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Post
from django.utils import timezone
from django.contrib.auth.decorators import login_required, user_passes_test
import requests
from selenium import webdriver
import time
from selenium.webdriver.common.keys import... |
__author__ = 'natalie'
from bot.config import config
def error(message):
return 'Error: {}'.format(message)
def not_valid_args(args, message=None):
err = 'arguments not valid'
if args:
err += ': {}'.format(args)
if message:
err += '\n{}'.format(message)
return error(err)
def... |
from flask import Blueprint
notification = Blueprint('notification', __name__)
from . import logic |
# log/urls.py
from django.urls import path
from . import views
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# 127.0.0.1:8000/log/
path('', views.index, name='index'),
# Signup/Account Creation
url(r'^signup/$', views.sign... |
print('welcome to the Gingerbread_Checkers launcher')
print('would you like to start a new game?')
wu = input('>>>')
yes = 'yes'
Yes = 'Yes'
no = 'no'
No = 'no'
def y():
print('okay, starting new game')
def x():
print('okay then')
if wu = yes:
y()
if wu = Yes
y()
if wu = no
x()
if wu = No
x()
else:
print('error... |
import nltk
text="Dan's parents were overweight.,Dan was overweight as well.,The doctors told his parents it was unhealthy.,His parents understood and decided to make a change.,They got themselves and Dan on a diet.".split(',')
print [sen.lower() for sen in text]
print [nltk.word_tokenize(sen) for sen in text]
wnl=... |
"""
Object
The Object is the "naked" base class for things in the game world.
Note that the default Character, Room and Exit does not inherit from
this Object, but from their respective default implementations in the
evennia library. If you want to use this class as a parent to change
the other types, you can do so b... |
from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> List:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for i in range(n-1, -1, -1):
if nums[i] > nums[i-1]:
small_num = nums[i-1]
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 19:08:59 2021
@author: Gustavo
@mail: gustavogodoy85@gmail.com
"""
#%% Ejercicio 2.18 Balances
import csv
#from pprint import pprint
def leer_camion(ruta_archivo):
camion = []
with open(ruta_archivo, 'rt') as f:
rows = csv.reader(f)
header =... |
import pprint
import xmltodict
import yaml
from typing import Dict, List, Union
from convertlib import is_null, simplify_attr_list, ensure_list
with open('vos.xml', 'r') as vo_xml_file:
# Use dict_constructore = dict so we don't get ordered dicts, we don't really care about ordering
parsed = xmltodict.parse(v... |
# search
@api.route('/search', methods=['POST','GET'])
@allow_cross_domain
def search_api():
rd = request.get_data().decode()
print(rd)
rd = json.loads(rd)
searched = search.search_api(rd['sentence'])
return jsonify(searched)
# return jsonify(searched)
@api.route('/search/<s>', methods=['GET'])... |
from abc import ABCMeta, abstractmethod
class AbsProxySensorTemperatura(metaclass=ABCMeta):
@abstractmethod
def leer_temperatura(self):
pass
|
# Do the following commands in the mongo shell
"""
use nlp100
db.artists.find({name: "Queen"})
"""
from pymongo import MongoClient
client = MongoClient("localhost")
db = client.nlp100
collection = db.artists
for idx, data in enumerate(collection.find({"name": "Queen"})):
assert isinstance(data, dict)
print(i... |
import time
import threading
from datetime import datetime
from config import basedir, LIGHT_START_TIME, LIGHT_ON_TIME, REQUIRED_FEED_LAPSE, REQUIRED_AUTOFEED_LAPSE
class Aquarium(object):
def __init__(self, lightStartTime=LIGHT_START_TIME, lightOnTime=LIGHT_ON_TIME):
self.lightOnTime = lightOnTime
... |
import sys
import copy
import rospy
import StringIO
from std_msgs.msg import String
from std_msgs.msg import Header
from std_msgs.msg import Int64
from StringIO import StringIO
import moveit_commander
import moveit_msgs.msg
from moveit_msgs.msg import PositionIKRequest, RobotState
from moveit_msgs.msg import RobotTra... |
import os
import os.path as op
import sys
import shutil
import argparse
import subprocess
# Directories/paths
this_dir = os.path.dirname(os.path.realpath(__file__))
template_origin_path = os.path.join(this_dir, 'xlwings_template.xltm')
if sys.platform.startswith('win'):
win_template_path = op.join(os.getenv('APP... |
#!/usr/bin/python -tt
#Derek Ruiz, csce470-500
"""
NOTES:
program scores documents by the summation of their tf-idf scores
------------------------------------------------------------------------------------------
This program returns a list of how many iterations it takes for convergence before
returning clusterin... |
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import time
import matplotlib.pyplot as plt
import os
class Config:
def __init__(self):
self.img_shape = [28,28,1]
self.filters = 16
self.z_dim = 20
self.sample_num = 49
self.batch_size = 4096
... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# import time module
# Author: Eason
import time
local_time = time.localtime(time.time())
time = time.time()
print "=" * 24
print "累计从1970年到现在的总累计时间"
print time
print "=" * 24
print "本地时间是:", local_time
print "=" * 24
|
import hug
@hug.get()
def hello_world():
return "Hello world!"
|
from topology import *
from util import *
def make_rout_xml(T, out_f):
with open(out_f, 'w') as of:
print('<filteringDatabases>', file=of)
for i in range(T.node_n):
print('\t<filteringDatabase id="switch{}">'.format(i), file=of)
print('\t\t<static>', file=of)
pr... |
#!usr/bin/env python
import sys
"""def hello():
print "Hello, World!"
"""
def usage():
print >> sys.stderr, "Usage python %s <filename>" % (sys.argv[0])
def main():
#print "Program arguments are: ", sys.argv
#print "No of arg is: ", len(sys.argv)
if len(sys.argv) != 2:
usage()
... |
#coding: utf-8
#生成器,输出杨辉三角形
def triangle(n) :
b = [1]
yield(b)
t = 1
while t < n :
b = [1] + [ b[i] + b[i+1] for i in range(len(b)-1)] + [1]
t += 1
yield(b)
n = input()
for t in triangle(n) :
print t
|
#!/usr/bin/env python3
import os
# Specify the locations of the Monte Carlo simulations and data directories here.
# Edit these variables to point to the right place for you.
data_dir = "/Users/thomasedwards/Dropbox/Work/DM/Indirect/AMCs/axion-miniclusters/Andromeda_data/"
montecarlo_dir = "/Users/thomasedwards/Dropb... |
from flask import Flask ,jsonify,request,render_template
from flask_restful import Api , Resource
import numpy as np
import torch
import json
from sentence_transformers import SentenceTransformer
import torch
import json
import sentencepiece
from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config
a... |
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.metrics import accuracy_score, r2_score
# from sklearn.svm import LinearSVC, SVC
from sklearn.neighbors ... |
# -*- coding: utf-8 -*-
import telebot
import os
import requests
import time
import random
from yobit import get_btc
from yobit import get_money
from telebot import types
from flask import Flask, request
from flask_sslify import SSLify
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token, threaded=False)... |
# -*- coding: utf-8 -*-
import numpy as np
import torch
from torch import Tensor
import matplotlib.pyplot as plt
################ Generate data ################
def generate_disc_set(nb):
"""Generate dataset
INPUT
nb: number of points to generate
OUTPUT:
data
labels with one hot ... |
import os
import sys
import pdb
# You might need to run this in the query images folder:
# sips -r -90 *.JPG && sips -r 90 *.JPG or sips -r 270 *.JPG
build_retrieval_database = sys.argv[1]
create_correspondences = sys.argv[2]
run_direct_matching_3D_points_feature_builder = sys.argv[3]
query_image_arg = sys.argv[4] # ... |
#/usr/bin python
from findblobsXGC import findblobsXGC
from trackblobsXGC import trackblobsXGC
import adios as ad
import numpy as np
from matplotlib.tri import Triangulation,LinearTriInterpolator
from IPython.parallel import Client
rc = Client()
dview = rc[:]
with dview.sync_imports(): #these required by findblobsXGC... |
import torch
from torch import nn
from einops import rearrange, repeat
##################################
# Linformer
##################################
def get_EF(input_size, dim, method="learnable", head_dim=None, bias=True):
"""
Retuns the E or F matrix, initialized via xavier initialization.
... |
import copy, os, sys
from RootTools.core.Sample import Sample
import ROOT
# Logging
import logging
logger = logging.getLogger(__name__)
from TopEFT.samples.color import color
# Data directory
try:
data_directory = sys.modules['__main__'].data_directory
except:
#from TopEFT.Tools.user import data_directory as... |
from django.apps import AppConfig
class RecommendAppConfig(AppConfig):
name = 'recommend_app'
|
from rest_framework import serializers
from kratos.apps.pipeline.models import Pipeline
from kratos.apps.task.serializers import TaskSerializer as TaskField
from kratos.apps.app.serializers import AppSerializer as AppField
class PipelineListSerializer(serializers.ModelSerializer):
class Meta:
model = ... |
'''from math import sqrt
n = int(input('miximal number'))
for a in range(1,n+1):
for b in range(a,n):
c_square = a**2 + b**2
c = int(sqrt(c_square))
if ((c_square - c**2)) == 0:
print(a, b, c)'''
#ex of nested for
#program for printing pythogorean number
travelling = input('yes,... |
import cv2
import numpy as np
import argparse
from kernels import kernels
import time
def filter(image2D,kernel,norm=True):
padding = int((kernel.shape[0]-1)/2)
image2D_pad = np.pad( image2D, padding )
new_image = np.zeros( image2D.shape )
for x in range( image2D.shape[0] - padding ):
for y... |
# Testing Local Webpages
##Localhost Test
* Goto "http://bs-local.com:45691/check"
* Page title
|
print("{}, {}".format("Hello","World"))
print("{0}, {1}, {0}".format("Hello", "World"))
print("{first}, {last}".format(first="Hello", last="World"))
# Since 3.6
var = 8
print(f"{var}")
# < align to left, ^ center, > right
print('{a:<10}|{a:^10}|{a:>10}'.format(a='test'))
# padding
print('{a:*<10}|{a:*^10}|{a:*>10}'.f... |
import bleach
import psycopg2
import datetime
def most_popular_articles():
"""Return the most popular three articles of all time from 'news' , most viewed first."""
db = psycopg2.connect(database="news")
c = db.cursor()
c.execute("SELECT path, count(*) AS num FROM log "
+"WHERE path = path AND status = '200... |
from tabulate import tabulate
def print_ip_table(reach_ip, unreach_ip):
table = {"Reachable": reach_ip, "Unreachable": unreach_ip}
print(tabulate(table, headers="keys"))
if __name__ == "__main__":
reach_ip = ["10.1.1.1", "10.1.1.2"]
unreach_ip = ["10.1.1.7", "10.1.1.8", "10.1.1.9"]
print_ip_tabl... |
import requests
import jwt
# TODO: rewrite tests with Flask, properly
r = requests.get(
'http://188.120.249.89/',
headers={
'X-Auth-Token': jwt.encode(
{'user_id': -1}, key='_1R*Ng_K3Y', algorithm='HS256'
).decode('utf-8')
},
params={'url': 'https://github.com/linuxwacom/in... |
from decimal import Decimal
import boto3
dynamodb = boto3.resource('dynamodb',region_name='eu-west-2')
table = dynamodb.Table('Samples')
table.put_item(
Item={
'timestamp': int(1),
'values': [Decimal('1.2'), Decimal('1.3'), Decimal('2.4'),
Decimal('0.0'), Decimal('0.4'), Decimal... |
import cv2
# importing the Coco Classname
classNames = []
classFile = 'coco.names'
with open(classFile, 'rt') as cocoNames:
classNames = cocoNames.read().rstrip('\n').split('\n')
# importing the configuration files
configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = 'frozen_inference_graph.... |
def story_intro():
"""
Introduction to the game and game name
"""
print(" *****************************************")
print()
print("Adventure game that brings you through a Wonderland")
print("with Alice. Meet fantastic creatures along the way")
print("and help restore balance to W... |
#!/usr/bin/env python3
from control import *
inst = 'cpu-cycles,instructions'
cache_l0 = 'raw-l1-dcache,raw-l1-icache'
cache_l1d = 'raw-l1-dcache,raw-l1-dcache-refill,raw-l1-dcache-wb'
cache_l1i = 'raw-l1-icache,raw-l1-icache-refill'
cache_l1 = 'raw-l1-dcache-refill,raw-l1-icache-refill,raw-l1-dcache-wb'
cache_l2 = 'r... |
def bank(dec1, dec2):
def Bank(func):
def wrapper(func1, func2):
print('This is my first choice of {} :{} at {} and my second choice is {} at {} '.format(func.__name__, dec1, dec2, func1, func2))
return func(func1, func2)
return wrapper
return Bank
#This will collect my... |
# -*- encoding: utf-8 -*-
# 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,用*号替换
__author__ = 'Administrator'
import re;
import os;
def initWords():
words = list()
with open("filtered_words.txt", "r") as f:
for line in f:
aline = re.findall(r'\w+', line)
for senceWords in a... |
from io import BytesIO
from PIL import Image
from django.core.files.storage import default_storage
FORMATS = {
"jpeg": "JPEG",
"png": "PNG",
"webp": "WebP",
"bmp": "BMP",
"tiff": "TIFF",
}
CONVERTIBLE_FORMATS = {
"jpeg": ["png", "webp", "bmp", "tiff"],
"png": ["jpeg", "webp", "bmp", "tif... |
#/bin/env python3
# Copyright (c) Moises Martinez by Fictizia. 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
#
# Unle... |
'''
全局配置文件
'''
target_list = ["172.17.{}.1:8080".format(i) for i in range(1,5)]
self_host = "172.17.5.1"
# shell_pass = "4rk1i9ht" |
"""python Mini Project #1 | Python Tutorials For Absolute Beginners In Hindi #71
As we have nearly completed our Python object-oriented programming concepts, now it is time to do a mini-project.
Statement:-
The task is to create an “Online Library Management System”. For this, you have to create a library class that i... |
import json
from datetime import datetime
from decimal import Decimal
from ..exceptions import NoRawTXData
from unittest import TestCase
from unittest.mock import MagicMock, patch
from xml.dom.minidom import parseString
from dicttoxml import dicttoxml
from apprisetransactions import settings
from apprisetransactions.... |
import unittest
from app import database_connector, user
import sqlite3
class DatabaseTest(unittest.TestCase):
def test_access(self):
filename = 'test_database.db'
db = database_connector.DatabaseConnector(filename)
self.assertEqual(type(db.c), sqlite3.Cursor)
db.close()
def t... |
import matplotlib.pyplot as plt
import numpy as np
inputFolder = "../Data/"
outputFolder = "../Plots/"
showImage = True
#TODO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! need to think about what plots should start at 0
def endPlot():
if showImage:
plt.show()
else:
plt.close()
def makePerfAnalysis(filePath, title, ou... |
# coding: utf-8
'''
# Gestures for Pythonista
This is a convenience class for enabling gestures in Pythonista UI applications, including built-in views. Main intent here has been to make them Python friendly, hiding all the Objective-C stuff. All gestures correspond to the standard Apple gestures, except for the cus... |
# Program with a Nepali class and a subclass Newari
class Nepali:
def __init__(self):
print("Namaste")
class Newari(Nepali):
def __init__(self):
Nepali.__init__(self)
print("Jujulapa")
n1 = Newari()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.