text stringlengths 8 6.05M |
|---|
import urwid
import ethernet
from list_box_item import ListBoxItem
class PacketListBox(urwid.ListBox):
def __init__(self):
self.criteria = []
self.data = []
self.widgets = []
self.content = urwid.SimpleListWalker(self.widgets)
urwid.ListBox.__init__(self, self.content)
... |
import logging
import colorlog
class ConsoleLoggerFactory:
def create(self):
logger = logging.getLogger("console")
logger.setLevel(logging.DEBUG)
format_str = "%(message)s"
date_format = "%H:%M:%S"
cformat = "%(log_color)s" + format_str
formatter = colorlog.Colored... |
# Generated by Django 2.1.5 on 2019-02-01 09:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Espn', '0005_profile_active'),
('Espn', '0004_auto_20190201_0539'),
]
operations = [
]
|
from keras.constraints import maxnorm, Constraint
from keras.layers import Input, Masking, GRU, merge, Dense, TimeDistributed, BatchNormalization, Activation, Dropout, Conv1D, RepeatVector ,Lambda
from keras.models import Model , Sequential
from keras.layers import concatenate,Bidirectional
from keras.layers.merge ... |
import json
import time
from requirementmanager.grpc_client.client import GrpcClient
grpc_client = GrpcClient()
_TYPE_MAP = {
'FR': '2',
'NFR': '3',
'RR': '4',
}
_RTYPE_MAP = {
'0': None,
'1': '最大',
'2': '最小',
'3': '平均',
}
_SIGN_MAP = {
'1': '小于',
'2': '大于',
'3': '等于',
... |
import logging
import os
import unittest
from typing import Union, Dict
from rdflib import Graph, BNode, URIRef, Literal
from funowl.base.rdftriple import TRIPLE
from funowl.converters.functional_converter import to_python
from tests.utils.build_test_harness import ValidationTestCase
from tests.utils.rdf_comparator i... |
"""
Time/Space Complexity = O(1)
"""
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0: return 1
size = N.bit_length()
mask = (1 << (size)) - 1
return N ^ mask |
from selenium import webdriver
import logging
import time
class LoginPage():
user_inp_loc =('xpath','//input[@formcontrolname="userName"]')
password_inp_loc = ('xpath','//input[@formcontrolname="password"]')
login_btn_loc = ('xpath','//button[@type="submit"]')
def __init__(self,driver):
self.dr... |
"""Staten Generaal Digitaal corpus ingestion."""
import os.path
import glob
import pandas as pd
from ..dbutils import session_scope
from ..tokenize import terms_documents_matrix_ticcl_frequency
from ..sacoreutils import add_corpus_core
def ingest(session_maker, base_dir='', sgd_dir='SGD', **kwargs):
"""Ingest ... |
import tempfile
from argparse import ArgumentParser
import os
import cv2
import numpy as np
from cytomine import Cytomine, CytomineJob
from cytomine.models import AlgoAnnotationTerm, Annotation
from cytomine_sldc import CytomineSlide, CytomineTileBuilder
from shapely.affinity import affine_transform, translate
from sk... |
#codinng=utf-8
import pytesseract
from PIL import Image
from ShowapiRequest import ShowapiRequest
#image = Image.open("E:/imooc2.png")
#text = pytesseract.image_to_string(image)
#print(text)
r = ShowapiRequest("http://route.showapi.com/184-4","62626","d61950be50dc4dbd9969f741b8e730f5" )
r.addBodyPara("typeId", "35")
r... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
def landing(request):
"""For normal servers, return our project landing page. For maint servers,
show our maintenance page. Hiring shows a little banner stripe."""
hiring=True
c... |
from randnum import generate_random_num_str
if __name__ == '__main__':
for x in range(10, 20):
rand_number = generate_random_num_str()
print(f'{rand_number} length: {len(rand_number)}')
|
from django.conf.urls import url
from . import views
app_name = 'users'
urlpatterns = [
url(r'^register/$', views.UserRegister, name='register'),
# url(r'^login/$', views.UserLoginView.as_view(), name='login_test'),
url(r'^login/$', views.UserLogin, name='user_login'),
url(r'^logout/$', views.UserLogo... |
#form learned from https://www.youtube.com/watch?v=3XOS_UpJirU
from django import forms
class PersonForm(forms.Form):
state = forms.CharField(widget=forms.HiddenInput()) |
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets
from ImproveDeepNN.OptimizationMethods.opt_utils import *
from ImproveDeepNN.OptimizationMethods.testCases import *
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams... |
# -*- coding: utf-8 -*-
class basePage:
"""
所有pages的基类,所有的剩余page应该继承Page类
"""
def __init__(self, poco):
self.poco = poco
|
from django.urls import resolve
from rest_framework import status
from rest_framework.exceptions import ErrorDetail
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIRequestFactory
from cars.models import Car, Manufacturer, Rate
from cars.serializers import RateSerializer
from ... |
import os
import sys
import logging
cwd = os.getcwd()
directory_path = os.path.expandvars(f"{cwd}/logs")
log_file_path = os.path.expandvars(f"{cwd}/logs/error.log")
class Log:
def __init__(self) -> None:
self.info_log = logging.getLogger("INFO")
self.error_log = logging.getLogger("ERR... |
'''Write a Python program to remove a key from a dictionary. '''
Dict = {'a':12,'b':92}
print(Dict)
if 'b' in Dict:
del Dict['b']
print(Dict)
|
"""
tdc_config_local.py - tdc plugin-writer-specified values
Copyright (C) 2017 bjb@mojatatu.com
"""
import os
ENVIR = os.environ.copy()
ENV_LD_LIBRARY_PATH = os.getenv('LD_LIBRARY_PATH', '')
ENV_OTHER_LIB = os.getenv('OTHER_LIB', '')
# example adding value to NAMES, without editing tdc_config.py
EXTRA_NAMES = di... |
import numpy as np
def gaussian_filter(size, sigma):
# creates the x and y values for the filter
linspace_size = int(size / 2)
x, y = np.meshgrid(np.linspace(-2, 2, size), np.linspace(-2, 2, size))
# creates the gaussian filter using formula in book
fltr = np.zeros((size, size), dtype=np.f... |
import random
from django.core.management.base import BaseCommand
from faker import Faker
from school.models import School, Student
from school.enum import SexEnum, NationalityEnum
class Command(BaseCommand):
help = 'Initial Fake Data'
def add_arguments(self, parser):
# Positional arguments
p... |
import unittest
from countUniqueWords import unique_words_count
class countUniqueWordsTest(unittest.TestCase):
def test_count_unique_words_empty_list(self):
self.assertEqual(0, unique_words_count([]))
def test_count_unique_words_random(self):
self.assertEqual(
2, unique_words_co... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-14 13:42
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('experiment', '0005_crowd_doc'),
]
operations = [
migrations.RemoveField(
... |
def gcd(a,b):
while b!=0:
r = a % b
a = b
b = r
return a |
"""
Time Complexity = O(N^2)
Space Complexity = O(1)
"""
# TLE error
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if not gas or not cost:
return 0
def travel(indx, tcost = 0, start = 0):
if indx == len(gas) + start:
... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.7.10
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode\n')
try:
a = 10/0
print('a:',a)
except:
print('错误:捕获到异常') |
"""
Functions for dealing with ISO 8601 timestamps and intervals
"""
import datetime
import isodate
from tzlocal import get_localzone
from dateutil.tz import tzlocal
def iso8601_as_timedelta(iso):
"""Convert an ISO 8601 string to a timdelta"""
try:
duration = isodate.parse_duration(iso)
except i... |
import imageio
import numpy as np
#import matplotlib.pyplot as plt
from matplotlib import colors
import subprocess
import glob
import csv
'''
#--------------------------------------
district = 'Bangalore'
keyPostProcessing = 2
fileExtn = '.tif'
if fileExtn == '.png':
keyPreProcessing = 191
keyMode = 0
elif file... |
# -*- coding: utf-8 -*-
import sys
import tweetstream
import threading
import time
import Queue
import cPickle
import os
from lib.moodClassifierClient import MoodClassifierTCPClient
sys.path.append('dict')
import dictionary
import requests
# sys.path.append('../')
MCC = MoodClassifierTCPClient('127.0.0.1',6666)
words ... |
#!/usr/bin/env python
from datetime import datetime
start = datetime.now()
i=0
txt = ""
nb_coups = 6
maxi = 10 ** nb_coups
while (i != maxi):
for chiffre in str(i):
txt += chiffre + "-"
print(txt[:-1])
i += 1
txt = ""
end = datetime.now()
print(end-start) |
from python_algorithm.Sort.record import Record
from typing import List
def quick_sort_recursion(lst, start, end):
if start >= end:
return
small_list_start = start
large_list_start = end
pivot = lst[small_list_start]
empty_lot = small_list_start
is_pointer_front = False
while sm... |
import cv2
import numpy as np
import json
mask_definition_json = json.load(open('data/json/annotation_definitions.json', 'r'))
mask_definitions = {}
for spec in mask_definition_json['annotation_definitions'][1]['spec']:
label_name = spec['label_name']
r = round(spec['pixel_value']['r'] * 255)
g = round(spec... |
import unittest
from simpleNN import *
import numpy as np
class TestSimpleNN(unittest.TestCase):
"""
Our basic test class
"""
X = np.arange(15).reshape((5,3))
Y = np.array([1,1,1,0,0])
Theta1 = 1 * np.ones((4,5)) #4x5
Theta2 = 2 * np.ones((6,5)) #6x5
Theta3 = 3 * np.ones((6,... |
import os
from flask import Flask, render_template, request, send_file, Response, jsonify
import tempfile, csv
app = Flask(__name__, static_url_path='/static')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/download', methods=['GET','POST'])
def download():
if request.method ... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-csp-observer',
version='1.0.2',
description='A Django app that evaluates CSP reports to identify malicious activity.',
long_description=long_description,
long_description_content_ty... |
import os, re; from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'pysettings','__init__.py')) as fd:
__version__ = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(... |
import asyncio
from aiohttp import web, client
from modules.parser import MyHTMLParser
DEST_HOST = 'habr.com'
LOCAL_HOST = 'localhost'
LOCAL_PORT = 8080
async def handler(request):
headers = dict(request.headers)
headers['Host'] = DEST_HOST
if 'Referer' in headers:
headers['Referer'] = headers['R... |
#!/usr/bin/python
t= 10
def Run():
#global t
print 't=',t
#t= None
def Run2():
t2= 100
def RunInRun2():
#global t2 #ERROR
print 't2=',t2
#t2= None
RunInRun2()
Run()
Run2()
|
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for i in nums:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
maxx,index = 0,0
for i in dic.... |
#!/usr/bin/env python3
# encoding: utf-8
"""
bubble_sort.py
Created by Jakub Konka on 2011-11-01.
Copyright (c) 2011 University of Strathclyde. All rights reserved.
"""
import sys
import random as rnd
def bubble_sort(array):
'''This function implements the standard version of the
bubble sort algorithm.
Keyword... |
"""Work-A-Holic (WAH)
for that feeling of "WAH, how did I spend 200 hours on this?"
Adapted from https://github.com/acoomans/gittime
Work in progress
"""
import argparse
import yaml
from colorama import init, Fore, Style, Back
from git import Repo
from git.objects.commit import Commit # typing
from pathlib import Pa... |
import _winreg
import itertools
from collections import namedtuple
import windows
from windows.generated_def.windef import KEY_READ
class ExpectWindowsError(object):
def __init__(self, errornumber):
self.errornumber = errornumber
def __enter__(self):
pass
def __exit__(self, etype, e, t... |
#! /usr/bin/env python
import csv
import os
import argparse
from threading import Thread
from categorizer_tasks import query_yahoo, query_alexa
def parse_args():
parser = argparse.ArgumentParser('little script to gather the category labels given a list of sites')
parser.add_argument('-a', '--alexa', action='st... |
"""使用gunicorn运行服务.
注意,使用本项目的flask的log组件不能改变其log的format,但可以在配置文件中以`SERVER_CONFIG_`+[官方页面](http://docs.gunicorn.org/en/latest/settings.html#settings)
写出的配置项的大写来设置gunicorn的配置.从而修改log的形式.
推荐的设置有:
+ `"SERVER_CONFIG_ACCESS_LOG_FORMAT":"{\"remote_address\":\"%(h)s\",\"request_time\":\"%(t)s\",\"request\":\"%(m)s %(U)s\",\"... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 09:50:06 2017
@author: 29907
"""
#txt_regex -Look up all matched text in text file.
import re,os
#Open all text file.
file_list=os.listdir('.')
txt_list=[]
for file in file_list:
print(file)
if file[-3:]=='txt':
txt_list.append(file)
match_regex=re.c... |
#input
# 32 6
# Castor 551 641
# Procyon -922 -520
# Deneb -459 -741
# Mizar -221 -209
# Mira -34 -614
# Sirius -960 -76
# Alcor -76 339
# Heka 733 631
# Betelgeuse -814 -641
# Nembus -433 -71
# Thabit 53 -6
# Media -493 -567
# Gemma 425 -418
# Yildun -879 463
# Jabbah -135 -903
# Kochab 495 -585
# Bellatrix 738 574
# ... |
#! /usr/bin/python
# SPDX-License-Identifier: GPL-2.0-only
# -*- python -*-
# -*- coding: utf-8 -*-
# twatch - Experimental use of the perf python interface
# Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com>
#
import perf
def main(context_switch = 0, thread = -1):
cpus = perf.cpu_map()
threads = pe... |
#SetupDzdRules pushes defined rules to SQL table for later use
import Config.Config as config
import pandas as pd
import Tables.CreateDzdRules as DZDtable
def create_dzd_table():
""" create_dzd_table creates SQL table that will hold dzd rules """
cur = config.conn.cursor()
cmd = DZDtable.createTable
... |
# Generated by Django 3.1.2 on 2021-04-10 23:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('folder', '0003_folder_present_in_shared_me_of'),
]
operations = [
migrations.AddField(
model_name='folder',
name='si... |
import dash
import dash_design_kit as ddk
import dash_core_components as dcc
from dash.dependencies import Output,Input
import pandas as pd
from datetime import datetime
import plotly.graph_objs as go
import requests
r = requests.get("https://financialmodelingprep.com/api/v3/symbol/available-cryptocurrencies"... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('investigator', '0007_auto_20170607_1728'),
]
operations = [
migrations.RemoveField(
model_name='investigator',
... |
"""Brain progression game logic."""
import random
from typing import Tuple
PROGRESSIONN_LEN = 10
MIN_STEP = 1
MAX_STEP = 10
DESCRIPTION = 'What number is missing in the progression?'
def make_progression(min_step, max_step, progression_len) -> list:
"""
Make random arithmetic progression.
Args:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import uuid
from pathlib import Path
from typing import Optional, Union
import smorest_sfs
from .datetime import utctoday
UPLOADS = "uploads"
WHITE_LIST = [
Path("uploads", "avators", "default", "AdminAvator.jpg"),
Path("uploads", "avators", "default", ... |
import roslib
import rospy
from std_msgs.msg import Bool, Float64
import time
from tqdm import tqdm
import time, select
import math
from ackermann_msgs.msg import AckermannDrive
from gazebo_msgs.msg import ModelStates
positions = [0,0,0]
velocities = [0,0,0]
class PID:
def __init__(self, kp, kd, ki):
... |
from pippi import dsp
midi = {'lpd': 3}
def play(ctl):
param = ctl.get('param')
lpd = ctl.get('midi').get('lpd')
idxWf = param.get('idxWf', default=0)
idxWin = param.get('idxWin', default=0)
idxMod = param.get('idxMod', default=0)
freq = 220
length = dsp.mstf(lpd.get(8, low=50, high=... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
#matplotlib.use("cairo") # does not support rasterization of lines, but allow embedding subset of fonts
import matplotlib.pyplot as mpl
import pylab as pl
import os, sys
class Figure():
def __init__(self, title=None, lc="black", lw=1.1, pt='o', ps=None, ... |
HOST = "irc.twitch.tv"
PORT = 6667
PASS = "oauth:chmp4zoi9vx0zqll4zebr81wl2fsuz"
IDENT = "bobthemuffinman"
CHANNEL = "proleaguecsgo"
|
"""
fix_csv
Created November 12, 2019 by Jennifer Baughman
Description: This week we're going to normalize CSV files by writing a program, fix_csv.py,
that turns a pipe-delimited file into a comma-delimited file. I'll explain how it should work by
example.
Your original file will look like this:
Reading|Make|Model|T... |
from random import choice,random, sample, uniform
def mutate(agents, probability):
for agent in agents:
specimen_length = len(agent.value)
indexes = [i for i in range(specimen_length)]
number = int(probability*specimen_length)
to_be_mutated = sample(indexes,number)
... |
from flask import request
from requirementmanager.app import app
from requirementmanager.mongodb import (
requirement_collection, archive_requirement_collection,
requirement_tree_collection, archive_requirement_tree_collection
)
from requirementmanager.dao.requirement_list import RequirementListMongoDBDao
from... |
import numpy as np
def make_strictly_decreasing(x_interp, y_interp, prepend_value=3.7):
"""
Takes a monotonically decreasing array y_interp and makes it strictly decreasing by interpolation over x_interp.
Arguments:
x_interp {numpy.ndarray} -- The values to interpolate over.
y_interp {num... |
# Curso de lógica de programação
print('Hello World')
print('Curso de lógica de programação com Python') |
from brownie import Wei
DEADLINE = 99999999999
def test_forward_no_value_refund(liquid_lgt, relayer, storage, accounts):
initial_tokens = liquid_lgt.poolTokenReserves()
initial_balance = accounts[0].balance()
calldata = "60fe47b1000000000000000000000000000000000000000000000000000000000000000e"
... |
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
#####################################
### DATA IMPORT
#####################################
energy_df = pd.read_csv(r"DATA\EIA Energy Consumption by Sector.csv")
str(energy_df)
print(energy_d... |
class word(object):
def __init__(self):
pass
def read(self,n):
print(n)
def search(self,n,a):
wn=0
ln=0
flag=0
fword=""
for b in a:
if b!=" " and b!="\n" :
fword=fword+b
continue
elif b==" ":
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
t,x,y,x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7,x8,y8,x9,y9,tot_energy,potential,kinetic = np.genfromtxt('molecular_dynamics_2d_test.out').T
i,velocities_x,velocities_y = np.genfromtxt('mo_dy_velocities.out').T
plt.figure(1)
plt.... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class UserInfo(models.Model):
id = models.IntegerField(primary_key=True)
loginname = models.CharField(max_length=150)
truename = models.CharField(max_length=60)
groupname = models.CharField(max_length=80)
... |
#imports
from dinosaur import Dinosaur
class Herd:
#constructor
def __init__(self):
self.herd = [Dinosaur("Anklyosaurus", 100, 300, "Tail lash"), Dinosaur("Anklyosaurus", 100, 300, "Tail lash"), Dinosaur("Anklyosaurus", 100, 300, "Tail lash")]
#Methods
#Note: The Anklyosaurus delivers a painful bl... |
from PyQt4 import QtGui
from AddEmployeeUI import Ui_AddEmpDialog
import DB
from PyQt4.QtCore import QObject, pyqtSignal
class AddEmployee(QtGui.QDialog):
trigger = pyqtSignal()
def __init__(self, datelistDV3, exisitingnames):
self.lastDate = str(datelistDV3[6])
self.exisitingnames = exisiting... |
import unittest
from code import instance as i
from code import datamapping as dm
from code import greedyfirst as gf
from code import algorithm as a
from code import baseobjects as bo
from code import tabu
class TestTabuSpecific(unittest.TestCase):
def setUp(self):
raw_data = dm.Importer()
# ra... |
#!/usr/bin/python
print locals()
print 'a is defined' if 'a' in locals() else 'a is not defined'
a= 100
print locals()
print 'a is defined' if 'a' in locals() else 'a is not defined'
class Test:
def __init__(self):
#print locals()
print self.__dict__
print 'b is defined' if 'b' in self.__dict__ else 'b ... |
# Media entre números
opcao = 'S'
soma = 0
qtd = 0
maior = 0
menor = 0
while opcao == 'S':
valor = int(input('Digite um valor: '))
opcao = input('Deseja continuar (S/N)? ').strip().upper()
qtd += 1
soma += valor
if maior == 0 or valor > maior:
maior = valor
if menor == 0 or valor < menor... |
from django.urls import path
from . import views
urlpatterns = [
path('images/', views.images),
path('timeline/', views.timeline),
path('timeline/more_scene/', views.more_scenes),
path('timeline/group/', views.timeline_group),
path('timeline/info/', views.detailed_info),
path('more/', views.mo... |
#server_dw.sql
from flask import Flask, request, abort
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy import (Table, Column, Integer, String, MetaData, ForeignKey, Numeric)
from sqlalchemy import inspect
from sqlalchemy.orm import sessionmaker
from bson.json_util import dumps, default
impo... |
import gym
import time
import joblib
filename = "results/Humanoid-v3_results.pkl"
traj, _ = joblib.load(filename)
env = gym.make('Humanoid-v3')
env.reset()
env.env.sim.set_state(traj["sim_states"][0].x)
env.env.sim.forward()
env.render()
for z, action in enumerate(traj["actions"]):
if z > 0:
env.env.si... |
"""
Django settings for workshop project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... |
#!/usr/bin/env python
# Funtion:
# Filename:
import hashlib
'''
# md5
m = hashlib.md5()
m.update(b'hao123')
print(m.hexdigest())
m.update(b'456')
print(m.hexdigest())
m2 = hashlib.md5()
m2.update(b'hao123456')
print(m2.hexdigest())
# sha1
ha1 = hashlib.sha1()
ha1.update(b'hao1236789')
print(ha1.hexdigest())
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block Amc
# Generated: Sat May 12 10:36:31 2018
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform... |
# -*- coding: utf-8 -*-
# tensorflow 实现 cnn 识别手写数字
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("data/", one_hot=True)
tf.reset_default_graph()
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 28, 28, 1]) # shape in CNN... |
import time
ALIVE = '*'
EMPTY = '-'
class Grid:
def __init__(self, height, width):
self.height = height
self.width = width
self.rows = []
for _ in range(self.height):
self.rows.append([EMPTY] * self.width)
def get(self, y, x):
return self.rows[y % self.height][x % self.width]
def set(self, y, x, ... |
# Created By Colton Fetters @ Bardel Entertainment 2016
# Contact info cfetters@bardel.ca, seat number 1141
#
# This Toool was designed to help Bardel artist quickly edit set up there sets
#
#
# Version:
# 1.0: initial release
#
# import maya module
import maya.cmds as cmds
import maya.mel as mel
from functools... |
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Apache License, version 2.0.
# If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www.apache.org/licenses/LICENSE-2.0.
# SP... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 16:10:36 2020
@author: Th0ma
"""
import cv2 as cv
import os
from matplotlib import pyplot as plt
import numpy as np
def isValid(filepath):
return os.path.exists(filepath) and os.path.isfile(filepath)
def Harris_simple(filepath):
img = cv.imread(filepat... |
# Converte metros para centimetros e milimetros
metros = int(input('Digite a quantidade em metros:'))
print('Metros: {}\nCentímetros: {}\nMilímetros: {}'.format(metros, metros * 100, metros * 1000))
|
#!/usr/bin/python3
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data)
inorder(root.right)
def postorder(root):
if root is None:
return
postorder(root.left)
postorder(... |
numero_filas=5
numero_columnas=5
matriz = []
for i in range(2):
matriz.append([])
for j in range(3):
matriz[i].append("relleno")
print(matriz)
#Otra Manera de Crear una Matriz
matriz = [0] * numero_filas
for i in range(numero_filas):
matriz[i] = [0] * numero_columnas
print (matriz) |
# 443. String Compression
#
# Given an array of characters, compress it in-place.
# The length after compression must always be smaller than or equal to the original array.
# Every element of the array should be a character (not int) of length 1.
# After you are done modifying the input array in-place, return the new ... |
from bifrost.src.CommonTestUtils import BaseTestUtils
class TestCreateTimeline(BaseTestUtils):
"""
Testing the timeline model.
"""
def setUp(self):
self.simple_setup()
def test_user_timeline_relationship(self):
"""
Testing the timeline and the user relationship works.
... |
import cv2 as cv
import numpy as np
'''Constants'''
# Which camera to use.
CAM_IDX = 0
# Left camera parameters.
FX_L = 720
FY_L = 720
CX_L = 640
CY_L = 360
K1_L = -0.15
K2_L = 0
MTX_L = np.array([
[FX_L, 0, CX_L],
[ 0, FY_L, CY_L],
[ 0, 0, 1]
])
DIST_L = np.array([K1_L, K2_L, 0, 0])
# Righ... |
from flask import Flask
from dash import Dash
#import dash_auth
import dash_bootstrap_components as dbc
VALID_CREDENTIALS = {
'UserAux': 'AppyAux5GS'
}
server = Flask('dashboard')
app = Dash(
__name__,
meta_tags=[{"name": "viewport", "content": "width=device-width"}],
external_stylesheets=[dbc.theme... |
#!/usr/bin/env python3
import os
import re
import sys
import random
from optparse import OptionParser
from builtins import print
from docutils.nodes import line
from pyverilog.vparser.parser import parse
import pyverilog.vparser.ast as vast
from pyverilog.ast_code_generator.codegen import ASTCodeGenerator
... |
from collections import Counter
N = int( input())
S = [ input() for _ in range(N)]
CS = Counter(S)
ans = ""
ansn = 0
for s in CS:
if CS[s] > ansn:
ans = s
ansn = CS[s]
print(ans)
|
from queue import Queue
from threading import Thread
import random
import time
_sentinel = object()
def producer(out_q):
n=10
while n:
time.sleep(1)
data = random.randint(0,10)
out_q.put(data)
print("生产者生产了数据{0}".format(data))
n-=1
out_q.put(_sentinel)
def consumer... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
from weixin_sogou.items import WeixinSogouItem
import scrapy
class WeixinSpider(scrapy.Spider):
name = "weixin"
allowed_domains = ["sogou.com","mp.weixin.qq.com"]
start_urls = [
"http://weixin.sogou.com/"
]
def p... |
#!/usr/bin/env python
"""
Compare request names in the input table (dump from oracle_dump.py)
and CouchDB request database.
Usage:
python oracle_couchdb_comparison.py oracle_dump_request_table.py > comparison.log
needs to have credentials for accessing CMS web ready in
$X509_USER_CERT $X509_USER_KEY, or proxy s... |
# -*- coding: utf-8 -*-
# @Time : 2019/3/25 11:22
# @Author : xuyun
a = 148074776
b = 147974775
c = (a-b)/1024
print(c) |
import sys
#sys.argv[0] is filename of script, counts as first argument
# start cmd line args at sys.argv[1}
print "The name of this script is {}".format(sys.argv[0])
print "User supplied {} args at run time".format(len(sys.argv))
for arg in sys.argv[1:]:
print arg
while True:
try:
if len(sys.argv... |
import collections
import numpy as np
plane_cap = 30
city_count = 20
crate_count = int(0.7*plane_cap * city_count**2)
plane_count = 2
Edge = collections.namedtuple("Edge", ["i", "j", "cargo"])
PlaneEdge = collections.namedtuple("PlaneEdge", ["plane_idx", "i", "j", "cargo"])
def gen_crates_planes():
crates = np.z... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.