text stringlengths 38 1.54M |
|---|
#!/bin/python3
from ui import *
from xml.etree import ElementTree
import xml.etree.cElementTree as ET
import random as rdm
from tqdm import tqdm
from file_read_backwards import FileReadBackwards
def traduce (key, table):
"""
traduit (ce que je veux transformer en texte ou en binaire, le dictionaire d'encodage_... |
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os
np.random.seed(42)
# To plot pretty figures
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
... |
# Program to print full pyramid
num_rows = int(input("Enter the number of rows"));
for i in range(0, num_rows):
for j in range(0, num_rows-i-1):
print(end=" ")
for j in range(0, i+1):
print("*", end=" ")
print()
|
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib import auth
from .models import Accounts
def index(request):
u = auth.authenticate(username='martin', password='martin')
return HttpResponse("Yes, sir.") |
#!/usr/bin/python3
# Direcciones desde las que cogemos las cosas. La idea es generar un único XML
# Este contendrá primero la clasificación, y luego las 2 jornadas.
# http://resultados.as.com/resultados/futbol/segunda/clasificacion
# http://resultados.as.com/resultados/futbol/segunda/calendario
# Usamos la librería S... |
#ForLoopChallanges07.py
#Enoch
total = 0
for i in range(0,4):
num1 = int(input("Enter a number"))
q = str(input("Do you want that number to be included y or n"))
if q == "y":
total = total + num1
elif q == "n":
print("We will move on then")
print("The total is", total)
|
__all__ = ["login_router", "users_list_router", "reg_router", "items_router", "exchange_router"]
from .items import items_router, exchange_router
from .login import router as login_router
from .registration import router as reg_router
from .users_list import router as users_list_router
|
from flask import Flask, render_template, redirect
from models import db, connect_db, Pet
from forms import AddPetForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///adoption'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
app.config['SECRET_KEY... |
def is_isogram(string):
parse = string.lower().replace("-", "").replace(" ", "")
return len(set(parse)) == len(parse)
|
# Update Record (Update Query in MySQL)
import pymysql
connection=pymysql.connect(host='localhost',user='root',password='',db='crudpython')
myCursor=connection.cursor()
myCursor.execute("update record set Name='Camille Hernandez', Mobile='09072191005', Address='Pampanga' where Id='10'")
print ("Record Up... |
import cv2
import pdf2image
import pytesseract
import imageloc
import numpy
import pdfgenerator as gen
from pdf2image import convert_from_path, convert_from_bytes
def PtoCV(pil_image):
open_cv_image = numpy.array(pil_image)
# Convert RGB to BGR
open_cv_image = open_cv_image[:, :, ::-1].copy()
return... |
"""
design stack such that finding min is O(1) time
instead of implementing LL, use deque for py
"""
from collections import deque
class custom_stack():
def __init__(self):
self.stack = deque()
self.m = 0
def append(self, x):
if len(self.stack) == 0:
self.m = x
... |
import sys
import click
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager,UserMixin,login_user,logout_user,login_required,current_user
#配置数据库时报错
WIN = sys.platform.startswith('win')
if WIN:
pre = 'sqlite:///'
else:
pre = 'sqlite:///... |
# coding=utf-8
"""
@Author: Freshield
@Contact: yangyufresh@163.com
@File: test_fun.py
@Time: 2020-06-02 16:48
@Last_update: 2020-06-02 16:48
@Desc: None
@==============================================@
@ _____ _ _ _ _ @
@ | __|___ ___ ___| |_|_|___| |_| | @
@ | __| _| -... |
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""
https://leetcode.com/problems/construct-binary-tree-from-preord... |
from datetime import datetime
import numpy as np
import pandas as pd import matplotlib as mpl
import matplotlib.pyplot as plt
### 1. generate sequences of dates or time-spans
##
rng = pd.date_range('1/1/2011', periods=72, freq='H')
rng[:5]
ts = pd.Series(np.random.randn(len(rng)), index=rng)
converted = ts.asfreq... |
import numpy as np
def unpack_edges(edges):
return set(tuple(edges[i,:]) for i in xrange(edges.shape[0]))
def pack_edges(edges):
A=np.zeros((len(edges),2), dtype=np.int64)
for i,e in enumerate(edges):
A[i,:]=e
return A
def restrict(edges, full_edges):
return edges & full_edges
|
def gsheetplot():
import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow,Flow
from google.auth.transport.requests import Request
import os
import pickle
import matplotlib.pyplot as plt
SCOPES = ['http... |
from pVIPRAM_inputBuilderClass import *
class RankedEntity:
def __init__(self, ident, score):
self.id = ident
self.score = score
def __lt__(self, other):
return self.score < other.score
def convertStrToInt(str):
binNum = ""
for s in str.lower():
if ((ord(s) < 97) or (ord(s) > 122)):
continue
else:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-10-04 11:24
from __future__ import unicode_literals
from django.db import migrations, models
import viviendas.models
class Migration(migrations.Migration):
dependencies = [
('viviendas', '0021_auto_20181004_1322'),
]
operations = [
... |
#!/usr/bin/env python3
""" database testsuite """
from selenium_ui_test.pages.database_page import DatabasePage
from selenium_ui_test.pages.user_page import UserPage
from selenium_ui_test.test_suites.base_selenium_test_suite import BaseSeleniumTestSuite
from test_suites_core.base_test_suite import testcase
import trace... |
import logging
import re
from platypush.context import get_backend
from platypush.message.event import Event, EventMatchResult
class AssistantEvent(Event):
""" Base class for assistant events """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
self._ass... |
import cv2
import _thread
import time
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
from time import sleep
from PIL import Image
cap= cv2.VideoCapture('/home/pi/Downloads/videoplayback.mp4')
n_rows = 1
n_images_p... |
from fns.utils import *
from fns.functions import *
class BaseDataProvider(object):
"""
Abstract base class for DataProvider implementation. Subclasses have to
overwrite the `_next_data` method that load the next data and label array.
This implementation automatically clips the data with the given min/... |
import sys, json, csv
from random import randint, choice, uniform, random, sample
import os
cr = csv.reader(open("./iso-codes.csv","rb"))
countries=[]
for row in cr:
v, k = row
countries.append(v)
jsonFile = {
"input_file": "./states_provinces/ne_10m_admin_1_states_provinces.shp",
"name_field": "name",
"... |
# -*- coding:utf-8 -*-
import os
import torch
from torchvision import models
from numpy import random
import time, pickle
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from torch.utils.data import DataLoader
import torch.nn.functional as F
import numpy as np
U_LEARNING_RATE=3... |
# We run two threads:
# Thread 1 will take videos
# Thread 2 will check the videos and upload with appropriate flag
import os
import calendar
import time
from multiprocessing import Process
import sys
sys.path.append('./video')
import video_util
sys.path.append('./cloud')
import dropbox_util
import logging
# Mainly f... |
#!/usr/bin/env python
"""High-speed diffractometer.
F. Schotte, 31 Oct 2013 - 28 Jan 2016"""
__version__ = "1.0.3"
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from Ensemble import SampleX,SampleY,SampleZ,SamplePhi
window = Motor... |
from repoze.bfg.url import route_url
from checking.utils import render
def View(request):
return render("frontpage.pt", request,
login_url=route_url("login", request))
|
from sqlalchemy.exc import DatabaseError
from app.data.mysql import MySQL
from app.data.tables.category import Category
def add_category(title):
category = Category(title=title)
try:
return category.save()
except DatabaseError as e:
code = e.orig.args[0]
if code == 1062:
... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import unittest
from django.test.client import RequestFactory
from django.db.models import query
from django.contrib.admin.sites import AdminSite
from cities_light import admin as cl_admin
from cities_light import models as cl_models
class AdminTestC... |
"""Change virtual backgrounds or reactions when in zoom meetings"""
"""Used exact pixel position so not that good."""
import pyautogui as py
import time
from pixel_settings import PixelSettings
class changeVB: # change virtual background
def __init__(self):
self.ps = PixelSettings()
def open_virt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ReceiverInfoVO(object):
def __init__(self):
self._area = None
self._city = None
self._detail_address = None
self._mobile = None
self._name = None
s... |
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=150)
body = models.TextField(blank=True)
date_pub = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='posts/images/')
class Meta:
ordering = ['-date_pub']
def __str__(self):
ret... |
from datetime import datetime
from calendar import timegm
from nacl.signing import VerifyKey
from nacl.encoding import HexEncoder
from .fzencode import load, dump
def read_message(f):
size = load(f)
assert isinstance(size, int)
size += f.tell()
header = load(f)
pos = f.tell()
if pos < size:
... |
from django.forms import ModelForm
from emp.apps.videos.models import Video, VideoPlaylist
""" Form for creating new Video (upload) """
class VideoForm(ModelForm):
class Meta:
model = Video
# fields to display in upload form
fields = ('title','description','categories','tags','src_file')
""" Form for creating ... |
import FWCore.ParameterSet.Config as cms
initialStepTrajectoryFilterShapePreSplitting = cms.PSet(
ComponentType = cms.string('StripSubClusterShapeTrajectoryFilter'),
layerMask = cms.PSet(
TEC = cms.bool(False),
TIB = cms.vuint32(1, 2),
TID = cms.vuint32(1, 2),
TOB = cms.bool(Fal... |
#!/usr/bin/env python3
""" The Whole Barn """
def shape(matrix):
""" matrix shape """
shape = [len(matrix)]
while type(matrix[0]) == list:
shape.append(len(matrix[0]))
matrix = matrix[0]
return shape
def inception(mat1, mat2):
""" traverse """
add = []
for i in range(len(... |
import sqlite3
import uuid
import time
import json
import logging
logging.basicConfig(filename="./debug_logs/npmlite.log", level=logging.ERROR,
format="%(asctime)s:%(name)s:%(levelname)s:%(message)s")
db_logger = logging.getLogger("ManageDB")
class ManageDB:
"""Takes in database name, databa... |
# -*- coding: utf-8 -*-
# @Time : 2019/4/7 3:15
# @Author : Nismison
# @FileName: deal_json.py
# @Description: json处理函数
# @Blog :https://blog.tryfang.cn
def dict_get(dict_, objkey):
"""
从嵌套的字典中拿到需要的值
:param dict_: 要遍历的字典
:param objkey: 目标key
:return: 目标key对应的value
"""
if isinstance(... |
import json
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
# fele:afax/views.py
# createxhr_01.html
def create_views(request):
return render(request, "createxhr_01.html", locals())
def server02_views(request):
retu... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 01:24:00 2020
@author: Martinez Garcia Isabel
2) Realice la representacián de la red semantica por medio de un programa
que permita implementar los siguientes verbos: Tiene, Vive y es.
"""
AnimalesEs = [("Tortuga","Oviparos"),
("Gallo","Oviparos"),
... |
# Generated from Cal.g4 by ANTLR 4.8
from antlr4 import *
if __name__ is not None and "." in __name__:
from .CalParser import CalParser
else:
from CalParser import CalParser
# This class defines a complete generic visitor for a parse tree produced by CalParser.
class CalVisitor(ParseTreeVisitor):
# Visit... |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Wen Guan, <wen.guan... |
import math
def td(T,RH):
r=(17.27*T/(237.7+T)+math.log(RH/100))
Td=237.7*r/(17.27-r)
return Td
'''
Td=td(10.9,64)
print(Td)
'''
def Mechanical_mixing_height(T,Td,P,Uz,Z,Z0):
mechanical_mixing_height=(121/6)*(6-P)*(T-Td)+0.169*P*(Uz+0.257)/12*0.0000579*math.log(Z/Z0)
return mechanical_m... |
dir = {}
while True:
name = input("Enter name [end to stop] :")
if name == "end":
break
phone = input("Enter phone number :")
if name not in dir:
dir[name] = {phone} # create new set with phone number
else:
dir[name].add(phone) # add phone number to existing set
for na... |
import pygame
import resources as rs
health = 175
tanksDict = ""
class Tank(object):
def __init__(self, tankData, colorIndex):
""" Initialize function for the tanks
:param tankData: Interpreted Json data
"""
self.x = tankData["x"]
self.y = tankData["y"]
self.width =... |
#!/usr/bin/python3
#
# Copyright (c) 2018-2019 Collabora, Ltd.
#
# SPDX-License-Identifier: Apache-2.0
#
# Author(s): Ryan Pavlik <ryan.pavlik@collabora.com>
#
# Purpose: This file contains tests for check_spec_links.py
import pytest
from check_spec_links import MessageId, makeMacroChecker
from spec_tools.con... |
# -*- coding: utf-8 -*-
{
'name' : "Utility Modules",
'version' : "1.0",
'author' : "tranchiendang@gmail.com",
'description' : '''
Change qweb downloaded file name, get report_file as name of downloaded file
''',
'category' : "Utility",
'depends' : ['report'],
'website': 'https:/... |
#!/usr/bin/python
import h5py
from .visual_util import *
from .ref_util import _get_readid_from_fast5, \
_get_alignment_attrs_of_each_strand
from statsmodels import robust
import numpy as np
import collections
""" get the raw signal and event from fast5 """
# this module is based on DeepSignal
def get_signal_... |
def is_triangle(lis):
lis.sort()
if lis[0] + lis[1] > lis[2]:
return True
return False
lis = [0]*3
print ("Please input 3 integers")
for i in range(3):
lis[i] = int(raw_input())
if is_triangle(lis):
print ("Yes")
else:
print ("No")
|
import sys, tweepy
def twitter_auth():
try:
consumer_key = 'gJGAh2Kja0V1gCOp4OoBuFe4i'
consumer_secret = 'aqGv25ZrGxYyMfLbdrShdLL3aiGl90af0cc1xo86sJKDPKtwXf'
access_token = 'AAAAAAAAAAAAAAAAAAAAAFtqHAEAAAAAuo8A8kKea67cj%2FNU57hqSD31dyg%3DevsEy0FYjsVm2AaysJfStyeu081ZdA2uXDG09NZEKfNVQ3Y... |
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fps = 30
fpsClock = pygame.time.Clock()
screenx = 800
screeny = 600
grassQuantity = 800
BerryQuantity = 14
SBerryQuantity = 2
surface = pygame.display.set_mode((screenx, screeny))
pygame.display.set_caption('Hungry Knight Clone')
colours =... |
#! /usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
import numpy as np
try:
#import cPickle as pickle
import _pickle as pickle
except:
import pickle
import time
import torch
import torchvision as tv
from torch import nn, optim
from torch.utils.data.sampler impor... |
#!/usr/bin/env python3
""" base page object """
import time
import traceback
import tools.interact as ti
# from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By as BY
from se... |
from imutils.video import VideoStream
from imutils.video import FPS
import face_recognition
import imutils
import pickle
import cv2
from twilio.rest import Client
from imgurpython import ImgurClient
tw_account_sid = 'AC187864d6bb8a603665d83632571f02cc'
tw_auth_token = '3d7951e1fc7ef42813c4e44ec9417654'
tw_client = Cli... |
# Author : Kang Ho Dong
# Date : 2020 - 07 - 18
# Title : BOJ 15651
# Language : Python 3
def func_backtracking(n,m,ls):
if len(ls) == m and len(ls) != 0:
for i in ls:
print(i,end=" ")
print()
return
for i in range(1,n+1):
ls.append(i)
func_backtrack... |
# from collections import OrderedDict
# # The built in data structure
# class LRUCache(OrderedDict):
# def __init__(self, capacity: int):
# self.capacity = capacity
# def get(self, key: int) -> int:
# if key not in self:
# return -1
# else:
# self.move_to_end... |
# Load Test client app
import sys
import socket
HOST = 'localhost'
PORT = 8001
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, err:
print "Error creating socket: %s" % str(err[0])
sock.connect((HOST, PORT))
sock.send('Foobar')
|
# coding=utf-8
import hashlib
import urllib
from random import Random
class HelperMixin(object):
def random_str(self, randomlength=32):
str = ""
chars = "abcdefghijklmnopqrstuvwxyz0123456789"
length = len(chars) - 1
random = Random()
for i in range(randomlength):
... |
"""
An implementation of ICA using mixtures of Gaussian marginals.
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <lucas@theis.io>'
__docformat__ = 'epytext'
from numpy import *
from numpy.linalg import inv, det, slogdet
from numpy.random import *
from s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-17 12:44
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('backend', '0064_auto_20171116_0839'),
... |
#hello world!
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
import datetime as dt
from flask import Flask, jsonify
#################################################
# Database Setup
################... |
import json
from io import BytesIO
from avro.io import DatumWriter, BinaryEncoder, DatumReader, BinaryDecoder
from avro.schema import SchemaFromJSONData, Names
from gevent import socket, monkey
from gevent.queue import Queue
from loguru import logger
monkey.patch_all()
queue = Queue(100)
class Meta:
def __init... |
__author__ = 'quynhdo'
from liir.nlp.ml.nn.base.Layer import Layer
from liir.nlp.ml.nn.base.NNNet import NNNet
from liir.nlp.ml.nn.base.Functions import CrossEntroyCostFunction
from liir.nlp.ml.classifiers.linear.logistic import load_data
try:
import PIL.Image as Image
except ImportError:
import Image
from l... |
from flask import Flask, render_template, url_for, request
import pandas as pd
import numpy as np
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.externals import joblib
from sklearn.metrics import (confusion_matrix, accuracy_score)
f... |
import cv2
from abc import ABC, abstractmethod
import numpy as np
class BaseModel(ABC):
INVALID_POSITION = (-1, -1)
@abstractmethod
def __init__(self, position):
self.position = position
@abstractmethod
def render_model(self, drawer):
pass
def render(self, drawer):
"... |
#!coding:utf8
'''
Date:2018/11/9/11:21
Author:yqq
Description: 百度翻译
'''
# 请在 File >> Setting >> Project:TranslateTool >> Interpreter >> 设置为 Python2.7.*
import sys
import time
from lib.BDtraslate import Translate
#reload(sys)
sys.setdefaultencoding('utf-8')
if __name__ == '__main__':
with open('../txt/text.txt'... |
import csv, pprint
from pymongo import MongoClient
#server = MongoClient('127.0.0.1')
server = MongoClient('149.89.150.100')
db = server.celharry
db.students.drop()
students = db.students
#============================================= STUDENTS
peeps = open("peeps.csv")
peepdict = csv.DictReader(peeps)
for stude... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 2017
@author: john abel
Module set up to perform analysis for Yongli Shan.
"""
from concurrent import futures
import itertools
import numpy as np
from scipy import signal, stats, optimize
from scipy.sparse import dia_matrix, eye as speye
from scipy.sparse.linalg impo... |
from rest_framework import permissions
from rest_framework import serializers
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from micameo.balance.models import BalanceTalent, Withdraw
from micameo.balance.selectors import get_balance_talent, get_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is a demo script for showcasing this package's functionality in brief.
@author: Pranay S. Yadav
"""
# Import call
import ETC
# ------------------------
# IO & SEQUENCE MANAGEMENT
# ------------------------
# Read data to a list
text = ETC.read(filepath="somefil... |
import os
import glob
import numpy as np
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, \
roc_auc_score, f1_score
# モデルの予測結果と教師値を用いて、予測結果を評価するスクリプト
# AUCやaccuracyなどを計算する
# TPが1件もないと、F1 scoreを算出す... |
# Generated by Django 3.0.5 on 2020-11-02 14:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('data', '0051_auto_20201102_1444'),
('schedule', '0003_auto_20201102_1459'),
]
operations = [
migrat... |
def load_front_torso_mesh():
from lace.mesh import Mesh
mesh = Mesh(filename="/Users/pnm/code/tape/examples/anonymized_female.obj")
mesh.cut_across_axis(1, minval=100.0, maxval=120.0)
mesh.cut_across_axis(0, minval=-19.0, maxval=19.0)
mesh.cut_across_axis(2, minval=0)
return mesh
def main():
... |
def main():
n = int(input())
countries = [input() for _ in range(n)]
print(len(set(countries)))
if __name__ == "__main__":
main()
|
import requests
from rest_framework import status
from rest_framework.generics import CreateAPIView, DestroyAPIView, ListCreateAPIView, ListAPIView
from rest_framework.response import Response
from cars.models import CarModel, CarMake, CarRate
from cars.serializers import CarSerializer, RateCarSerializer, PopularCarSe... |
def convert_to_binary(a):
ret=[]
while a>0:
rem=int(a%2)
ret.append(str(rem))
a=int(a/2)
s= ''.join(ret)
s=s[::-1]
return int(s)
def diff(A):
for i in range(len(A)):
A[i]=convert_to_binary(A[i])
temp=[]
for i in range(len(A)):
for j in range(i+1,le... |
#!/usr/bin/env python3
"""Helper script to generate release notes."""
import argparse
import logging
import os
import re
import subprocess
from datetime import datetime
from typing import List, Optional, Tuple
from github import Github, GithubException, Repository, Tag
from packaging.version import Version
# http://d... |
import asyncio
import websockets
import socket
import tajniacy_definitions as td
import tajniacy_game as game
import tajniacy_network as tn
async def main():
td.init()
td.FILE_CHOICE.extend(game.file_list())
game.reset_matrix()
game.reset_secret()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connec... |
# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, BooleanField, SelectField, SubmitField
from wtforms.validators import Required, Length, Email, Regexp
from wtforms import ValidationError
from flask.ext.pagedown.fields import PageDownField
from ..models import Role,... |
import socketserver
import configparser
import logging
from gi.repository import Gst
from lib.Util import Util
from lib.GSTInstance import GSTInstance
import io
class NetCamClientHandler(socketserver.BaseRequestHandler):
cam_config = 0
cam_id = 0
coreStreamer = 0
def __init__(self, requ... |
# Import package
import urllib3, requests, json
# Set up request credential infor
api_key = "02834833a9dfe29dc2c55eb707c5a73c"
example_api_request = "https://api.themoviedb.org/3/movie/550?api_key="+api_key
bearer_token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwMjgzNDgzM2E5ZGZlMjlkYzJjNTVlYjcwN2M1YTczYyIsInN1YiI6IjVmNTE4YjE... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
"""Core modules used exclusively by :py:mod:`nbuild` or the compilation library (:py:mod:`stdlib`).
The content of the core module should not be used by a build manifest.
"""
|
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.haAdmin.ha_ipmi.views \
import IndexView
from openstack_dashboard.dashboards.haAdmin.ha_ipmi.views \
import DetailView
#from openstack_dashboard.dashboards.haAdmin.ha_ipmi.views \
# import UpdateView
#... |
# MONKEY PATCH!!!
import json
import os
import sys
import mockredis
import redis
from swsssdk import SonicV2Connector
from swsssdk import SonicDBConfig
from swsssdk.interface import DBInterface
from swsscommon import swsscommon
from sonic_py_common import multi_asic
if sys.version_info >= (3, 0):
long = int
... |
#
# @lc app=leetcode.cn id=814 lang=python3
#
# [814] 二叉树剪枝
#
# https://leetcode-cn.com/problems/binary-tree-pruning/description/
#
# algorithms
# Medium (70.80%)
# Likes: 135
# Dislikes: 0
# Total Accepted: 16K
# Total Submissions: 22.5K
# Testcase Example: '[1,null,0,0,1]'
#
# 给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么... |
# http://www.pythonchallenge.com/pc/def/linkedlist.html
# http://www.pythonchallenge.com/pc/def/linkedlist.php
import urllib2
url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php'
def get(s):
url2 = url + '?nothing=' + s
req = urllib2.Request(url2)
response = urllib2.urlopen(req)
page = respon... |
# LINKEDIN
"""
SOLVED -- LEETCODE#508
Given a binary tree, find the most frequent subtree sum.
Example:
3
/ \
1 -3
The above tree has 3 subtrees. The root node with 3, and the 2 leaf nodes,
which gives us a total of 3 subtree sums. The root node has a sum of 1 (3 + 1 + -3),
th... |
#one of your homework assignments is to write a method that
#finds twos. It takes two lists and returns any elements that appears in
#both lists containing the digit 2.
#How would we make sure that such a program is working?
def find_twos(first_list, second_list):
return []
assert(find_twos([], []) == [])
assert... |
"""
Problema propuesto
Desarrollar una clase que represente un Cuadrado y tenga los siguientes métodos: inicializar el valor
del lado llegando como parámetro al método __init__ (definir un atributo llamado lado), imprimir su
perímetro y su superficie.
"""
class Cuadrado:
def __init__(self):
self.cuadrado... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Bookmark
from django.views.generic import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
import sys
import os
sys.path.append... |
from flask import Flask,jsonify,abort,make_response,render_template
from flask_httpauth import HTTPBasicAuth
from mysql import Mysql
import time
import utlis
import re
from judje import JudjeTime
app = Flask(__name__)
@app.route('/favicon.ico')
def get_fav():
return app.send_static_file('favicon.ico')... |
import tkinter as tk
import random as ran
import time
import webbrowser
win = tk.Tk()
win.title("Камень-Ножницы-Бумага")
win.geometry("500x700+300+100")
win.resizable(False, False)
# переменные
paper = tk.PhotoImage(file="image/inst/paper.png")
kulak = tk.PhotoImage(file="image/inst/kulak.png")
noj = tk.... |
#!/usr/bin/env python
'''
PREREQUISITES:
chmod +x checkoutSvnNote.py
INSTALLING PYTHON PACKAGES:
sudo easy_install <package_name>
DESCRIPTION:
Checkout a CMS Note from SVN.
USAGE:
checkoutSvnNote.py [options]
EXAMPLES:
./checkoutFromSvn.py -n HIG-18-014 --noteType papers
./checkoutFromSvn.py -n HIG-18-015 --no... |
import os
import sys
import numpy as np
import tensorflow as tf
import scipy.misc
from matplotlib import pyplot as plt
def gen_data(gan_model_factory, model_path, batch_size, zs):
if zs is None:
assert batch_size > 0
elif batch_size is None:
batch_size = zs.shape[0]
else:
assert z... |
from unittest import TestCase
from shared.intcode import Intcode, read_data
class TestSilver(TestCase):
def test_example_0(self):
self.assertEqual(
Intcode([1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]).run_program(),
3500
)
def test_assignment(self):
data = read... |
import pygame,random,math,sys
from pygame.locals import *
from datetime import datetime, date, time
from LA_bbb import *
from pygame import Rect
class Arrow(pygame.sprite.Sprite):
def __init__(self, speed):
imgR = []
for i in range(4):
aa = pygame.image.load('lessonA/jiantou/' + str(i+... |
import tensorflow as tf
from tensorflow.python.framework import function
cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost:2223"]})
@function.Defun(tf.int32, tf.int32)
def MyFunc(x, y):
with tf.device("/job:local/replica:0/task:1/device:CPU:0"):
add1 = x + y
return [add1, x - y]
# Buildi... |
import numpy as np
# from itertools import permutations
# outF = open("D-small-attempt0.out","w")
outF = open("D-small.out","w")
verbose = 0
with open("D-small-attempt0.in","r") as inF:
# with open("D.in","r") as inF:
t= int(inF.readline())
for it in xrange(t):
k, c, s = map(int, inF.readline... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.