text stringlengths 38 1.54M |
|---|
# Using print() functions to draw ascii art.
print(" /|")
print(" / |")
print(" / |")
print("/___|")
# The order in which you write your instructions matters alot. (Top down sequence)
|
def longest_slide_down(pyramid):
pyramid.reverse()
for i in range(1,len(pyramid)):
slideSum=[]
for j in range(len(pyramid[i])):
slideSum.append(max(pyramid[i][j]+pyramid[i-1][j],
pyramid[i][j]+pyramid[i-1][j+1]))
pyramid[i] = slideSum
return pyramid[-1][0... |
import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from flaskr import create_app
from models import setup_db, Question, Category
class TriviaTestCase(unittest.TestCase):
"""This class represents the trivia test case"""
def setUp(self):
"""Define test variables and initiali... |
import xml.etree.ElementTree as ET
"""
data ='''<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>'''
#las tres comillas simpless fue para meter toda esa informacion en varias lineas Jaja salu2
tree=ET.fromstring(data)#Crea un arbol de el docu... |
from django.contrib.gis.utils import LayerMapping
from models import Contours
contoursJsonFile = '/Users/kiran/Downloads/contours.json'
mapping = {
'trt':'TRTO0326_',
'trt_i':'TRTO0326_',
'height':'HEIGHT',
'htm': 'HTM',
'rpoly':'RPOLY_',
'lpoly':'LPOLY_',
'tnode':'TNODE_',
'fnode':'FNODE_',
'length':'LENGTH'... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
# 리스트를 만든다.
리스트 = ["가", "나", "다", "라"]
# 증감폭을 음수로 설정하여 끝에서 앞방향으로 값을 슬라이싱한다.
# 이때 한 줄씩 출력해야 하므로 for문을 사용하여 하나씩 여러번 출력되도록 한다.
for i in 리스트[: :-1]:
print(i)
# 실행결과 : 라
# 다
# 나
# 가
|
from serverzen_fabric import utils, ossupport, _internal
class ApacheService(_internal.LoggerMixin,
utils.RunnerMixin, ossupport._OSMixin):
def _apache(self, cmd):
self.log('Executing', 'apache.' + cmd)
self.runner.clone(sudo_user='root') \
.run(self.os.apacheinitd... |
#!/usr/bin/env python
'''
This node subscribe topic "chat_data" from picture_voice_recognize.py and
"/usb_cam/image_raw".When this node receive the string information "cheese",
this node then picture according the data of "/usb_cam/image_raw" and save in
the given path.
'''
from __future__ import print_function
impo... |
#-*- coding: utf-8 -*-
"""
Created on Wed Aug 1 08:50:40 2018
class MyGan
@author: Dujin
"""
runfile('C:/users/dujin/desktop/tensorflow/infogan/basefunc.py')
class MyGan(object):
def __init__(self,sess,data_path,ydim = 12 ,zdim = 10,batch_size = 64, input_height = 28 , input_width =28,channel = 1,epoch = 10000):
... |
#######################################################
#
# Cruiser.py
# Python implementation of the Class Cruiser
# Generated by Enterprise Architect
# Created on: 30-6��-2021 15:38:36
# Original author: 70748
#
#######################################################
import abc
class Cruiser(abc.ABC):
@abc... |
"""longest common subsequence"""
class LCS:
def __init__(self):
self.lcs = ""
def longest_common_subsequence(self, x: str, y: str, m: int, n: int):
if m == 0 or n == 0:
return 0
elif x[m - 1] == y[n - 1]:
return 1 + self.longest_common_subsequence(x, y, m - 1, ... |
import pygame
pygame.init()
RUNNING = pygame.mixer.music.load('data/Gameplay/sound/running.mp3')
JUMP = pygame.mixer.music.load('data/Gameplay/sound/jump.mp3')
HURT = pygame.mixer.music.load('data/Gameplay/sound/hurt.mp3')
ENEMY_DEATH = pygame.mixer.music.load('data/Gameplay/sound/enemy-death.mp3')
CHEST = pyga... |
import os
django_secret = os.getenv('DJANGO_SECRET_KEY', 'l0cAl-t3st*')
django_is_debug_activated = os.getenv('DJANGO_DEBUG', 'False').lower() == 'true'
django_relative_path_for_static_file = os.getenv('DJANGO_STATIC_PATH', './public/static')
auth0_client_id = os.getenv('AUTH0_CLIENT_ID')
auth0_client_secret = os.get... |
#===============================================================================
# 26888: Verify that the favourite contacts will be listed on the top of the full
# contact list
#
# Procedure:
# 1- Open Address book app
# 2- Navigate to the top of contacts lists.
#
# Expected results:
# The favourite contacts are liste... |
# -*- coding: utf-8 -*-
'''
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
'''
from __future__ import unicode_literals
from ..model.email_address ... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from server.services import driver as driver_service
class Command(BaseCommand):
help = 'Sends notifications to drivers'
def handle(self, *args, **options):
# driver_service.process_... |
#!/usr/bin/env python
"""
Jay Sweeney, Ben Ihle, 2011.
Simple DNS server
for regex-based conditional domain
resolution and forwarding.
Place config (see below) into
./bdns_settings.py
What this does
~~~~~~~~~~~~~~
static mapping for www.google.com
static mapping for .*google.com (e.g. mail.google.com, www.aaaddsssgoog... |
"""
@Time : 2020/12/1418:37
@Auth : 周俊贤
@File :get_tsa_thresh.py
@DESCRIPTION:
"""
import torch
def get_tsa_thresh(schedule, global_step, num_train_steps, start, end):
training_progress = torch.tensor(float(global_step) / float(num_train_steps))
if schedule == 'linear_schedule':
threshold = training_... |
from collections import defaultdict
def distance(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
def find_closest(coords, x, y):
closest = 1000000
closestcells = []
for i, coord in enumerate(coords):
d = distance(x, y, coord[0], coord[1])
if d < closest:
closest = d
... |
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
#np.seterr(divide='ignore', invalid='ignore')
import sympy as sym
from scipy import integrate
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
from scipy.optimize ... |
import abc
import collections
import collections.abc
import dataclasses
from functools import wraps, partial, reduce
import hashlib
import operator
from typing import Any, Callable, Dict, Iterable
import warnings
class Stack:
"""Lightweight wrapper over builtin lists to provide a stack interface"""
def __init... |
class ImageFrame:
def __init__(self, pixels):
self.img = PhotoImage(width = WIDTH, height = HEIGHT)
for row in range(HEIGHT):
for col in range(WIDTH):
num = pixels[row*WIDTH+col]
if COLORFLAG:
kolor = '#%02x%02x%02x' % (num[0], num[1], ... |
from Todo_app.models import Task
from django.contrib import admin
# Register your models here.
class TaskAdmin(admin.ModelAdmin):
list_display = ['user','title','complete','description','created']
admin.site.register(Task,TaskAdmin) |
import re
import sys
input_filename = sys.argv[1]
try:
output_filename = sys.argv[2]
except Exception:
output_filename = 'output.txt'
regs = [
( r'[\[\]]' , '' ),
( r'\bnvarchar[ ]*\((.)*\) ' , 'string ' ),
( r'\bdecimal[ ]*\((.)*\)' , 'decimal' ),
( r'\buniqueidentif... |
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
class SentryAppInteractionTest(APITestCase):
def setUp(self):
self.superuser = self.create_user(email="superuser@example.com", is_superuser=True)
self.user = self.create_user(email="user@example.com")
se... |
def calc_min_calls(input_stream) -> int:
last_occurence = {0 : -1, 1 : -1}
n_calls = {0 : 0, 1 : 0}
for idx, direction in enumerate(input_stream):
if last_occurence[direction] == -1:
n_calls[direction] += 1
last_occurence[direction] = idx
elif (idx - last_occurence... |
import uuid, datetime, json
import pandas as pd
from functree import app, models, tree, analysis
def from_table(form):
raw_table = pd.read_csv(form.input_file.data, delimiter='\t', comment='#', header=0, index_col=0).dropna(how='all')
root = models.Tree.objects().get(source=form.target.data)['tree']
nodes... |
import os, datetime, uuid
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from hashids import Hashids
# Create your models here.
def get_default_hash_id():
hashids = Hashids(salt=setti... |
# 11有一个列表['a','b','c','a','e','a'], 使用for循环统计a出现的次数,并删除其中的所有a元素
# lis = ['a','b','c','a','e','a',"a","a"]
# count = 0
# for i in lis: #循环列表
# if i == 'a':
# count = count + 1 #当i是a的时候,每循环一次加一次
# print(count) #循环结束后,打印最后次数
# for j in range(count): #按计数引循环a
# lis.remove("a") ... |
# -*- coding: utf-8 -*-
from django import template
from django.db.models import Count
from sdifrontend.apps.mainpage.models import SysDataset, Category, SidebarMenu
register = template.Library()
@register.simple_tag(takes_context=True)
def get_sidebar_items(context, **kwargs):
# get the categories
nav_elem... |
str="abcdefg"
list1 = list(range(1,7))
list2 = list(range(7,13))
dic = {1:'hi',2:'hello'}
set1 = {1,2,3,3,3,4,4,5,5,5,1}
tuple1 = (1,2,3,4,5,4,4,5,5)
# for i in list1:
# print(i)
# for s in set1:
# print(s)
for t in tuple1:
print(t)
for i in list1:
for j in list2:
print(i,j)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 09:19:41 2020
@author: Christopher S. Francis
"""
import sys
import wx
import interfaceStuff
from datetime import datetime
class StdOutDialog(wx.Dialog):
def __init__(self, parent, result=""):
super().__init__(parent)
self.SetTi... |
''' Full suite of error analysis on CoNLL05 '''
from collections import Counter
import itertools
from itertools import izip
import subprocess
import sys
import re
from wsj_syntax_helper import extract_gold_syntax_spans
from full_analysis import read_file, read_conll_prediction, extract_spans,\
... |
import json
# writing into file & reading from files
f=open("My_File.txt","w")
text= "Some random text"
f.write(text)
f.close()
f=open("My_File.txt","r")
text_2=f.read()
print(text_2)
f.close()
# Writing lists into files
some_list = ["1","2","3"]
filename = "numbers.csv"
# CSV = Comma Separated Values
with open(f... |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import os
from tqdm import tqdm
from .utils import augment_val
from datasets.robotics import ProcessForce, ToTensor
from datasets.robotics import MultimodalManipulationDataset
from torch.utils.data import DataLoader
from torch.utils.da... |
import asyncio
async def test_install(guillotina_couchbase_requester): # noqa
async with guillotina_couchbase_requester as requester:
response, _ = await requester('GET', '/db/guillotina/@addons')
assert 'guillotina_couchbase' in response['installed']
|
from drawing_tools.canva import Canvas
class ICanvas:
def __init__(self, command, instances):
self.instance = Canvas(int(command[1]), int(command[2]))
|
import unittest
from mock import Mock
from ml.agent.base import Agent
from ml.runner.env.base import Runner
class RunnerTests(unittest.TestCase):
def setUp(self):
self.runner = Runner(
env_name='',
agent=Mock(spec=Agent),
max_steps=10
)
|
"""
*Variance Inference*
"""
from abc import ABCMeta
from .._operator import MomentInference
__all__ = ["VarianceInference"]
class VarianceInference(
MomentInference,
):
__metaclass__ = ABCMeta
|
import random as r
def mix_strength(i1,i2,d):
j1 = d.get(i1)
j2 = d.get(i2)
temp1 = (j2[0],j1[1],j1[2])
temp2 = (j1[0],j2[1],j2[2])
d[i1] = temp1
d[i2] = temp2
def mix_decal(i1,i2,d):
j1 = d.get(i1)
j2 = d.get(i2)
temp1 = (j1[0],j2[1],j1[2])
temp2 = (j2[0],j1[1],j2[2])
d[i1] = temp1
d[i2] = te... |
from django.contrib import admin
from django.urls import include, path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path("admin/", admin.site.urls),
path("photos/", include("photos.urls")),
path("user/", include("users.urls")),
path("pos... |
import os
import sys
from termcolor import colored
def computeTrueCase(filename, output_file='output_files'):
log = ''
try:
print ('Converting to PDF...')
if not os.path.exists(output_file):
os.makedirs(output_file)
log = os.popen('pdflatex --output-directory={0} {1}'.for... |
# Copyright (C) 1998-2015 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# Th... |
import numpy as np
class LatticeBoltzmann:
def __init__(self, ny, nx):
self.q = 9 # number of velocities
self.d = 2 # dimension
# Define class constants for use in its functions
self.nx = nx
self.ny = ny
self.init_grid_var()
def init_grid_var(self):
... |
#PRINTING THE Q TABLE
import rospy
# from std_msgs.msg import Float64, String
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
import sys
import random
from math import cos, sin, atan, pow
import numpy as np
import csv
from pandas import ExcelWriter
PI = 3.14159265359
vel = 0
ang = 0
l... |
"""
Estimating Hessian for ReLU neural network activations using forward HVP + Lanzosc.
"""
import matplotlib.pyplot as plt
from insilico_Exp_torch import TorchScorer
from GAN_utils import upconvGAN
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm, tra... |
#!/usr/bin/python
from flask import Flask, request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def getSpecs():
return "Hello world"
if __name__ == "__main__":
app.run(debug=True,host="0.0.0.0")
|
import random
def coloda():
deck = []
for i in range(2, 11):
for e in ('C', 'P', 'B', 'X'):
deck.append(str(i)+e)
for i in ('J', 'Q', 'K', 'T'):
for e in ('C', 'P', 'B', 'X'):
deck.append(i+e)
return deck
def start(deck):
hand = []
for i in r... |
import numpy as np
from sklearn.datasets import make_circles, make_moons, make_blobs
import os
import matplotlib.pyplot as plt
import plotly.graph_objects as go
def generate_data_lin(N=1000):
x, y = make_blobs(N, centers=np.array(
[[-1, -1], [1, 1]]), n_features=2, cluster_std=0.2)
y[y == 0] = -1
... |
from pwn import *
import string
import sys
HOST = sys.argv[1]
io = remote(HOST, 6789)
io.sendline("mjtezmjtezmjtez")
print(io.recvuntil('That\'s it!',timeout=2).decode()) |
#!/usr/bin/env python
# coding: utf-8
# # Ejemplo
# In[14]:
#Se importan las librerias
import sys
import glob
import os
import datetime
import logging
import subprocess
#from importlib import reload
import re, csv
from io import StringIO
import shlex
import uuid
import pandas as pd
import shutil
# In[36]:
#Decl... |
from pathlib import Path
import logging
import argparse
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from siamese.data.datamodule import OmniglotDataModule
from siamese.modules.model import siamese_net
from pytorch_lightning.callbacks import QuantizationAwareTra... |
# coding: utf-8
import pbr.version
__version__ = pbr.version.VersionInfo('dopplerr').release_string()
VERSION = __version__
LOGGER_NAME = "cfgtree"
__all__ = [
'__version__',
'VERSION',
]
|
# Copyright 2016 Ericsson AB.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
# 유저(클라이언트)들이 웹페이지를 요청할때 데이터를 보내고 싶다
# Method 방식
# GET : 데이터를 헤더(header)에 싣고 전송
# POST : 데이터는 바디(body)에 싣고 전송
# 요청패킷 = 헤더 + 바디 로 구성된다
# GET방식은 보안에 취약하다
# POST방식은 보안에 좋다 ( GET <-> POST )
#
# 데이터 추출은 request 객체를 통해서!!
#
'''
GET의 예시 : 주소 + '?' + 데이터(키=값&키=값&...)
Ex)
https://news.naver.com/main/read.nhn?
oid=018&si... |
#!/usr/bin/env python
# encoding: utf-8
import re
import string
import random
import bcrypt
import hmac
from datetime import date, datetime
import time
import os
def get_model_table(str):
"""
获取模型类对应的表名,大驼峰字符串转换为小写加下划线格式, 如果最后一个为Model,则去掉
eg: UserInfo => user_info
:return: str
"""
_word_list ... |
from django.db import models
# Create your models here.
class UrlString(models.Model):
created_on = models.DateTimeField(auto_now_add=True)
url_path = models.URLField(max_length=300, default="")
def __str__(self):
return self.url_path
def get_absolute_url(self):
return 'h... |
from django.shortcuts import render, redirect, HttpResponse
from django.views import View
from system.models import System
from authen.models import Project, UserInfo
from audits.utils import yualert, SystemAudits
from authen.utils import FormAuthen
from system.utils import yuoem, yuversion, yusystemconfig
import js... |
# -*- coding: utf-8 -*-
import numpy as np
# numpy 배열의 생성 함수
# numpy 모듈의 함수를 사용하여 배열을 생성할 수 있음
# 1. np.zeros(배열의형태) : 입력된 형태의 배열을
# 생성하면서 모든 요소의 값을 0으로 초기화
# - 아래의 코드는 3행 2열의 다차원 배열이 생성되고
# 모든 요소의 값은 0으로 채워짐
numpy_array_0 = np.zeros((3,2))
print("numpy_array_0 : \n{0}".format(numpy_array_0))
# 2. np.ones(배열의형태) ... |
# Progress Bar part 2
import tkinter
from tkinter import *
from tkinter.ttk import *
# functions
# def clicked():
# probar["value"] = 50
def clicked():
probar2.start(10)
def stop():
probar2.stop()
root = Tk()
root.title("Progress Bar")
root.geometry("500x300")
probar1 = Progressbar(r... |
# Software Design Final Project
# Team Daydream
# V1.0 - ERIC + KIM (only OpenCV)
# Changelog
# - Added basic overlay functionality
import cv2
import numpy
import time
MAXFRAMES=60 # max number of frames (length of animation)
NUM_FRAMES=36 # number of animation frames
OVERLAYFRAMERATE = 24
fc_overlay = 0 # fram... |
from networkx.algorithms.community import LFR_benchmark_graph
import networkx as nx
n = 1000
tau1 = 2.2
tau2 = 2.3
mu = 0.35
generated_sample_count = 0
num_of_samples = 5
while generated_sample_count < num_of_samples:
try:
#G = LFR_benchmark_graph(n, tau1, tau2, mu, average_degree=5, min_community=20)
... |
import logging
import sys
from datetime import timedelta, datetime
from hashlib import sha1
from yaml import load, FullLoader
import lcg_generator.random as lcg
from constants import *
from query_writer.writer import sql_insert
# Init
_result_list = []
# Setup
logging.basicConfig(level=LOG_DEFAULT_LOGGING_LEVEL, fi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from seqmod.modules import attention as attn
from seqmod.modules.custom import StackedLSTM, StackedGRU, MaxOut
class Decoder(nn.Module):
"""
Attentional decoder for the EncoderDecoder architecture.
Pa... |
import datetime as dt
total = 0
d = dt.date(1901,1,1)
delta = dt.timedelta(days=1)
while d <= dt.date(2000,12,31):
if d.weekday() == 6 and d.day == 1:
total += 1
d += delta
print total |
import sys
from sqlalchemy import Column, Integer, String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
from setting import Base
from setting import ENGINE
class Mitemset(Base):
"""
ユーザモデル
"""
__tablename__ = 'mitemset'
setno = Column(Integer, primary_key=True)
tra... |
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 10000
#create a socket object
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind to address and ip
server.bind((bind_ip, bind_port))
#server listening to tcp connection
server.listen(5)
print("[*] Listening on %s: %d" % (bind_ip, bind_por... |
#-*- coding: utf-8 -*-
def logging_sources(request):
login_ip = request.META.get('REMOTE_ADDR', '')
user = request.user
return login_ip, user |
import numpy as np
import cv2
start = [0,0]
end = [0,0]
cl1 = True
def theloop(event,x,y,flags,param):
global cl1, start, end
if event == cv2.EVENT_LBUTTONDOWN:
if cl1:
start = [x,y]
cl1 = False
print 'st : ', start
else:
end = [x,y]
... |
x=float(input("Enter the Base:"))
n=int(input("Enter the Exponent:"))
s=0
for a in range(n+1):
s=s+x**a
print("Sum of Series=",s)
|
# Copyright 2016 NEC Corporation
#
# 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 agree... |
from PySide.QtCore import*
from PySide.QtGui import*
import sys
import updateBox
class upDialog(QDialog, updateBox.Ui_Dialog):
def __init__ (self, parent = None):
super(upDialog, self).__init__(parent)
self.setupUi(self)
|
# -*- coding: utf-8 -*-
import os
import sys
# class that will contain the data entries for organized funtioning
class detailInfo:
def __init__(self, date , maxtemp, mintemp, maxhumid, minhumid):
self.date= date
self.maxTemp= maxtemp
self.minTemp = mintemp
self.maxHumid= maxhumid
... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any(target in a for a in matrix)
if __name__ == '__main__':
matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[... |
import pathlib
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from model import MyModel
test_path = pathlib.Path('data/test')
CLASSES = np.array([dire.name for dire in test_path.iterdir()])
BATCH_SIZE = 64
IMAGE_HEIGHT = 112
IMAGE_WIDTH = 112
def get_label(file_path):
parts = tf.strin... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import os
import importlib
dataset = os.environ.get('DATASET', 'ibm')
load_dataset = (importlib
.import_module('explainer.data.' + dataset)
.load_dataset)
|
from selenium import webdriver
import time
chrome_browser = webdriver.Chrome(executable_path='C:/chromedriver')
chrome_browser.get('https://web.whatsapp.com/')
time.sleep(15)
user_name = 'Whatsapp bot'
user = chrome_browser.find_element_by_xpath('//span[@title="{}"]'.format(user_name))
user.click()
me... |
#!/usr/bin/env.python
# -*- coding:utf-8 -*-
a, b, c = map(int, input().split())
d = {10:'A',11:'B',12:'C'}
def cal(x):
l = ''
while x > 0:
x,j = divmod(x,13)
if j>9:
j = d[j]
l = l+str(j)
return l[::-1]
a = cal(a)
b = cal(b)
c = cal(c)
print('#{:0>2}{:0>2}{:0>2}'.for... |
"""
import modulo
modulo.fun()
modulo.fun2()
import modulo as mod
mod.fun()
mod.fun2()
"""
"""
from modulo import fun, fun2
fun()
fun2()
"""
from modulo import *
fun()
fun2() |
# Copyright 2022 Quantapix Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
#!/usr/bin/env python
import sys
import numpy
import catmaid
import vispy
import vispy.scene
import vispy.app
def renderNeurons(neurons, colors='random', w=2, aa=False):
print("Rendering...")
canvas = vispy.scene.SceneCanvas(
keys='interactive', show=True,
title='skeletons',
... |
from django.contrib import admin
from .models import Service
# Register your models here.
class ServiceAdmin(admin.ModelAdmin):
readonly_fields=('created_at','updated_at')
admin.site.register(Service,ServiceAdmin) |
#!/usr/local/python
# -*- coding:utf-8 -*-
import redis
r = redis.Redis(host='localhost', port=6379)
r.rpush('list', 'item1')
r.rpush('list', 'item2')
r.rpush('list2', 'item3')
# 将item3从list2弹出并推入list左端
print r.brpoplpush('list2', 'list', 1)
print r.brpoplpush('list2', 'list', 1)
print r.lrange('list', 0, -1)
# 将ite... |
import random, datetime
from django.shortcuts import (
render, reverse, HttpResponse, redirect
)
from django.contrib import auth
from django.http import JsonResponse
from django.views import View
from django.db.models import Q, Count
from django.forms import modelformset_factory
from PIL import (
Image, ImageD... |
# Переставьте цифры числа в обратном порядке .
n = input()
sz = n.__len__()
i = sz - 1
while i >= 0:
print(n[i], end='')
i -= 1
|
import random
from django.contrib.auth.models import User
from faker import Faker
#from backend.users.models import UserProfile, Organization
from ..users.models import UserProfile, Organization
def create_user(username,
password='12345',
cname='无名氏',
ename='Unknow... |
import httplib2
import json
import urllib
hObj = httplib2.Http('.cache')
wSrc = 'http://www.wikidata.org/w/api.php'
lang = 'en'
def _get(param):
param['format'] = 'json'
param = urllib.urlencode(param)
resp, cont = hObj.request(wSrc + '?' + param)
return json.loads(cont)
def search(type, search):
... |
from collections import namedtuple, Counter
Program = namedtuple('Program', ['weight', 'sons'])
Node = namedtuple('Node', ['name', 'sum', 'weight', 'sons', 'equal'])
Leaf = namedtuple('Leaf', ['name', 'sum', 'equal'])
class MemoryTree:
TOWER = {}
ARROW = ' -> '
def __init__(self, input='input.txt'):
... |
"""
Visualize trends of COVID-19 cases and deaths
"""
# %%
from os.path import join
import logging
from bokeh.io import curdoc
from bokeh.palettes import Purples
from bokeh.layouts import gridplot, row
from bokeh.plotting import figure
from bokeh.themes import Theme
from bokeh.models import (
ColumnDataSource,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import argparse
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
import pandas.rpy.common as com
from pandas import DataFrame
def Sizezonematrixfeatures(Img):
rdf = com.convert_to_r_dataframe(Img)
ro.globalenv['Image'] = rdf
... |
#!/usr/bin/python
MANHATTAN_ZIP_CODES = [
10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010, 10011,
10012, 10013, 10014, 10015, 10016, 10017, 10018, 10019, 10020, 10021, 10022,
10023, 10024, 10025, 10026, 10027, 10029, 10030, 10031, 10032, 10033, 10034,
10035, 10036, 10037, 10038, 10039, ... |
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.db.models import QuerySet
from web.domains.case.shared import ImpExpStatus
from web.domains.case.types import ImpOrExp
from web.flow import errors
from web.models import AccessRequest, ApprovalRequest, Process, Task
TT = Task.T... |
from text_gnn.config import TEMP_PATH
import joblib
import gensim
import numpy as np
from seaborn import distplot
from matplotlib import pyplot
from collections import Counter
from nltk.corpus import stopwords
from sklearn.datasets import fetch_20newsgroups
def get_data(cate):
if cate == 'all':
l1, t1 = ... |
import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
# Find the "SEEN" messages in INBOX
c.select('INBOX')
typ, [response] = c.search(None, 'SEEN')
if typ != 'OK':
raise RuntimeError(response)
msg_ids = ','.join(response.decode('utf-8').split(' '))
# Creat... |
from flask import redirect, render_template, url_for
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
from app.extensions.login import login_player
from app.models import db, Player
from app.views.salad_bowl import salad_bowl
class CreatePlayerForm(FlaskForm... |
# --------------------------------------------------------------------------- #
# __init__.py #
# #
# Copyright © 2015-2020, Rajiv Bakulesh Shah, original author. #
... |
import torch
import numpy as np
import random
from prospr.dataloader import dataloader
from prospr.nn import CUDA, CROP_SIZE, DIST_BINS, ANGLE_BINS, SS_BINS, ASA_BINS, INPUT_DIM
IDEAL_BATCH_SIZE = 2
def norm(thing):
mean = np.mean(thing)
stdev = np.std(thing)
return (thing - mean) / stdev
def get_start... |
import copy
class Solution:
def permute(self, nums):
returnList = []
def DFS(remain, stack):
if remain == []:
returnList.append(stack[:])
else:
for i in range(len(remain)):
r = copy.copy(remain)
s = r.p... |
import pyttsx3
# One time initialization
engine = pyttsx3.init()
# Set properties _before_ you add things to say
engine.setProperty('rate', 150) # Speed percent (can go over 100)
engine.setProperty('volume', 0.9) # Volume 0-1
# Queue up things to say.
# There will be a short break between each one
# w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.