text stringlengths 8 6.05M |
|---|
from unityagents import UnityEnvironment
import numpy as np
from maddpg import MADDPG
from buffer import ReplayBuffer
import torch
from collections import deque
from utilities import transpose_list, transpose_to_tensor, convert_to_tensor
import matplotlib.pyplot as plt
def main():
env = UnityEnvironment(file_name... |
#!/usr/bin/env python
import numpy as np
def read_tiles( fn='input.03' ):
maxx, maxy = 0, 0
tiles = {}
with open( fn, 'r' ) as fp:
for line in fp:
d = line.strip().split()
claim = int( d[0][1:] )
x, y = d[2].split(','); x = int(x); y = int(y[:-1])
w, d = d[3].split('x'); w = int(... |
# coding: utf-8
import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2)
import os
import json
from io import BytesIO as Bytes2Data
import numpy as np
import sys
from caffe2.python import workspace
from core.config import assert_and_infer_cfg
from core.config import cfg
from core.config import merge... |
import redis
r = redis.Redis(host='localhost',port=6379)
r.set('ffffff','hhhhha')
print(r.get('ffffff'))
|
import logging, pickle, os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import sklearn.cluster as sk
import sklearn_extra.cluster as sk_extra
import tslearn.clustering as ts
from sklearn.exceptions import NotFittedError
from sklearn.metrics import calinski_harabasz_... |
import csv
import lda
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF
corpus = []
titles = []
inputfile = "C:\\tests\\myinput.csv"
outputfile = "C:\\tests\\myoutput.txt"
with open(inputfile, "r") as msdninput_file:
reader = csv... |
import urllib.request
from PIL import Image
from scipy.spatial import KDTree
from webcolors import (
CSS3_HEX_TO_NAMES,
CSS3_NAMES_TO_HEX,
hex_to_rgb,
)
import os
try:
from slack_bolt import App
except:
os.system('pip3 install slack_bolt')
from slack_bolt import App
def css(rgb_tuple):
css3_db = CSS3_HEX_TO_NAM... |
from tensorflow.keras import optimizers
def build_optimizer(opt="adam", learning_rate=0.001):
"""
Select optimizer with a learning rate to use in compiling the model
@type opt: string
@param opt: Which optimizer function to take
@default opt: adam
@type learning_rate: float
@param learning... |
import numpy as np
from electromorpho.core.gaussian import sample_from_gn
from electromorpho.metrics.score import BGe
from numpy.random import RandomState
from electromorpho.structure.graph_generation import random_dag
from electromorpho.mcmc.graphs.state_space import RestrictionViolation
from electromorpho.mcmc.graph... |
__author__ = 'centling'
import urllib
from bs4 import BeautifulSoup
dir_download = 'E:\project\dowloadMP3\MP3\\'
percentage = 0
def reporthook(block_read,block_size,total_size):
global percentage
percentage_new = block_read*block_size*100/total_size
if percentage!=percentage_new:
percentage = per... |
#coding:utf-8
INSTALLED_APPS
django.contrib.auth, \
django.contrib.contenttypes, \
django.contrib.messages
django.contrib.admin
MIDDLEWARE
django.contrib.auth.middleware.AuthenticationMiddleware
django.contrib.messages.middleware.MessageMiddleware
TEMPLATES (context_processors)
django.contrib.... |
print( ord( input())- ord( "A") + 1)
|
from sonosco.inference.asr import SonoscoASR
class DummyASR(SonoscoASR):
def __init__(self) -> None:
"""
Dummy implementation of ASR with fixed return values
"""
super().__init__("")
def infer(self, sound_bytes: any) -> str:
"""
Args:
sound_bytes:... |
from pathlib import Path
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import nltk
import re
import math
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk import word_tokeni... |
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
answer = float('inf')
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
tmp = nums[i] + nums[lef... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
for m in range(1,10):
for n in range(1,10):
if m>n:
print (end=' ')
else:
print ("{}*{}={:<2}".format(m,n,m*n),end=' ')
print()
|
#연속한 숫자의 곱을 구하는 알고리즘
#입력 : n
#출력 : 1부터 n까지 연속한 숫자를 곱한 값
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return f
print(fact(1))
print(fact(3))
print(fact(5))
def fact1(n):
if n<=1:
return 1
else:
return n*fact1(n-1)
print(fact1(1))
print(fact1(3))
print(fact1(10))
#O(n)
#재... |
import os
import sklearn.model_selection as splitter
from tools.image import get_image_as_array
# Remove files from os.walk that clutters the generation of data
def remove_unwanted_files(fileList):
try_remove_element_from_list(fileList, 'LICENSE')
try_remove_element_from_list(fileList, '.DS_Store') # In case ... |
file = open("day7input", "r")
store = file.readlines()
print(store) |
#! /usr/bin/env python3
"""Prepare subdirectory tree and launch rosetta backrub for given pdb and carriage-return delimited residue numbers
file"""
import argparse
import os
import subprocess
import sys
import time
try:
from suplementary_scripts.define_pdb_shell_prody import extract_res_list, get_structure, get_... |
import pygame
from src.tools import *
class frame:
def __init__(self, image, delaytick = 1, colorKey = None):
if type(image) == str:
self.image = load_imageOnly(image, colorKey)
elif type(image) == pygame.Surface:
self.image = image
self.delaytick = delaytick
def... |
from db.config import _Db
from db.sentences.sentence import Sentences
from db.subFlow.flow import Flow
# for x in _Db['sentences'].find():
# print(x)
# for x in Sentences.objects.all():
# x.type = 'video'
# x.save()
# for x in Flow.objects.all():
# x.type = 'video'
# x.save()
new_flow = Flow()
... |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2015-2016 Nick Hall
# Copyright (C) 2020-2021 Kari Kujansuu
#
# 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... |
if __name__ == '__main__':
import pandas as pd
import numpy as np
import _user_input as user_input
from _plot_func import *
from _models import *
from _support_func import *
from _helper_func import *
from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler
impor... |
nome=input('digite seu nome: ')
print(f'olá {nome} seja bem vindo')
|
N = int( input())
cake = '.'*N
ANS = ['']*N
for i in range(N):
if i%2 == 1:
ANS[i] = cake
else:
ans = ''
if i%4 == 0:
for j in range(N):
if j%3 == 1:
ans += 'X'
else:
ans += '.'
else:
... |
# 323. Number of Connected Components in an Undirected Graph
#
# Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes),
#
# write a function to find the number of connected components in an undirected graph.
#
# Example 1:
#
# 0 3
#
# | |
#... |
# function to do an accumulative sum
def cum_sum(x):
y = []
for xx in x:
z = 0
for yy in x[0:xx]:
z = z + yy
y.append(z)
return y
def unique(x):
y = []
t = 0
for xx in x:
exist = False
if xx in x[t+1:]: exist = True
if xx in x[:t]: exist = True
if not exist: y.append(xx)
t = t+1
return y
print... |
#coding:utf-8
"""
"""
class User(object):
def __init__(self, id_, name):
self.id_ = id_
self.name = name
def get_id(self):
return self.id_
def get_name(self):
return self.name
if __name__ == '__main__':
id_ = "1"
name = "user1"
task = User(id_, name)
p... |
def insertionSort(L):
for i in range(1, len(L)):
curr = L[i]
pos = i
while pos > 0 and L[pos - 1] > curr:
L[pos] = L[pos - 1]
pos -= 1
L[pos] = curr
randomlist = [66,24,97,1,71,20,43,58,99,32]
insertionSort(randomlist)
print(randomlist)
|
# Generated by Django 3.1.6 on 2021-03-23 00:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log', '0010_auto_20210322_2055'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='cost',
... |
# PROGRAM KONIEC GRY W WERSJI ULEPSZONEJ
# PRZYKŁADOWE UŻYCIE CUDZYSŁOOWÓW W ŁAŃCUCHACH ZNAKÓW
print("tylko",
"nieco",
"większy.")
print ("Oto, end=" ")
print ("on...")
print (
"""
| | / / / \
"""
)
input("\n\nAby zakończyć program nacisnij klawis... |
from flask import request
from gateway.app import app
from gateway.http_client import usermanager_http_client
from gateway.utils.handle_api import (
get_client_username, handle_request_response
)
@app.route('/user/delete', methods=['DELETE'])
@handle_request_response
@get_client_username
def user_delete(client_u... |
from PyQt4 import QtGui
class Actor(object):
#
# Init
#
def __init__(self, name, colour = 0x000000):
self.name = name
self.setColour(colour)
self.setSpeed(1)
self.cell = (0, 0)
self.x = 0
self.y = 0
self.canPass = False
# Can this actor go through other actors?
self.ignoreBlocking = False
# ... |
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.conf import settings
from accounts.models import Addresses
from books.models import Book
# Create your models here.
class Coupon(models.Model):
code = models.CharField(unique=True, max_length=50, verb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import datetime
import redis
import time
from flask.ext.socketio import emit
from app.config import INFO_INTERVAL, TABLE_MAX_ROWS
__author__ = 'liuyang@telking.com'
"""
* User: liuyang
* Email:sleshep@gmail.com
* Date: 16-1-28
* Time: 下午2:35
"""
... |
import logging
from abc import ABCMeta
from dataclasses import dataclass, Field, fields
from typing import List, Any, Tuple, Type, Optional
from rdflib import Graph
from rdflib.term import URIRef
from funowl.base.cast_function import cast
from funowl.base.rdftriple import SUBJ
from funowl.writers.FunctionalWriter imp... |
import pygame
import time
import random
TYPE_AVATAR = 1
TYPE_DROPPING_ENEMY = 2
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
BLACK = (0, 0, 0)
class Thing:
def __init__(self, t):
self.type = t
if self.type == TYPE_AVATAR:
self.blob_img = pygame.image.load('blob2.png')
elif self... |
import uuid
from typing import List
from biostudiesclient.api import Api
from biostudiesclient.auth import Auth
from submission.entity import Entity
from submission.submission import Submission
BIOSTUDIES_LINK_TYPES = {
'sample': 'biosample',
'study': 'ena',
'run_experiment': 'ena'
}
ENTITY_TYPE_SERVICE... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import gzip
import itertools
from random import Random
import os
import shutil
import tempfile
from typing import Iterable, Iterator, Any, Union
import unittest
import pickle
import gc
from infinibatch.iterators import (
create_source_iterat... |
import os
import uuid
from flask import Blueprint, jsonify, request, current_app, abort
from mongoengine import DoesNotExist, ValidationError
from pymongo.errors import DuplicateKeyError
from werkzeug.utils import secure_filename
from backend.auth import token_required
from backend.models import Project, User, Donati... |
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
import unittest
from address import Address
class TestAddress(unittest.TestCase):
def test_init(self):
index = u'123456'
country = u'Российская Федерация'
region = u'Московская область'
subregion = u'Подольский район'
... |
from django.urls import path
from .views import index, create_post, show_post, edit_post, delete_post
from .views import show_model
urlpatterns = [
path('', index, name='index'),
path('create_post', create_post, name='create_post'),
path('show_post', show_post, name='show_post'),
path('edit_post/<item_... |
import requests
from requests import get
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import datetime
from time import sleep
from random import randint
import os
from os.path import expanduser
home = expanduser("~")
downloads_path= f"{home}/Downloads"
headers = {"Accept-Language": "en-US, en;q... |
# Generated by Django 3.1.1 on 2020-11-27 08:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20201127_1355'),
]
operations = [
migrations.RenameField(
model_name='myevents',
old_name='event',
... |
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from __future__ import absolute_import
from django.db.models.signals import post_save, pre_save
try:
from picklefield import PickledObjectField
try:
import cPickle as pickle
except ImportError:
import pickle
... |
binary = bin(3)
print(binary[2:])
hexa = hex(30)
print(hexa[2:])
|
print("Gestor de edad")
edad = int(input("Ingrese su edad: "))
if edad >= 18:
print("Usted es mayor de edad")
elif edad < 18:
print("Usted es menor de edad") |
from django.core.urlresolvers import reverse
__author__ = 'self'
from django.db import models
from django.contrib.auth.models import User
from decimal import *
from django.utils.timezone import datetime
from intent.apps.core.utils import percentage
class Stream(models.Model):
ACTIVE_STATUS = 0
PAUSED_STATUS ... |
import day05_part1, day05_part2
def test_part1_example():
input = list(map(int, """0
3
0
1
-3""".splitlines()))
assert day05_part1.solve(input) == 5
def test_part1():
input = list(map(int, open("day05_input.txt").read().splitlines()))
assert day05_part1.solve(input) == 387096
def test_part2_exam... |
# -*- coding: utf-8 -*-
def hello(var = "Word")
return format('Hello, {}',var)
|
def calculate_bill_amount(food_type,quantity_ordered,distance_in_kms):
bill_amount=0
if(distance_in_kms<=3):
if(food_type=="V"):
bill_amount=(120*quantity_ordered)
elif(food_type=="N" ):
bill_amount=(150*quantity_ordered)
elif(distance_in_kms>3 and distance_in_kms<=6)... |
#! /usr/bin/env python3
from collections import defaultdict
from functools import partial
from get_filenames import get_filenames
from get_data import get_data
from process_xsec import process_xsec
from delta_var import get_delta
import numpy as np
files = get_filenames('/home/luke/Documents/Physics/Research/MCFM-too... |
"""Add deployment column and change unique constraint on users to deployment/
email.
Revision ID: 1a45abbc3682
Revises: 50de7e70cdd0
Create Date: 2015-09-10 14:22:39.853006
"""
# revision identifiers, used by Alembic.
revision = '1a45abbc3682'
down_revision = '50de7e70cdd0'
from alembic import op
import sqlalchemy ... |
import requests, json
from tkinter import *
from tkinter.ttk import Combobox
def open_auth_page(screen):
print("Scrren")
window = Frame(screen, width=800, height=600, bg="#ffffab")
window.place(x=50, y=50)
title = Label(window, font=("Gotham", "15"), text="Auth Form")
title.place(x=140, y=0)
l... |
print('******************')
__all__ = ['GLOBAL_NAME', 'hello', 'Person']
GLOBAL_NAME = 'Lechrond'
def hello():
print("hello lechrond")
class Person(object):
def __init__(self):
print('this is init method')
print('******************')
|
# Find the total cost of each customer's orders. Output customer's id,
# first name, and the total order cost. Order records by customer's
# first name alphabetically.
# Import your libraries
import pandas as pd
customers = customers[['id', 'first_name']]
orders = orders[['cust_id', 'order_cost']]
m = pd.merge(cus... |
def collatz(n):
if n==1: return [1]
if n%2 == 0: return [n] + collatz(n//2)
else: return [n]+ collatz(3*n+1)
collatzLength = dict()
n = 1000000
maxLength = -1
maxIndex = 0
collatzLength[1] = 1
for i in range(2,n):
num = i
tempLength = 0
while num !=1:
if num%2 == 0 :
... |
#!/usr/bin/env python
#
# Copyright 2017 - The Android Open Source Project
#
# 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 requir... |
import unittest
import Appliances
import ApplianceOwner
class TestAppliance(unittest.TestCase):
test_on_matrix_on = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
test_on_matrix_off = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def testIsOn(self):
testAppl = Appliances.Appliance("test",1... |
from tkinter import*
#https://www.youtube.com/watch?v=Cq5tpTwfJJY закончил на 10 41
root =Tk()
root.title('y = sin(x)')
root.geometry('1020x620')
canvas = Canvas(root, width=1020, height=620, bg='#002')
# линия ссетки по вертикали
for y in range(21):
k = 50 * y
canvas.create_line(10+k, 610, 10+k, 10, widht=1,... |
# PUBLIC DOMAIN NOTICE
# National Center for Biotechnology Information
#
# This software is a "United States Government Work" under the
# terms of the United States Copyright Act. It was written as part of
# the authors' official duties as United States Government employees and... |
print('Hello World')
print('Hello Github')
print('Mohaha')
print('edit01')
print('edit02')
|
class Encoder:
def __init__(self):
self.name = 'encoding'
def __call__(self, detections, img):
raise NotImplementedError('Extend the Encoder class to implement your own feature extractor.')
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import models
from django.forms import ModelForm, Textarea
class Question(models.Model):
news_Article_Heading = models.CharField(max_length=2000)
content = models.TextField()
created = models.DateField(... |
# Generated by Django 2.1.7 on 2019-11-29 17:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vitrine', '0006_bdd_chiffre_nom'),
]
operations = [
migrations.AlterModelOptions(
name='bdd_evenement',
options={'ordering':... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import Required, Email, Length, Regexp
class LoginForm(FlaskForm):
email = StringField('Email', validators= [Required(message= 'Error Fill'),Email(message= '... |
LABEL_SPATIAL = "label-spatial"
LABEL_OTHER = "label-other" |
'''
Created on Feb 22, 2017
@author: Alex Ip, Geoscience Australia
'''
import sys
import subprocess
import re
from geophys_utils import DataStats
def main():
assert len(sys.argv) == 4 or len(sys.argv) == 5, 'Usage: %s <root_dir> <file_template> <data_stats_csv_path> [<max_bytes>]' % sys.argv[0]
root_dir = sy... |
import numpy as np
def normalize(vector):
"""returns a unit vector in the same direction as vector"""
if np.linalg.norm(vector) == 0:
return vector
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
"""returns the angle between v1 and v2 in radians"""
v1_unit = normalize(v1)... |
#Date: April 2nd, 2020
#Written by: Oscar Law
#Description: Using machine learning to predict language, first every machine learning project
import pygame
import sys
import string
from Screens import Screen
from PredictLanguageML import counter, classifier
import random
#Initiating pygame
pygame.init()
... |
from restaurant import Restaurant
restaurant = Restaurant("Kjell's Ice cream", "Icecream")
restaurant.describe_restaurant()
|
# -*- coding: utf-8 -*-
"""
This script will serve as the main function set used for the operations of boom
tracking algorithm.
"""
import RPi.GPIO as gp
from time import sleep
import picamera
import cv2
import numpy as np
import argparse
import imutils
#import imutils
def take_photo_set():
#
# Set the first... |
import pytesseract
from PIL import Image
import cv2
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
image_sour = "D:/Users/84460/Desktop/Oracle_Split/Picture/01/0001.png"
text = pytesseract.image_to_string(image_sour, lang = "chi_sim_vert")
print(text) |
from point_pattern import PointPattern
import pysal as ps
shapefile = ps.open(ps.examples.get_path('new_haven_merged.shp'))
dbf = ps.open(ps.examples.get_path('new_haven_merged.dbf'))
for geometry, attributes in zip(shapefile, dbf):
break
|
from django import forms
from .models import Hood, Profile, Business, Post, Social_Amenities
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms.widgets import TextInput, PasswordInput
class SignUpForm(UserCreationForm):
"""
... |
import math
numero = int(input("Digite un número: \n"))
if numero > 0:
print("La raiz cuadrada de",numero,"es",math.sqrt(numero))
elif numero < 0:
print("El cuadrado de",numero,"es",(numero**2))
print("El cubo de",numero,"es",(numero**3)) |
import json
import pymongo
from xml.dom.minidom import parse
import xml.dom.minidom,re
import jieba
class DateEncoder(json.JSONEncoder ):
def default(self, obj):
if isinstance(obj,dict):
return obj.__str__()
return json.JSONEncoder.default(self, obj)
def sampleData():
datas... |
import pymongo
import json
from bson import ObjectId
# connection string
# mongo_url+"mongodb+srv://............"
mongo_url="mongodb://localhost:27017"
client= pymongo.MongoClient(mongo_url)
# get or craeate database
db=client.get_database("campingLife")
class JSONEncoder(json.JSONEncoder):
de... |
from django.shortcuts import render
from .forms import messageToGuideForm, messageToTravelerForm
from trips.models import tripGuide
from .models import messageToTraveler, messageToGuide
def sendGuideMessage(request, id):
user = request.user
trip = tripGuide.objects.get( tripID = id )
form = messageToGuideF... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 22 12:08:32 2021
@author: martin
"""
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
class Fractals:
def __init__(self,largeur=600,longueur=500):
self.largeur=largeur
self.longueur=longueur
self.maxi=80
... |
'''
author: juzicode
address: www.juzicode.com
公众号: juzicode/桔子code
date: 2020.6.21
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: juzicode/桔子code\n')
class Student():
def __init__(self,name,id):
print('实例化对象......')
self.name = name
self.id = id
def get_name(... |
#dropout
"""
应对过拟合的另一个方法是dropout
dropout方法有一些不同的变种,这里说的是倒置丢弃法
1.对网络的隐藏层应用丢弃法时,该层的隐藏单元将有一定概率被丢弃,设丢弃概率为p,那么有p的概率隐藏单元会被清零,1-p的概率隐藏单元会除以1-p做拉伸。
2.dropout概率p是dropout的超参数。具体来说,设随机变量(xi)为0和1的概率为p和1-p,使用dropout时,计算新的隐藏单元h'i,h'i=((xi)/(1-p))*h'i
3.随机dropout之后,输出层的计算无法过度依赖h1-h5中的任意一个,从而在训练模型时起到正则化的作用,并可以用来应对过拟合。
4.测试模型时,为了拿到更加确... |
from json_converter.json_mapper import JsonMapper
from typing import List
from conversion.conversion_utils import fixed_attribute
from submission.entity import Entity
BIO_STUDY_SPEC = {
'attributes': ['$array', [
{
'name': ['', fixed_attribute, 'Name'],
'value': ['stud... |
#!/usr/bin/python
#\file draw_squares2.py
#\brief Draw squares (no overlap).
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Dec.22, 2021
import numpy as np
import cv2
def GenSquarePattern2(img_w=200, img_h=200, w=20, h=20, N=10,
bg_col=(255,255,255), line_col=(2,48,15... |
# Generated by Django 3.2.5 on 2021-07-16 11:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PageCategory',
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import lockvote
_nodeServer = 'http://39.105.210.35:5000'
_genesisAddress = 'A3Es8Thkr7UWWfn4H1y4v9aJcP89GVpa4W'
_genesisTrId = '289c0738ee485ba6f289f015fd2ae7b632e8c1167c40e5a55d663c32ad05b67d'
_genesisSecret = 'fluid bracket forum either face bird toy april boss stam... |
from math import atan2
class PanelSheet():
z1 = 0
z2 = 0
en = 0
theta = 0
strength1 = 1
strength2 = 1
def __init__(self, loc1, loc2):
self.z1 = loc1
self.z2 = loc2
relZ = loc2-loc1
self.en = (-relZ.imag + relZ.real*1j)/abs(relZ)
self.theta = atan2(relZ.imag, relZ.real)
def velocity(self, z):
... |
""" A OneGov Page is an Adjacency List used to represent pages with any kind
of content in a hierarchy.
See also: `<https://docs.sqlalchemy.org/en/rel_0_9/orm/self_referential.html>`_
"""
from sqlalchemy import func
from sqlalchemy.ext.hybrid import hybrid_property
from onegov.core.orm.abstract import AdjacencyList
... |
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=10)
def __str__(self):
return self.name
# for testing the list and detail views of Django
class Informations(models.Model):
first_name = models.CharField(max_length=10)
last_name = models.CharField... |
class TermType:
def TermType(self):
self.coef = float(0) # 계수
self.degree = int(0) # 차수
class LinkedListNode(TermType):
def LinkedListNode(self):
self.Term = TermType()
self.Term.TermType()
self.pLink = {'HeaderClass': 0, 'CurrentClass': 0, 'NextClass': 0}
... |
from python12306.mainloop import Schedule
def main():
instance = Schedule()
instance.run()
if __name__ == "__main__":
main()
|
class Animal(object):
"""Makes cute animals."""
is_alive = True
health="good"
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def decription(self):
print(self.name)
print(self.age)
hippo=Animal('Baloo', 44)
... |
"""
The itty-bitty Python web framework.
"""
import cgi
import mimetypes
import os
import re
from io import BytesIO
import sys
import traceback
from typing import Dict, Union, Callable, List, Tuple, Optional
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server
__orig_author__ = 'Daniel Linds... |
import numpy as np
import matplotlip as plt
def initialBell(x):
return np. where(x%1.<0.5,np.power(np.sin(2*x*np.pi),2),0)
nx=40
c=0.2
x = np.linspace(0.0, 1.0, nx+1)
phi = initialBell(x)
phiNew= phi.copy()
phiOld= phi.copy()
for j in xrange(1,nx):
phi[j]=phiOld[j]-0.6*c*(phiOld[j+1] - phiOld[j-1])
phi... |
class MoneyFmt(object):
def __init__(self, value=0.0):
self.value = round(float(value), 2)
def update(self, value=None):
self.value = value
def __repr__(self):
return str(self.value)
def __str__(self):
val = '$' + str(self.value)
return val
def __nonzero__... |
#!/usr/bin/env python
"""
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-cloudwatch-metrics.html
"""
import datetime
import sys
from boto.ec2 import cloudwatch
AWS_REGION = ''
AWS_KEY = ''
AWS_SECRET = ''
ELB_NAME = 'tester'
PERIOD = 60
MINUTES = 1 # minutes of data to retrieve
### Real... |
from collections import Counter
def word_count(fname):
with open(fname)as f:
return Counter(f.read().split())
print("Number of words in the file: ", word_count("file.txt"))
|
# Generated by Django 2.1.3 on 2019-12-11 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('curso', '0005_auto_20191210_2023'),
('curso', '0006_auto_20191210_0521'),
]
operations = [
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.