text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Python 中的文档形式:
形式 角色
#注释 文件中的文档
dir函数 对象中可用属性的列表
文档字符串__doc__ 附加在对象上的文件中的文档
PyDoc: help函数 对象的交互帮助
PyDoc: HTML报表 浏览器中的模块文档
标准手册 正式的语言和库的说明
网站资源 在线教程、例子等
出版的书籍 商业参考书籍
"""
... |
import unittest
from katas.kyu_4.next_bigger_number_with_same_digits import next_bigger
class NextBiggerTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(next_bigger(12), 21)
def test_equals_2(self):
self.assertEqual(next_bigger(513), 531)
def test_equals_3(self):
... |
# matrix_paths.py
def matrix_paths_recursive(m, n, i, j):
# base case
if i == m - 1 and j == n - 1:
return 1
# recurse into cells to the right and below if within bounds
count = 0
if i+1 < m:
count += matrix_paths_recursive(m, n, i+1, j)
if j+1 < n:
count += matrix_path... |
"""
Edanur Demir
Loss functions used in EENet training
"""
import sys
import torch
import torch.nn.functional as F
def loss(args, exit_tag, pred, target, conf, cost):
"""loss function
Arguments are
* args: command line arguments entered by user.
* pred: prediction result of each exit point.
... |
import inspect
import logging
import traceback
from .errors import BlockedFunctionError
from .events import emergency
from .logginglib import do_log
from .logginglib import get_logger
from .blocked_function import BlockedFunction
class VulnerableMachine:
"""
An abstract class that allows machines to switch ... |
driving = input('請問你有沒有開過車? ')
if driving != '有' and driving != '沒有': #driving不等於'有' ,也不等於'沒有'
print('只能輸入 有 或 沒有')
raise SystemExit
age = input('請問你的年齡? ')
age = int(age)
if driving == '有':
if age >= 18:
print('你通過測驗了')
else:
print('奇怪 你怎麼會開過車')
elif driving == '沒有':
if age >= 18... |
import unittest
from katas.kyu_6.fizz_buzz import solution
class FizzBuzzTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(solution(20), [5, 2, 1])
def test_equals_2(self):
self.assertEqual(solution(2), [0, 0, 0])
def test_equals_3(self):
self.assertEqual(solu... |
# -*- coding: utf-8 -*-
# @Author: steve yuan
# @Date: 2017-05-27 09:21:47
# @Last Modified by: steve yuan
# @Last Modified time: 2017-06-22 22:46:53
import webbrowser
class Movies():
def __init__(self, movie_title, original_network, stars,
movie_storyline, poster_image, trailer_youtube):
... |
from __future__ import print_function
import json
import optparse
import pprint
import sys
from elasticsearch import Elasticsearch
def run_elasticsearch(data_object):
es = Elasticsearch(hosts = [{"host":"localhost", "port":9200}])
if es.indices.exists("irods_audit"):
request_body = {
... |
import math
from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def heapify(i,a):
if len(a) == 0: return
leftIdx = 2*i + 1
rightIdx = leftIdx + 1
minv = a[i]
swapIdx = -1
if leftIdx < len(a):
... |
from Task903 import catprob
from Task902 import featprob
def docprob(bayes, item, cat):
cat_prob = catprob(bayes, cat)
feature = bayes.get_features(item)
for feat in feature:
feat_prob = featprob(bayes, feat, cat)
cat_prob = feat_prob + cat_prob
return cat_prob
|
import requests
import time
def main():
tikers = ['bitcoin', 'ethereum', 'dogecoin']
while True:
for tiker in tikers:
myapi_req = requests.get(f'http://127.0.0.1:8080/myapi/{tiker}').text
print(myapi_req)
print('\n')
time.sleep(5)
main() |
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
# Create your models ... |
#should be called once
import sqlite3
conn = sqlite3.connect('prot.db')
c = conn.cursor()
c.execute('CREATE TABLE protein (proid integer primary key, name VARCHAR(200), path VARCHAR(200))')
c.execute('CREATE TABLE tags (tagid integer primary key, name VARCHAR(200))')
c.execute('CREATE TABLE ptag (proid,tagid)')
conn... |
from Tkinter import Text, Tk, END, mainloop
from os.path import isfile
def read_data(file_name):
print "read operation..........."
if isfile(file_name):
f = open(file_name)
else:
f = open(file_name+"_backup")
print "Getting the data from: ", f.name
data = f.readlines()
print da... |
# -*-coding:utf-8-*-
import time
import warnings
import numpy as np
from gensim.models.doc2vec import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
import labsql
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
class D2V:
def __init__(self):
self.doc = []
... |
# -*- coding: utf-8 -*-
# @Time : 2019/11/29 23:04
# @Author : Jeff Wang
# @Email : jeffwang987@163.com OR wangxiaofeng2020@ia.ac.cn
# @Software: PyCharm
import cv2
import numpy as np
"""
本片文档学习了findcontours以及最小外接矩形以及普通矩形
"""
"""1.读取图像、转灰度、高斯滤波、Canny求边缘"""
image = cv2.imread("./picture/coins.png")
gray = cv... |
"""Admin extension tags."""
from functools import reduce
from django import template
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core import signals as co... |
# Simply the class definitions for the bot and worker declarations
# Nice way to make HTTP get requests
import requests
# A nice holder for information we need between function calls
class Bot:
double_resets = {}
def __init__ (self, token):
self.token = token
handlers = {}
# Adds a singl... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 12:41:42 2013
Computes the scaled correlation matrix of the MEG signals
and generates a matlab file for each patient
Divides the signal in multiple files
@author: bejar
"""
import scipy.io
from numpy import mean, std
import matplotlib.pyplot as plt
from pylab impor... |
"""Construct manual chart outlining columned sheets."""
from matplotlib import pyplot as plt
import xmlStaticOperators
import pandas as pd
class xmlColumnChart(object):
def __init__(self, section_dictionary, key, year):
self.section_dictionary = section_dictionary
self.key = key
self.yea... |
# partial方法: 偏对象, 将一个函数copy给另一个函数, 可以改变形参. 返回的是一个可调用对象
import functools
def my_func(a, b=2):
"""my_func's doc"""
print("{}-----{}".format(a, b))
if __name__ == '__main__':
p1 = functools.partial(my_func, "para_a", b="para_b")
p1()
print(my_func)
print(p1)
print(my_func.__name__)
pri... |
random_state = 9
import random
random.seed(random_state)
import numpy as np
np.random.seed(random_state)
import tensorflow as tf
tf.set_random_seed(random_state)
from src.data import DataBuildClassifier
from src.NN import get_model
from src.callbacks import LossMetricHistory
from sklearn.model_selection import train_te... |
#encoding: utf-8
import copy
import permutaciones
#Given n, returns a list of all the permutations
#of the list from 1..n, example:
#permutatiosnR(2) returns [[1 2] [2 1] [1 1] [2 2]]
def permutationsR(n) :
i = 2 #ya son pares...
#generar la lista [1...n]
lista = generaLista(n)
pares = paresLista(lista)
res = []
... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import uart
from esphome.const import CONF_ID
DEPENDENCIES = ['uart']
empty_uart_component_ns = cg.esphome_ns.namespace('empty_uart_component')
EmptyUARTComponent = empty_uart_component_ns.class_('EmptyUARTComponent', cg.Compo... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 21:05:16 2015
@author: bolaka
submission1.csv - first pass @ 1.25643166239
submission2.csv - first pass
"""
import os
os.chdir('/home/bolaka/python-workspace/CVX-timelines/')
# imports
import time
import datetime
from cvxtextproject import *
from mlclassificationlib... |
from ..cameras_calibration import CamerasCalibration
class TumCamerasCalibration(CamerasCalibration):
def __init__(self, final_size, original_size, device):
original_focal_x = 535.4
original_focal_y = 539.2
original_cx = 320.1
original_cy = 247.6
camera_matrix = self.calcul... |
from .. import api
import time
class Winmm(api.ApiHandler):
"""
Emulates functions from winmm.dll
"""
name = 'winmm'
apihook = api.ApiHandler.apihook
impdata = api.ApiHandler.impdata
def __init__(self, emu):
super(Winmm, self).__init__(emu)
super(Winmm, self).__g... |
#Copyright (c) 2012, Jakub Matys <matys.jakub@gmail.com>
#All rights reserved.
import logging
from gfcontroller.backends.base import GpuBackend
CRITICAL_SPEED = 100
MAX_SPEED = 70
LOGGER = logging.getLogger('_gfcontroller')
class GpuFanspeedController:
def __init__(self, backend):
assert isinstance(bac... |
from menu import Menu
class Main:
def __init__(self):
menu = Menu()
while not menu.exit_program:
menu.display_menu()
menu.menu_option()
if __name__ == "__main__":
main = Main()
|
def mod10(card):
y = len(card)
digit = 0
for x in range (0, y):
if x%2 != 0:
digit +=(card[x] * 2)
if card[x]*2 >= 10:
digit -= 9
else:
digit += (card[x])
if digit%10 == 0:
return 1
else:
... |
from setuptools import setup
setup(
name='TicTacToe',
version='1.0',
description='Simple tictactoe game',
author='Alicja Polanowska',
py_modules=['tictactoe'],
)
|
import sys
import os
# image load/save
import imageio
# image manipulation
import numpy as np
import math
def filler2(canvas, pattern, i, j, h, w):
canvas[i:i + h, j:j + w] = pattern[0:h, 0:w]
def filler3(canvas, pattern, i, j, h, w):
canvas[i:i + h, j:j + w, :] = pattern[0:h, 0:w, :]
def pattern_extender... |
# coding: utf-8
import urllib.parse
from requests_oauthlib import OAuth1
from .httpclient import requests
from .config import get_config
from .log import lg
from . import color
class OauthError(Exception):
pass
def get_oauth_token():
config = get_config()
consumer_key = config['consumer_key']
cons... |
import pytest
from dash import Dash
from rubicon_ml.viz import MetricListsComparison
def test_metric_lists_comparison(viz_experiments):
metric_comparison = MetricListsComparison(
column_names=["var_0", "var_1", "var_2", "var_3", "var_4"],
experiments=viz_experiments,
selected_metric="test... |
from devmgr.devices.models import Device
from piston.utils import rc
from client_token_factory import ClientLoginTokenFactory
import urllib
import urllib2
# handler to send a c2dm message
class C2DMSender():
def __init__(self, collaps_key = 'boguskey'):
self.url = 'https://android.apis.google.com/c2dm/sen... |
"""
Defines a class for storing sudoku puzzles.
"""
from sys import stdout, stdin
class SudokuPuzzle:
def __init__(self, size=3):
"""
Defines a new puzzle. The given size will be squared to give the width/height.
"""
self.size = size
self.width = size ** 2
# Gener... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 05 00:24:30 2015
@author: lenovo
"""
## Lec 2.5, slide 4
x = 3
x = x*x #square value of x
print(x)
y = float(raw_input('Enter a number: '))
print(y*y)
# Lec 2.6, slide 2
x = int(raw_input('Enter an integer: '))
if x%2 == 0:
print('')
print('Even')
else:
pr... |
baseline=15
minimum_detectable_effect=5.0/15*100.0
print minimum_detectable_effect
sample_size_per_variant=870
import math
yellowstone_weeks_observing=math.ceil(sample_size_per_variant / 507.0)
bryce_weeks_observing=math.ceil(sample_size_per_variant / 250.0)
print yellowstone_weeks_observing
print bryce_weeks_o... |
import math
r = {1 : "leg a", 2 : "hypotenuse c", 3 : "altitude h", 4 : "are S "}
d = []
i = int(input(""))
#i = 4
print("i : ", i)
N = float(input(""))
#N = 64
print(r[i],":",N)
if i == 1:
a = N
c = math.sqrt(2) * a
h = c / 2
S = c * h / 2
elif i == 2:
c = N
a = c / math.sqrt(2)
h = c / 2... |
import re
from cms.models.pagemodel import Page
from easy_thumbnails.files import get_thumbnailer
from haystack import indexes
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from django.utils.encoding import force_text
from django.utils.translation import activate
... |
# coding:utf-8
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
from sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error
def mianProcess(train_dt, test_dt):
train_df = pd.DataFrame... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
from documentRead import DocumentRead
def community_member(directory):
# directory ='F:\\Git Repository\\InfluenceScore_result\\'
documentReader=DocumentRead(directory)
documentReader.load_document(key_word_list='memberOfCommunity')
document_name=documentReader.get_documents_name()
community_membe... |
# Generated by Django 3.2.6 on 2021-09-27 23:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api_auction', '0003_alte... |
from django.contrib import admin
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from books import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', views.BooksList.as_view()),
path('books/<int:pk>/', views.BookDetail.as_view()),
# path('d... |
"""
This is experimental
"""
from docutils.parsers.rst import directives
import glob
import copy
class Include(directives.misc.Include):
def run(self):
if self.arguments[0].endswith('*'):
out = list()
paths = glob.glob(self.arguments[0])
for path in paths:
... |
import base64
from django.contrib.auth import login, logout
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render
from .forms import AnswerForm, AskForm, LoginForm, SignupForm
from .models import Question, Answer
... |
from django.core.serializers import json
from python import Deserializer
json.PythonDeserializer = Deserializer
from django.core.serializers.json import *
|
import pandas as pd
import numpy as np
from random import randint
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pylab as pylab
from scipy import stats
import os.path
def guessCorrectness(guessedRightCnt, guessUpCnt, guessDownCnt, guessSkipCnt, rewardSum, guessCnt, profit, period):
correc... |
import classes
lib=classes.library()
for i in range(5):
lib.add_book(classes.create_new_book(Year=str(i)))
lib.all_books_info()
print("\n\n")
lib.book_(2)
lib.delete_book(2)
print("\n\n")
lib.all_books_info()
print("\n\n")
lib.book_(2)
|
from django.shortcuts import render,redirect
from django.http import HttpResponse
import datetime as dt
from django.http import Http404
from .models import Image
# Create your views here.
def welcome(request):
title='Gallery Webpage'
images= Image.objects.all()
return render(request, 'all-photos/image.htm... |
from builder import window
from data_grabber import data
from label_maker import *
root = window()
root = root.get_window()
text = ["this is a test", "this is a second test"]
data_object = data()
data_object.assign_labels(text)
label_object = labels(root)
label_object.build_labels(data_object)
my_labels = label_ob... |
from django.shortcuts import render
from .models import Project
# Create your views here.
def home(request):
projects = Project.objects.all()
context = {'project': projects
}
return render(request, 'homepage.html', context)
def project_index(request):
projects = Project.objects.all()
context = ... |
#Setup Start
# Import required Python libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO referencesinstead of physical pin numbers
# Throughout this book you will be using BCM GPIO reference to maintain the consistency
GPIO.setmode(GPIO.BCM)
# Defines the GPIO port number which will be used for Trigger and... |
import numpy as np
Output_filename = "ImageDataSetUnbalanced"
# Loading Datasets
Air = np.load('air_raw_3d_dataset.npy')
Air_mean = np.load('Mean_Array_air.npy')
Air_std = np.load('Std_Array_air.npy')
P_water = np.load('pr_wtr_raw_3d_dataset.npy')
P_water_mean = np.load('Mean_Array_pr_wtr.npy')
P_water_std = np.load(... |
#!/usr/bin/env python
# coding: utf-8
# In[78]:
import requests #Used to service API connection
from lxml import html #Used to parse XML
from bs4 import BeautifulSoup #Used to read XML table on webpage
import pandas as pd
#from pandas import DataFrame
import numpy as np
import wget
from common import cFunction as cf... |
from itertools import groupby
import json
from pprint import pprint
import re
import sys
with open(sys.argv[1]) as f:
chunks = re.split(r"\n\n+", f.read())
with open(sys.argv[2]) as f:
known_chars = json.load(f)
# play is a list of lists, each list represents an act
# act is a list of lists, each list repres... |
import requests
import json
url = 'http://localhost:8888'
url += '/v1/version'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
if __name__ == '__main__':
response = requests.get(url, headers=headers)
print(json.dumps(json.loads(response.text), indent=4, ensure_ascii=False))
|
#!/usr/bin/env python3
import base64
import binascii
import sys
import struct
class Message():
def __init__(self, dir, raw, tstamp):
self.som = None
self.message_length = None
self.message_class = None
self.seq_number = None
self.message_type = None
self.message = No... |
"""Object Services Classes."""
import logging
from .anyprotocolportobjects import AnyProtocolPortObjects
from .applications import Applications
from .applications import Application
from .applicationcategories import ApplicationCategories
from .applicationcategories import ApplicationCategory
from .applicationfilters ... |
#!/usr/bin/python3
"""
Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
""" methods for testing the function 'max_integer()' """
def test_null(self):
""" find greater- list null """
self.asser... |
from dllist import *
def test_create_list():
colors = DoubleLinkedList()
colors.dump()
def test_push():
print(f"\n\nTesting Push.")
colors = DoubleLinkedList()
colors.push("Pthalo Blue")
colors._invariant()
assert colors.count() == 1
colors.push("Ultramarine Blue")
assert colors.co... |
"""
token url =
https://oauth.vk.com/authorize?client_id=6320433&display=page&scope=140492191&response_type=token&v=5.8
"""
# vk settings
TOKEN = "971d715516dfe12c4321ec449d531a63b78dff794ee1682e849ff1e069bdecec47191be1e48b8051812b1"
API_VERSION = "5.69"
MAIN_USER_ID = 69128170
# protege settings
ONTOLOGY_NAME = "Ont... |
import mimo
_backbuffer = []
_image = []
_buffer = []
_current_color = 0xf00
def reset():
global _backbuffer
global _image
global _buffer
_backbuffer = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0... |
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save, pre_save, m2m_changed
from django.utils.text import slugify
class Category(models.Model):
name = models.CharField(max_length=45)
word = models.ManyToManyField('Word', related_name="category... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 15:26:31 2019
@author: xinyancai
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
df = pd.read_csv('~/Desktop/data/heloc_dataset_v1.csv')
df.RiskPer... |
import copy
import logging
import os
from subprocess import check_call
from typing import Any, Dict, Iterable
import yaml
from art.config import ArtConfig
from art.consts import DEFAULT_CONFIG_FILENAME
log = logging.getLogger(__name__)
def run_prepare(config: ArtConfig) -> None:
for prepare_step in config.prep... |
# -*- coding: utf-8 -*-
class Solution:
def gameOfLife(self, board):
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
self.computeSquare(board, i, j)
for i in range(m):
for j in range(n):
self.updateSquare(board,... |
import datetime
def add_gigasecond(birth_date):
return birth_date + datetime.timedelta(seconds=10**9)
|
from enum import Enum, auto
import socket
from typing import Dict
from Response import Response
import time
class Client:
def __init__(self, sock: socket.socket):
self.sock = sock
self.state = State.NOT_GREETED
self.username: str = None
self.last_interaction_time: time.time = tim... |
"""Functions for handling the network rules directory files.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import glob
import errno
import logging
import os
import time
from treadmill import ... |
# http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf
# https://youtu.be/vXPL6UavUeA
# https://youtu.be/QCnANUfgC-w
import string
import collections
def parse_command(user_input):
if user_input[1:] == "exit":
print("Bye!")
exit()
elif user_input[1:] == "help":
print("""Th... |
#! /usr/bin/env python
#!/usr/bin/env python
from __future__ import print_function
from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
import rospy
def calculate_joint_angles(req):
xc = 3
yc = 1
zc = 5
a1 = 2
a2 = 2
d3 = 8
# r = (pow(xc, 2) + pow(yc, 2) - pow(a1, 2) - pow(a2, 2)) / 2*a1
# # print(r)
... |
# Generated by Django 2.0.7 on 2020-08-13 10:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('aid', '0002_auto_20200812_1604'),
]
operations = [
migrations.AddField(
model_name='drug',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-09 14:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0010_auto_20170609_1427'),
]
operations = [
migrations.AddField(... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example ... |
#I pledge that I have abided by the Stevens Honors System-Yash Jalan
def main():
first = open("Before.txt", "r")
revised = open("After.txt", "w")
for l in first:
names = l.upper()
print(names,file=revised)
first.close()
revised.close()
main() |
def leiadinheiro(txt):
while True:
val = input(txt)
if val.isnumeric():
ret = val
break
else:
if val.find('.') != -1:
ret = val.replace('.', '')
if ret.isnumeric():
ret = int(ret) / (10**(len(ret) - val.f... |
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import TestCase
sys.path.append("..")
DATA_DIR = "%s/../../data/test" % pathlib.Path(__file__).parent.absolute()
WORK_DIR = "/tmp/semeval-tests"
def download_squad():
import zipfile
import requests
from tqdm import tq... |
# path visualize browser
import os
from tkinter import *
class CameraVisualizer:
def __init__(self):
pass
|
import matplotlib.pyplot as plt
import numpy as np
import math
from scipy.integrate import odeint
def f(p, v, T, m):
k = 1.380649*(10**(-23))
pi = math.pi
p = 4*pi*((m/(pi*k*T))**(3/2))*(v**2)*np.exp(-(m*(v**2))/(k*T))
return p
v = np.arange(0, 10000, 1)
m = 1.67*(10**(-27))
T = np.arange... |
#!/usr/bin/env /data/mta/Script/Python3.6/envs/ska3/bin/python
#############################################################################################
# #
# plot_acis_focal_temp.py: plot acis focal temperature tre... |
from rest_framework.routers import DefaultRouter
from api.customers.views import CustomerViewSet
router = DefaultRouter()
router.register(r"^", CustomerViewSet)
urlpatterns = router.urls
|
# Modules
import os
import csv
# Path to collect data from the Resources folder
infile = os.path.join('Resources', 'budget_data.csv')
budgetDataCsv = csv.reader(open(infile))
header = next(budgetDataCsv)
# Define Variables
months = []
totalMonths = 0
netTotal = 0
profitLoss = []
profitLossStepped = []
# Loop throu... |
import logging
import sys, os
from abc import abstractmethod
import eons
from .DataFunctor import DataFunctor
from ..SampleSet import SampleSet
#AnalysisFunctors are used in data manipulation.
#They take a configuration of known values (config) in addition to sample data, which is contains unknown and/or values of int... |
# --------------------------------------------------------------------------------- #
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 24 Nov 2011, 22.00 GMT
#
#
# TODO List
#
# 1) Anything to do?
#
#
# For all kind of problems, requests of enhancements and bug reports, pleas... |
class _NoModuleFound(Exception): ...
class InvalidName(ValueError): ...
class ModuleNotFound(InvalidName): ...
class ObjectNotFound(InvalidName): ...
def reraise(exception, traceback) -> None: ...
def namedAny(name): ...
|
#LEG MODULE
import maya.cmds as mc
import frank
def addAttributes(parentNode):
# METHOD TO ADD THE ATTRIBUTES NEEDED FOR THIS RIG MODULE
mc.setAttr((frank.addString('cucu', parentNode)), 'CULO', type='string')
def buildRigGuides():
mc.select(cl = 1)
mc.joint(p = [0,3,0], n = 'L_arm1_rigGuides')
mc.joi... |
# http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
palabra = input ("Introduce una palabra: ")
sinespacioslista = []
for letra in palabra:
letra = letra.lower()
if (letra == "á" or letra == "à" or letra == "ä" or letra == "â"):
letra = "a"
if (letra == "é" or letra == "è" or ... |
#program to find the area of a triangle if all 3 sides are given
import math
a=input ('enter first side:')
b=input ('enter second side:')
c=input ('enter third side:')
s=(a+b+c)/2.0
print 'semi-perimeter=',s
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print 'area=',area
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from internal_plugins.test_lockfile_fixtures.rules import rules as test_lockfile_fixtures_rules
from pants.backend.python.register import rules as python... |
import sys
import os
from numpy import *
import numpy as np
import numpy.random
from sklearn.datasets import fetch_mldata
import sklearn.preprocessing
from numpy import linalg as LA
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
mnist = fetch_mldata('MNIST original')
data = mnist['data']
labe... |
from onewire.device import Onewire
from onewire.config import load_cfg
import time
if __name__ == '__main__':
cfg = load_cfg()
base_dir = cfg.get('general', 'base_dir')
onewire = Onewire(base_dir=base_dir)
onewire.load_device()
while True:
for i in onewire.device_list:
print i.n... |
import datetime
from django.test import TestCase
from django.contrib.auth import get_user_model
from .. import models
from unittest.mock import patch
def sample_user(email='test.random@mail.com', password='11111'):
"""Creates a sample user"""
return get_user_model().objects.create_user(email=email, password=p... |
"""
=================
Testing Utilities
=================
This module contains data generation tools for testing vivarium_public_health
components.
"""
from itertools import product
import pandas as pd
def make_uniform_pop_data(age_bin_midpoint=False):
age_bins = [(n, n + 5) for n in range(0, 100, 5)]
sexe... |
import os
import itertools
import numpy as np
import cv2
os.chdir(os.path.dirname(__file__))
DEBUG = False
def pick_color(filename):
colors = []
im0 = cv2.imread(filename)
im0 = cv2.resize(im0, (960, 960))
for y, x in itertools.product(range(8), range(8)):
x1, x2 = [ x * 86 + 146, x * 86 + 2... |
# List is a value that contains values.
# It contains multiple values in an ordered sequence.
# Lists start at index 0
# They are denoted by [] with each item seperate by a comma ','
newList = ["One", "Two", "Three"]
# To access a value within a list we use an integer index.
newList[0]
# = "One"
# It is possible ... |
from django.forms import ModelForm
from .models import Employee, Passport, Statement
from django import forms
class DateInput(forms.DateInput):
input_type = 'date'
class PassportForm(ModelForm):
class Meta:
model = Passport
fields = ['fullname', 'serial_number', 'address', 'issed', 'code_sub... |
import sys
import requests
from fastapi import FastAPI
from fastapi.responses import Response
version = f"{sys.version_info.major}.{sys.version_info.minor}"
app = FastAPI()
@app.get("/")
async def read_root():
message = f"Hello world! From FastAPI running on Uvicorn with Gunicorn. Using Python {version}"
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.