text stringlengths 8 6.05M |
|---|
"""The CPU.
The CPU in the original GameBoy is a modified Zilog Z80.
http://www.devrs.com/gb/files/opcodes.html :
The GameBoy has instructions & registers similiar to the 8080, 8085, & Z80
microprocessors. The internal 8-bit registers are A, B, C, D, E, F, H, & L.
Theses registers may be used in pairs for 16-bit oper... |
from django.db import models
from apps.kx.models import KxUser
from rest_framework import serializers
# Create your models here.
class ShareFile(models.Model):
#owner = models.ForeignKey(KxUser, to_field='email', db_column='ower_email')
fileName = models.CharField(max_length=80, db_column='share_name')
si... |
import time
import utils
import os
from abc import ABCMeta
import tensorflow as tf
import numpy as np
"""
class Model(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
def fprop(self, x):
raise NotImplementedError
def get_logits(self, x):
logits, _ = self.fprop(x)
... |
import re
from unitree_legged_msgs.msg import LowState
from unitree_legged_msgs.msg import LowCmd
from unitree_legged_msgs.msg import MotorState
from unitree_legged_msgs.msg import MotorCmd
from sensor_msgs.msg import Imu,Joy
from geometry_msgs.msg import WrenchStamped
from std_msgs.msg import Float64
from robot_interf... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.10.20
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode \n')
import os,sys,socket,time,threading
def client_send(skt):
thread_name=threading.current_thread().name
print(thread_name... |
import numpy as np
import matplotlib
import queue
import wx
matplotlib.use('WXAgg')
from matplotlib.animation import FuncAnimation
from collections import deque
import matplotlib.pyplot as plt
import time
import csv
import cv2
import random
import sounddevice as sd
import sys
ALPHA1 = 0
ALPHA = 100000
A = np.array([[... |
class Car():
def __init__(self, brand, model, color, type, oil):
self.brand = brand
self.model = model
self.color = color
self.type = type
self.oil = oil
def drive(self):
print(self.model, "drive")
def oil_check(self):
if self.oil < 4:
pr... |
def longest_substring_without_duplication(string):
result = ''
for i in range(0, len(string)):
sub_string = string[i]
for j in range(i + 1, len(string)):
if string[j] not in sub_string:
sub_string += string[j]
else:
break
if len(res... |
import random
target="abhinav"
population_size=100
mutation_rate=0.02
letters="abcdefghijklmnopqrstuvwxyz "
letters=[letter for letter in letters]
gene_size=len(target)
class DNA:
def __init__(self):
global gene_size
self.gene_size=gene_size
self.gene=""
self.fitness=0
for i in range(s... |
from enum import Enum, IntEnum
import os.path
import subprocess
from . import util
def make_builds(cfg, revision, infos, wanted_builds, wanted_phases):
order = compute_order(cfg, infos)
print("simexpal: Making builds {} @ {}".format(', '.join([info.name for info in order]),
revision.name))
for info in order:
... |
'''
Created on 31 Mar 2015
@author: WMOORHOU
'''
from pypomvisualiser.display.TKWindowManager import WindowManager
class Visualiser(object):
'''
classdocs
'''
def __init__(self):
self.manager = WindowManager()
'''
Constructor
'''
def vi... |
"""users routes"""
from flask import current_app as app, jsonify
from models import Training
@app.route('/training/<training_no>', methods=['GET'])
def get_training(training_no):
query = Training.query.filter(Training.TrainingNo==training_no)
if query != None:
print('Exists')
block = qu... |
# -*- coding: utf-8 -*-
from openerp import models, fields, api
class stock_move(models.Model):
_inherit = "stock.pack.operation"
position = fields.Integer(string=u'Posición')
@api.model
def create(self, vals):
picking = self.env["stock.picking"].browse(vals.get("picking_id", False))
... |
import random
import os
from PIL import Image
def load_clip_video(video_path, frame_indices):
video = []
for i in frame_indices:
image_path = os.path.join(video_path, 'image_{:05d}.jpg'.format(i))
if os.path.exists(image_path):
video.append(load_image(image_path))
else:
... |
#!/usr/bin/env python
#Author: Duncan Campbell
#January 28, 2015
#Yale University
#plot the SSFR vs stellar for mock galaxies
#load packages
from __future__ import print_function
import numpy as np
import h5py
import matplotlib.pyplot as plt
import custom_utilities as cu
import sys
from astropy.cosmology import FlatL... |
"""BfCustomObject subclasses
"""
import fbx
from brenpy.cg import bpEuler
from brenfbx.fbxsdk.core import bfProperty
from brenfbx.fbxsdk.core import bfObject
from brenfbx.utils import bfFbxUtils
class BfNoteObject(
bfObject.BfObject,
bfObject.BfCustomObjectBase
):
"""
Simple object to store a user ... |
# Создадим пустой словать Capitals
Capitals = dict()
# Заполним его несколькими значениями
Capitals['Russia'] = 'Moscow'
Capitals['Ukraine'] = 'Kiev'
Capitals['USA'] = 'Washington'
Countries = ['Russia', 'France', 'USA', 'Russia']
for country in Countries:
# Для каждой страны из списка проверим, есть ли она в слов... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data_linear.csv').values
X = data[:, 0].reshape(-1, 1)
Y = data[:, 1].reshape(-1, 1)
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test... |
a=float(input("enter a number"))
b=float(input("enter another number"))
c=a*b
print(c)
|
from .Section import *
class SectionSample(Section):
def __init__(self, api, data):
"""
Internal use only: initialize section object
"""
if (not(data==None) & (type(data) == dict) &
("sectionType" in data.keys())
):
if (data["sectionT... |
from dataclasses import dataclass
from pymongo.collection import Collection
from requirementmanager.utils.uuid import generate_uuid
@dataclass
class Requirement:
project_id: str # 所属的项目id
name: str # 需求名称
description: str # 需求描述
_id: str = None
_type: str = None # 需求类型
# 基本信息
status... |
import cv2
import dlib
import numpy as np
from functools import lru_cache
from img_toolkit.geometry_utils import sort_clockwise
from img_toolkit.face_region_mask import face_img_mask
from design_pattern.decorator import Singleton
from AU_rcnn import transforms
import config
class FaceLandMark(object, met... |
from .database import Database
class SystemEmailsHelper(Database):
def __init__(self, *args):
super(SystemEmailsHelper, self).__init__(*args)
def insert_system_emails(self, user_id, email_type, status):
data = {"user_id", "email_type", "status", [user_id, email_type, status]}
return ... |
# Generated by Django 3.1 on 2021-03-05 21:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sap', '0002_studentcategories_rural'),
]
operations = [
migrations.AddField(
model_name='ally',
name='interested_in_in... |
from django.urls import path
from .views import *
app_name = "get_bank_csv"
urlpatterns = [
path("", bank_statement_page.as_view(), name="home"),
path("upload", uplode_csv, name='uplode_csv'),
path("withoutCategoryList", bank_statement_without_category_page.as_view(
), name="withoutCategoryList"),
... |
from django.shortcuts import render, HttpResponse, redirect
from .models import Resim
from .forms import PostForm
# Create your views here.
def index(request):
resimler = Resim.objects.all()
return render(request, 'index.html', {'resimler': resimler})
def resimEkle(request):
#if request.method == "GET":
... |
#!/usr/bin/env python3
import math
from decimal import *
MAX_DEN = 1000000000000
MAX_ROOT = 100000
"""
Euclidean algorithm
"""
def gcd(a, b):
if a == 0:
return b
return gcd(b%a, a)
"""
Is n square?
"""
def square(n):
root = math.floor(math.sqrt(n))
return root*root == n
"""
Calc... |
class Color:
RED = 0
GREEN = 1
BLUE = 3
BOLD = 4
def format_table(table_data, state_index=None):
"""Print a table with nice formatting.
:table_data: the data of the table including headers (2D list)
:state_index: index of the column that contains the format information
"""
col_w... |
#https://leetcode-cn.com/problems/minimum-moves-to-make-array-complementary/
'''
在1+a处,操作次数减少一次;
在a+b处,操作次数减少一次;
在a+b+1处,操作次数增加一次;
在b+limit+1处,操作次数增加一次。
'''
class Solution:
def minMoves(self, nums: [int], limit: int) -> int:
resultList = []
minMoves = 0
#构造1个limit*2的数组,假设每个TARGET数据上 对折的数... |
# -*- coding: utf-8 -*-
# @Time : 2019/2/15 22:26
# @Author : Chaucer_Gxm
# @Email : gxm4167235@163.com
# @File : Wordcloud_2_chinese.py
# @GitHub : https://github.com/Chaucergit/Code-and-Algorithm
# @blog : https://blog.csdn.net/qq_24819773
# @Software: PyCharm
from wordcloud import WordCloud
i... |
from twitter.common.net.tunnel import TunnelHelper
# This test file ensures there are no SyntaxErrors in the tunnel module.
def test_nothing():
assert True
|
from onegov.core.templates import render_macro
from onegov.core.utils import Bunch
from onegov.form import Form
from onegov.org.layout import DefaultLayout
from pyquery import PyQuery as pq
from webob.multidict import MultiDict
from wtforms.fields import StringField
class DummyRequest:
is_manager = False
is_... |
# Open and catalog list of samples observed for a given date
# on Malshare.com, location: http://www.malshare.com/daily/malshare.current.txt
# To Do:
# [x] Create output file (csv or txt?)
# [x] Store each md5 as a csv with 'hash' : 'date' mapping
# [x] Add 'search' argument that searches result file for provided hash
... |
import plt_utils
from animation import *
import html_utils
import numpy as np
import matplotlib.pyplot as plt
"""
This example shows how to extend Block class to create efficient animation
Instead of clearing and re-drawing a line on each frame use plt_utils.update_line
to update only line data and keep rest params ... |
import heapq
def kthLargestElement(nums, k):
'''
select the kth largest element in a list. We split the input into two heaps:
a max heap of size len(nums)-k on the left and a minheap of size k on the right.
We rebalance the two heaps until every element of the left heap is less than
every element of... |
from django.db import models
class Answer(models.Model):
content = models.CharField(max_length=80)
def __str__(self):
return self.content
class Question(models.Model):
content = models.CharField(max_length=80)
answers = models.ManyToManyField(Answer, related_name='question_answers')
cor... |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views import gener... |
'''
Created on 25-Dec-2018
@author: prasannakumar
'''
input1 = input("enter the first number: ")
input2 = input("enter the second number: ")
#user can also use the 'int' function to convert the string value into the number format but cannot take decimal as input.
result = float(input1) + float(input2)
print(result)
|
#!/usr/bin/env python
#encoding:utf-8
#
# Copyright (c) 2015 Ministerio de Fomento
# Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softw... |
import numpy as np
import random
from memoryfunctions import markov_update_words
import pykov
import createagentmemory
import time
from copy import deepcopy
def language_game(number_of_agents, number_of_rounds, plot_time_points, word_frequencies, initial_word_memory,
initial_word_transitions, reward):
history... |
import os
from flask import request
from templatemanager.app import app
from templatemanager.dao.document import (
Document, DocumentMongoDBDao
)
from templatemanager.mongodb import document_collection
from templatemanager.utils.handle_api import handle_response
from templatemanager.utils.uuid import generate_uuid... |
#CSCI 1133 Homework 6
#Sid Lin
#Problem 7B
class Member():
def __init__(self, ins = "None", name = "None"):
self.ins = ins
self.name = name
def getInstrument(self):
print(str(self.ins))
def getPlayer(self):
print(str(self.name))
def setInstrument(self, instrument):
... |
# general
c.backend = 'webengine'
c.content.pdfjs = True
c.downloads.location.directory = '~/Downloads'
c.editor.command = ['$EDITOR', '{file}']
c.auto_save.session = True
c.session.lazy_restore = True
c.tabs.background = True
c.tabs.last_close = 'close'
c.tabs.close_mouse_button = 'middle'
c.tabs.close_mouse_b... |
"""
@Author : Laura
@File : zt_system_test.py
@Time : 2020/3/26 10:26
"""
from Practices.hr_selenium0318.ZT_TestExample.zt_test.zt_selenium_test import TestZt
from selenium import webdriver
import unittest
import time
from ddt import ddt,data,unpack
class TestGongGao(TestZt):
def setUp(self):
su... |
# first task of assignment # 8
def add(n):
return lambda x: x + n
print add(133)(222)
|
"""
Test the routes defined in webapp/app/users/routes.py
"""
import pytest
from .conftest import check_for_docker
DOCKER_RUNNING = check_for_docker()
# use the testuser fixture to add a user to the database
@pytest.mark.skipif(not DOCKER_RUNNING, reason="requires docker")
def test_user(testuser):
assert True
... |
""" QUEUE
Time Complexity:
Access: O(n)
Search: O(n)
Insertion: O(1)
Deletion: O(1)
All above same for average (theta) case
Used:
1. When a resource is shared among multiple
consumers. Examples include CPU scheduling,
Disk Scheduling.
"""
... |
import scipy.optimize as opt
import scipy.stats as sta
import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
#initial value of rho
use_converge = 0
use_iter = 1
iteration = 15
scale = 100
ro = 0.9
converge_condition = 50
graph_scale = 0.1
#initial value of qn and qn+1
basic_q = []
for i ... |
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization
from keras import regularizers, models, layers, optimizers
from keras.datasets import cifar10
def model0():
model0 = models.Sequential()
... |
"""
accomplish the function remove_all(data, value),
the time complexity is O(n)
"""
def remove_all(data, value):
index_list = [None]*len(data)
index_num = 0
for i in range(len(data)):
if data[i] == value:
index_list[index_num] = i
index_num += 1
if index_num ... |
"""MusicBackEnd URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sistemi Corporation, copyright, all rights reserved, 2020
Martin Guthrie
"""
import logging
from core.test_item import TestItem
from public.prism.api import ResultAPI
# file and class name must match
class brthr00xx(TestItem):
""" Brother Label Printer Example
... |
# Generated by Django 2.1.2 on 2019-01-25 19:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dealer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Ca... |
#!/usr/bin/env python
"""
Get vector representation for relation extraction
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from six.moves import xrange, cPickle
import re
import os
import traceback
from pathlib import Path
import string
import pick... |
import aoc
from typing import List, Tuple, Set, Dict
from collections import namedtuple
import math
from functools import lru_cache
import itertools
from operator import itemgetter
class Vector(namedtuple('Vector', ['x','y'])):
def __add__(self, other):
assert type(other) == Vector
return Vector(se... |
# encoding: utf-8
"""
Created on 2017-2-28
@author: Kyrie Liu
@description: config command structure
"""
import time
import os
import logging
import ctypes
import threading
FOREGROUND_WHITE = 0x0007
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN = 0x02 # text color contains green.
FOREGROUN... |
import pandas as pd
from autumn.core.db import Database
from .fetch import COVID_MMR_TESTING_CSV
from autumn.core.utils.utils import create_date_index
from autumn.settings.constants import COVID_BASE_DATETIME
def preprocess_covid_mmr(input_db: Database):
df = get_mmr_data(COVID_MMR_TESTING_CSV)
df = df[['da... |
import os
import sys
main_dir = os.path.split(os.getcwd())[0]
result_dir = main_dir + '/results'
sys.path.append(main_dir)
import numpy as np
import pandas as pd
import ot
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.preprocessing ... |
import csv, sys
import boto3
## Change the TagKeyName accordingly ##
TagKeyName = 'Channel'
TagValue = False
## Change the input parameters accordingly ##
column_headers = ["tag_channel", "resource_id", "service"]
column_index = {"tag_channel": None, "resource_id": None, "service": None}
service_names = {"Amaz... |
import flask
from flask import render_template
from flask import request
from flask import url_for
import json
import copy
import uuid
# Date handling
import arrow # Replacement for datetime, based on moment.js
import datetime # But we still need time
from dateutil import tz # For interpreting local times
# Modular... |
import os
class DefaultConfig():
SECRET_KEY = os.urandom(32)
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
DEBUG = True
# Connect to the database
# TODO IMPLEMENT DATABASE URL
SQLALCHEMY_DATABASE_URI = 'postgres://... |
#!/usr/bin/env python
from sys import argv
file = argv[1:]
file = ''.join(file)
with open(file, 'r') as file:
for line in file:
if line.find('!') == -1:
print(line.strip('\n'))
|
from django.contrib import admin
from storage.models import Category, Item, ItemAction
# Register your models here.
admin.site.register(Category)
admin.site.register(Item)
admin.site.register(ItemAction)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: shoumuzyq@gmail.com
# https://shoumu.github.io
# Created on 2015/12/28 12:27
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def merge_two_list(l1, l2):
if l1 and not l2:
return l1
if l... |
import subprocess
import pymysql
conn = pymysql.connector(host='localhost'),user='root',passwd='1234',db='mysql')
cur=conn.cursor()
cur.execute("select~")
r=cur.fetchall()
cur.close()
conn.close()
subprocess.call('ls -al')
|
# REST Framework
from rest_framework import generics, permissions, status
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.test import APIRequestFactory, APITestCase
# User class fr... |
"""
controls.py - support classes for LDAP controls
See http://python-ldap.sourceforge.net for details.
\$Id: controls.py,v 1.5 2007/07/16 10:49:48 stroeder Exp $
Description:
The ldap.controls module provides LDAPControl classes.
Each class provides support for a certain control.
"""
__version__ = '0.0.1'
__all__... |
# -*- coding: utf-8 -*-
import pygame
from abs_path import resource_path
class Bullet1(pygame.sprite.Sprite):
def __init__(self):
super(Bullet1, self).__init__()
self.image = pygame.image.load(resource_path(r'resources\bullet1.png'))
self.rect = self.image.get_rect()
self.mask = ... |
from model.contact import Contact
import random
import string
import os.path
import jsonpickle
import sys
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
for o, a ... |
#! /user/bin/env python
# _*_ coding: utf-8 _*_
# __author__ = "王顶"
# Email: 408542507@qq.com
"""
在控制台中输出摄氏温度和华氏温度对照表,第一列是摄氏度,
第二列是华氏度,摄氏度从-100到300度,间隔20度。
"""
print("Celsius Fahrenheit\n-----------------")
temp = -100
while temp <=300 :
print(temp, " ", (temp * 9) / 5 + 32)
temp = temp + 20
|
import torch
from torch.autograd import Variable
from src.datatools import RLWrapper
from src.datatools import IntegersLargerThanAverage
import numpy as np
def test_RLWrapper():
set_sizes = [2, 3]
datasets = [IntegersLargerThanAverage(32, set_size, 10) for set_size in set_sizes]
environment = RLWrapper(data... |
from src.role import *
SCREEN_SIZE = (1200, 800)
DELAY_TIME = 30
BG_COLOR = 255, 255, 255
TITLE = "深海宝鉴"
|
from django.conf.urls import url
from . import views
app_name = 'demo'
urlpatterns = [
url(r'^index/$', views.index, name="index"),
url(r'^test_page/$', views.test_page, name="test_page"),
# url(r'^quick_test/$', views.quick_test, name="quick_test"),
url(r'^start_test/$', views.start_test, name="start_test"),
] |
from django.contrib import admin
from .models import Work, TitleFontColor, TitleFontSize, ExcerptFontColor, ExcerptFontSize
class WorksAdmin(admin.ModelAdmin):
fields = ('title', 'image', 'title_font_size', 'title_font_color', 'excerpt', 'excerpt_font_size', 'excerpt_font_color', 'description_1', 'description_2', ... |
import argparse
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
from models import modules, net, resnet, densenet, senet
import net_mask
import loaddata
import util
import numpy as np
from torchvision.utils import save_image
from torchvision.transforms import ToPILImag... |
#!/usr/bin/python3
def weight_average(my_list=[]):
total = 0
i = 0
if len(my_list) == 0:
return total
for x in my_list:
total += (x[0] * x[1])
i += x[1]
return (total / i)
|
from django.shortcuts import render
from django.utils import timezone
from django.urls import reverse_lazy
from django.views.generic.list import ListView #데이터 보여주기
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView,UpdateView,DeleteView #데이터 추가
from .models import Lost
... |
from django.db import models
from django.core.validators import int_list_validator
from django.contrib.auth.models import User
import os
def image_upload_path(instance, filename):
return os.path.join(
'phones',
instance.name,
filename
)
class Brand(models.Model):
name = models.Cha... |
from operator import itemgetter
import os
import warnings
from .filters import (
MSCompare,
MSHasValue,
MSNoRules,
MSNot,
MSRawFilter,
MSStrCompare,
)
from .instructions import _MS, SY, LC, LS, CS, AC, AP, TE
from .lookup import Lookup, LookupCollection
class NotImplementedWarning(UserWarning... |
from django.db import models
# Create your models here.
class Tutorial(models.Model):
title = models.CharField(max_length=70, blank=False, default='')
description = models.TextField(blank=False, default='')
published = models.BooleanField(default=False)
class Meta:
verbose_name = 'tutorial'
... |
from myhdl import *
from jpeg_utils import Add_shift_top
x = Add_shift_top()
@instance
def tbstim():
print("%8d %s" % (now(), x))
x.setSig_state_update_sample()
yield delay(1)
print("%8d %s" % (now(), x))
x.setSig_state_transfer_out()
yield delay(1)
print("%8d %s" % (now(), x))
x.setSig_state_transfer_in(... |
"""Copyright (c) 2015 Francesco Mastellone
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... |
class PredictiveParser(object):
def check_terminal(self, sym):
if not sym or sym[0].isupper():
return False
return True
def check_nonterminal(self, sym):
if not sym or not sym[0].isupper():
return False
return True
def __init__(self, start, grammar):
self.start = start
self.grammar = grammar
se... |
import numpy as np
import matplotlib.pyplot as plt
#We show that as the number of samples increase Sn/n -> mean of Xi (weak law of large numbers)
n=10000
gaussian = []
exponential = []
uniform = []
laplacian =[]
#Gaussian
mu = 0
for i in range(1,n+1):
data = np.random.normal(mu,1.0,i)
gaussian.append(np.mean(da... |
print(ord('許')) # code point (decimal)
print(chr(ord('許'))) # takes integers and returns a Unicode string of length 1
def unicode_test(value):
import unicodedata
name = unicodedata.name(value)
value2 = unicodedata.lookup(name)
print('value={}, name={}, value2={}'.format(value, name,... |
from share.harvest.base import BaseHarvester # noqa
|
import day07_part1, day07_part2
def test_part1_example():
input = """pbga (66)
xhth (57)
ebii (61)
havc (66)
ktlj (57)
fwft (72) -> ktlj, cntj, xhth
qoyq (66)
padx (45) -> pbga, havc, qoyq
tknk (41) -> ugml, padx, fwft
jptl (61)
ugml (68) -> gyxo, ebii, jptl
gyxo (61)
cntj (57)""".splitlines()
assert day07_pa... |
from layout import Layout
from pos import Pos
from size import Size
import pygame
import colour
import styles
import orientation
class ListLayout(Layout):
def __init__(
self,
size,
pos=Pos(0,0),
border=0,
spacing=0,
orientation=orientation.VERTICAL,
scaling=... |
../line_line_intersect2.py |
import os
import cv2
import numpy as np
path = 'patterns/'
save = 'resized_patterns/'
images = []
for file in sorted(os.listdir(path)):
images.append(file)
for i in range(0, len(images)):
if len(images[i].split('_')) > 1:
print(images[i])
img = cv2.imread(path+images[i],0)
img = cv2.resize(img, (640,640))... |
from typing import Tuple
from .moment import MomentTransform, MomentTransformClass
import jax
from chex import Array, dataclass
import jax.numpy as jnp
import jax.random as jr
import tensorflow_probability.substrates.jax as tfp
dist = tfp.distributions
import abc
from distrax._src.utils.jittable import Jittable
cla... |
from morepath import redirect
from onegov.core.security import Secret
from onegov.election_day import _
from onegov.election_day import ElectionDayApp
from onegov.election_day.collections import ArchivedResultCollection
from onegov.election_day.forms import EmptyForm
from onegov.election_day.layouts import DefaultLayou... |
#!/usr/bin/env python
#
# Copyright 2016 zhangtonghao <nickcooper-zhangtonghao@opencloud.tech>
#
# 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... |
from flask import Blueprint, request, current_app, render_template
from jobplus.models import Job
Job = Blueprint('job', __name__, url_prefix='/jobs')
#职位分页列表
@job.route('/')
def joblist():
# 获取参数中传过来的页数
page = request.args.get('page', default=1, type=int)
# 生成分页对象
pagination = Job.query.paginate(
... |
# -*- coding:utf-8 -*-
# @Time : 2019/5/5 3:27
# @Author: xiaoxiao
# @File : contants.py
import os
base_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
excel_name=os.path.join(base_dir,"data","python.xlsx")
global_dir=os.path.join(base_dir,"config","global.conf")
online_dir=os.path.join(base_dir,"co... |
import numpy as np
import matplotlib.pyplot as plt
# Stoichiometric matrix
V = np.array([[-1.0, 1.0, 0.0],[-1.0, 1.0, 1.0],[1.0, -1.0, -1.0],[0.0, 0.0, 1.0]])
# Parameters and Initial Conditions
nA = 6.023e23 # Avagadro's number
vol = 1e-15 # volume of system
X = np.zeros((4,))
c = np.zeros(... |
# best time to buy and sell stocks
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
back_p, front_p, gap = 0, 0, 0
for front_p in range(len(prices)):
if prices[front_p] - prices[back_p] > gap:
gap = prices[front_p] - pric... |
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 30)
y = np.cos(x)
plt.plot(x, y)
plt.xlim(-1, 5)
plt.show()
|
from onegov.gazette.collections import CategoryCollection
from onegov.gazette.validators import UnusedColumnKeyValue
from onegov.notice import OfficialNotice
from onegov.notice import OfficialNoticeCollection
from pytest import raises
from wtforms.validators import ValidationError
class DummyApp:
def __init__(sel... |
import sys
hex = "abcdef0123456789"
if __name__ == "__main__":
lines = [l.strip() for l in sys.stdin]
total = sum([len(l) for l in lines])
mem = 0
for line in lines:
line = list(line[1 : len(line) - 1])
i = 0
count = 0
while i < len(line):
count += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.