text
stringlengths
8
6.05M
from django.contrib import admin from myblog.models import Board admin.site.register(Board)
n=0 def Epsilon(n): if (1+2**-n)==(1+2**(-n-1)): return 2**-n else: return Epsilon(n+1) print(Epsilon(n)) def EpsilonConCiclo(n): while (1+2**-n)!=1+2**(-n-1): n+=1 return(2**-n) print(EpsilonConCiclo(n))
from django.views.generic import FormView from django.urls import reverse_lazy from django.contrib import messages from django.utils.translation import gettext as _ from django.utils import translation from .models import Service, Employee, Feature, Plan, Client from .forms import ContactForm class IndexView(FormVie...
# -*- coding: utf-8 -*- from pyspark import SparkContext from pyspark.sql import * from pyspark.sql.types import * import dateutil.parser as date import json from pymongo import MongoClient spark = SparkSession\ .builder\ .master("spark://stack-02:7077")\ .config("spark.cores.max", 2)\ ....
#! python3 from pandas import read_csv data = [{ "name": "Bob", "gender": "male", "birthday": "1992-10-08" }, { "name": "Kavey", "gender": "female", "birthday": "1995-05-12" }] with open('data.csv', 'a', newline='') as csvfile: fieldnames = ['name', 'gender', 'birthday'] writer =...
import logging import logging.config import os import subprocess from . import DockerWrapper from .PlatformClient import PlatformClient from . import PlatformStructs as Pstruct import dotenv import time import traceback class Mediator(PlatformClient): def __init__(self): super().__init__() self.log...
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import itertools import logging from abc import ABC, ABCMeta from dataclasses import dataclass from enum import Enum from pathlib import PurePath from t...
''' Copyright 2018 Google LLC 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 apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under ...
from random import randint, choice from glm import vec3 from game.base.entity import Entity from game.constants import CLOUD_IMAGE_PATHS class Cloud(Entity): if randint(0, 10) <= 5: hdg = -1 else: hdg = 1 def __init__(self, app, scene, pos: vec3, z_vel: float): vel = vec3(randin...
from django.shortcuts import render # Create your views here. from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import CreateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin from . import models from . import serializers from rest_framework_jwt.authentication import JSONWebTok...
# Generated by Django 2.0 on 2018-01-30 16:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hamyar', '0011_auto_20180130_1624'), ('madadju', '0008_report'), ('madadkar', '0001_initial'), ] oper...
# Generated by Django 3.1.4 on 2020-12-27 12:42 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Player', fields=[ ('id', models.AutoField(a...
import sys import csv import os, random from flask import Flask, render_template, url_for, request, Markup, redirect app = Flask(__name__) @app.route('/') def main(): return render_template('base.html') @app.route('/analysis/<lat>/<lng>', methods=['GET']) def ana(lat, lng): # getData gets a 2D array # ...
# Generated by Django 2.0.7 on 2019-06-19 16:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('storage', '0003_auto_20190619_1536'), ] operations = [ migrations.AddField( model_name='data', name='name', ...
# -*- coding: utf-8 *-* import hashlib import logging import pickle import re import urllib import warnings import sys import tormysql import tornado from tornado import gen from tornado.concurrent import is_future from tornado.options import options as opts def query_finish(result): return result class DB(): ...
""" # 基于链表实现循环链表 """ import os import logging logger = logging.getLogger(__name__) class Node(object): """创建链表节点数据结构""" def __init__(self, value, next=None): self.value = value self.next = next class Error(Exception): """异常处理""" def __init__(self, msg='empty'): super().__ini...
# import unittest # # from selenium import webdriver # from selenium.webdriver.chrome.webdriver import WebDriver # # from webdriver_manager.chrome import ChromeDriverManager # # from tests.testCancelRequest import CancelChangeRequest # from tests.testCloseRequest import CloseChangeRequests # from tests.testCreateReques...
class TreeNode(object): """ Definition of a binary tree node.""" def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # max depth top down def mD(self, root): return max(self.mD(root.left), self.mD(root.right)) + 1 if root else 0 ...
#!/usr/bin/env python """ Takes a list of bibcodes and gets the ADS data in a latex list of items and writes it out to a file. You can get all your bibcodes by going to this URL (replacing 'Birnstiel,+T.' with your name and initial): http://adsabs.harvard.edu/cgi-bin/nph-abs_connect?author=Birnstiel,+T.&jou_pick=NO&...
#!/usr/bin/env python3 # coding: utf-8 # """Print the commands in some ("my") directories of the ones listed in PATH These "my" directories are determined as: (1) Directories beginning with my home directory (for something like /home/me/bin) if this directory is not listed with a '-' sign at the beginning in t...
import unittest from katas.beta.get_number_from_string import get_number_from_string class GetNumberFromStringTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(get_number_from_string('1'), 1) def test_equal_2(self): self.assertEqual(get_number_from_string('123'), 123) ...
#!/usr/bin/python3 import socket import math import time import pigpio # For managing any I/O import threading import queue import xml.etree.ElementTree as ET # pifighterinit does some of the initialisation for the program - getting mode set up, etc. from pifighterinit import * import pifighterstrip...
# Generated by Django 3.0.5 on 2020-11-22 15:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0011_update_proxy_permissions'), ('user', '0002_customuser_alias'), ] operations = [ migrat...
class Tree(object): def __init__(self): self.attribute="" self.children={} self.prediction="" self.informationGain=0 def setPrediction(self,label): self.prediction=label def getPrediction(self): return self.prediction def setAttribute(self,at...
n = int(input("Digite um numero: ")) if n < 0: print ("Numero invalido. Digite apenas valores positivos ") if n == 0 or n == 1: print (f"{n} é um caso especial.") else: if n == 2: print("2 é primo") elif n % 2 == 0: print (f"{n} não é primo, pois 2 é o único numero par primo") else: ...
# unreal.AssetToolsHelpers # https://api.unrealengine.com/INT/PythonAPI/class/AssetToolsHelpers.html # unreal.AssetTools # https://api.unrealengine.com/INT/PythonAPI/class/AssetTools.html # unreal.EditorAssetLibrary # https://api.unrealengine.com/INT/PythonAPI/class/EditorAssetLibrary.html # All operation...
import torch import torch.nn as nn import math from IPython import embed class ReconstructionLoss(torch.nn.Module): def __init__(self): super(ReconstructionLoss, self).__init__() self.tanh = nn.Tanh() def forward(self, ori_embeds, model_embeds, embed_l): # (B, L, E) temp = torc...
""" 折线图: 2.1注意: 1.可以只提供y的数据,也可以提供多对x,y的数据 """ from matplotlib import pyplot as plt import numpy as np x = np.arange(10) # 绘图方法: fig = plt.figure() ax = fig.add_subplot() ax.plot(x, x**2, 'r-.', x, 2*x, 'b-') plt.show()
from django.test import TestCase from django.contrib.auth.models import User from django.utils import timezone from django.dispatch import receiver from projects.models import ( Dependency, ProjectDependency, ProjectBuild, generate_projectbuild_id, ProjectBuildDependency, projectbuild_finished) from .factories...
from abc import ABCMeta, abstractmethod, abstractproperty import config class Response: __metaclass__ = ABCMeta @property @abstractmethod def _message(self): pass @property def message(self): message_ = self._message + config.MESSAGE_DELIMINATOR print(message_) ...
#!/usr/bin/python3 """ MODEL_CITY MODULE Provides the class and methods to interact with the cities table in the DB. """ from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class City(Base): """Represents a City in the DB...
class Solution(object): def maxProfit(self, prices): if prices is None or len(prices)==0: return 0 #Min, Max max_profits = [[0,0], [0,0]] latest = max_profits[0] #Find min-max ranges in array for i in range(len(prices)): if prices[i] <= prices[...
#!/usr/bin/env python import json import sys import urllib2 twitter_url = 'http://search.twitter.com/search.json?q=from:Hashtag_Fresno' response = urllib2.urlopen(twitter_url) data = json.loads(response.read()) for tweet in data['results'][:5]: print tweet['created_at'] print tweet['text'] print '' # bla...
#%% import requests from bs4 import BeautifulSoup import smtplib import time URL = r"https://www.bestbuy.com/site/acer-s271hl-27-led-fhd-monitor-black/6051018.p?skuId=6051018" headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari...
import flask import multiprocessing import os import tempfile from six.moves import cStringIO as StringIO from smqtk.utils import SmqtkObject from smqtk.utils import file_utils script_dir = os.path.dirname(os.path.abspath(__file__)) class FileUploadMod (SmqtkObject, flask.Blueprint): """ Flask blueprint ...
# Copyright (c) 2020 Adam Souzis # SPDX-License-Identifier: MIT from __future__ import absolute_import import os.path import six from six.moves.configparser import ConfigParser from supervisor import xmlrpc try: from xmlrpc.client import ServerProxy, Fault except ImportError: from xmlrpclib import Server as ...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist from turtlesim.msg import Pose from math import pow, sqrt, atan2 import numpy x= 0 y= 0 theta = 0 velocityPublisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) def callback(data): rospy.loginfo('Mis coordenadas antes de reci...
import unittest import numpy as np from core.field_transformer import FieldTransformer class FieldTransformerTest(unittest.TestCase): def test_sets_mark_to_coordinates(self): field = np.matrix('0 0 0; 0 0 0; 0 0 0') field_transformer = FieldTransformer(field, 1, (0, 0)) assert (field_tran...
def divisors(n): div = [] for i in range(1, n + 1): if n % i == 0: div.append(i) return len(div)
# -*- coding: utf8 -*- from flask import Blueprint, render_template, request, send_file, Response import config from pathlib import Path import os from natsort import natsorted, ns from os import listdir from os.path import isfile, join, isdir import get_image_size from thumbnail import create_thumbnail from flask im...
entrada = input().split(" ") a = int(entrada[0]) b = int(entrada[1]) while( a != 0 and b != 0): resultado = a + b resultado = str(resultado) resultado = resultado.replace('0','') print(resultado) entrada = input().split(" ") a = int(entrada[0]) b = int(entrada[1])
import serial from serial import Serial from time import sleep import time import sys import py222 import solver import numpy as np COM_PORT = 'COM4' # 請自行修改序列埠名稱 BAUD_RATES = 9615 ser = serial.Serial(COM_PORT, BAUD_RATES,bytesize=8, timeout=2) try: # 接收用戶的輸入值並轉成小寫 while True: choice = input('輸入"hel...
""" Crea un tabla de multiplicar pero invertida, dando los resultados desde el 10 hasta el 1 """ numero=int(input("Escribe un número: ")) aux=9 for a in range(1,11): a+=aux aux-=2 resultado=numero*a print("{}*{}={}".format(numero,a,resultado))
''' this program provide 3 functions 1. pcd map convert frame utm to enu 2. merge each small map to global map 3. downsample map uniformly Need Library: numpy open3d ''' import os import numpy as np import open3d from tqdm import tqdm # prefixes is list of map to combine prefixes=[ "Track_A_20201223...
#!/usr/bin/env python3 import math import queue from functools import cmp_to_key import fileinput class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self...
# -*- coding: utf-8 -*- class UF: def __init__(self,N): def union(self,p,q): # initialize N sites with integer names def find(self,p): #return component identifier for p def connected(self,p,q): #return true if p and q are in the same component def count(): #number of components
from typing import Tuple, List, Optional, Dict, Any, Set from . import Verb, WorkloadExceededError from .interface import Block from itertools import islice def build_node_tree(message : str) -> List['Interpreter.Node']: """ build_node_tree will take a message and get every possible match """ nodes...
'''Задание 1''' nums = [14, 21, 565, 18, 33, 20, 102, 108, 167, 891, 400] for number in nums: if number % 2 == 0: nums.remove(number) print(nums) '''Задание 2''' sentence = ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] longer_than_4 = [word for word in sentence if len(...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from textwrap import dedent import pytest from pants.backend.java.compile.javac import rules as javac_rules from pants.backend.java.dependency_inference.rules import ( InferJavaSourc...
from sys import stdin, exit from random import choice import Player, Colonies player_list = [] game = True class gameSetup(object): def __init__(self): self.max_players = 0 self.player_limit = 12 self.starting_era = 0 self.players = 0 def setupGame(self): self.decision = raw_input("Do you wish to start...
__author__ = 'Sebastian Bernasek' import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter from .base import Base from .settings import * from .palettes import Palette, line_colors class Expression(Base): """ Object for plotting expression dynamics. Attributes...
class Bag: # initiate local variables establishing assumptions where bag can hold a maximum of 8 and each size has an associated number def __init__(self): self.items = [] self.space_remaining = 8 self.size_values = {"small": 1, "medium": 2, "large": 3} # adds item to bag if space remaining def ad...
# -*- coding: utf-8 -*- """ oauthlib.oauth2.rfc6749.grant_types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import unicode_literals, absolute_import from .authorization_code import AuthorizationCodeGrant from .implicit import ImplicitGrant from .resource_owner_password_credentials import ResourceOwnerPass...
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * urlpatterns = patterns('Avaliacao.Questao.views', url(r'^responderQuestao/(?P<questao_id>\S+)/$', 'responderQuestao', name='responderQuestao'), url(r'^corrigirQuestao/(?P<questao_id>\S+)/$', 'corrigirQuestao', name='corrigirQuestao'), url...
# Generated by Django 2.2 on 2022-06-10 02:55 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0015_memberinvite_player'), ] operations = [ migrations.AlterField( model_name='group', ...
import argparse import gc import pickle import re import time from functools import partial, reduce from glob import glob from itertools import * from operator import add, iadd from os import path, remove, stat, walk import numpy as np from joblib import Parallel, delayed, dump, load # from multiprocess import Pool fr...
num1 = int(input("Informe o número 1: ")) num2 = int(input("Informe o número 2: ")) print(f'{num1} + {num2} = {num1+num2}')
from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sqlite3 class DeleteL(QDialog): def __init__(self, *args, **kwargs): super(DeleteL, self).__init__(*args, **kwargs) self.QBtn = QPushButton() self.QBtn.setText("Удалить") self.setWindowIcon(QIcon("icon/deleteL...
""" 类别:论语 """ import sqlite3 import os import json def make_db(db, path): sql = ''' CREATE TABLE IF NOT EXISTS "lunyu" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "chapter" TEXT, "paragraphs" TEXT ); ''' print('\r\n论语 正在初始化...') try: conn = sqlite3.connect(db) cur = conn.curso...
def handle_sheet(*args): # TODO pass
n = int(input('Digite um número: ')) s1 = n * 2 s2 = n * 3 s3 = n ** (1/2) print(f'O dobro de {n} vale {s1}') print(f'O triplo de {n} vale {s2}') print(f'A raiz quadrada de {n} é igual a {s3:.2f}')
# speedtest.py: FFT benchmark import sys import time import math import numpy as np from scipy.fftpack import fft from streamtools import * def time_fft(secs=10): print "Capturing for", secs, "seconds" stream = InStream() nblocks = seconds_to_blocks(stream, secs) avg_read = 0 # should be 44100 Hz avg_fft = 0 #...
from math import ceil, floor, trunc, pow, sqrt import emoji print(emoji.emojize("Ráiz Quadrada :earth_americas:", use_aliases=True)) num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raíz de {} é igual a {}'.format(num, raiz))
# -*- coding: utf-8 -*- """ ytelapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class NumberTypeEnum(object): """Implementation of the 'NumberType' enum. The capability supported by the number.Number type either SMS,Voice or all Attrib...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json from textwrap import dedent from typing import Callable, Optional import pytest from pants.backend.python.target_types import PexExecutionM...
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) import tensorflow as tf # Model x = tf.place x = tf.placeholder(tf.float32, [None, 784], name="x") x_image = tf.reshape(x, [-1,28,28,1]) tf.summary.image('input', x_image, 3) W = tf.Variable(tf.ze...
import xml.dom.minidom def getxml(value=None): """获取单节点的数据内容""" xmlFile = xml.dom.minidom.parse('data.xml') db = xmlFile.documentElement itemList = db.getElementsByTagName(value) item = itemList[0] return item.firstChild.data def getUser(parent=None, child=None): """获取单节点的数据内容""" xmlF...
"""return true if there is no e in 'word', else false""" def has_no_e(word): """return true if there is e in 'word', else false""" def has_e(word): """return true if word1 contains only letters from word2, else false""" def uses_only(word1, word2): """return true if word1 uses all the letters in word2, else false...
''' @Description: DFS @Date: 2020-05-31 11:45:50 @Author: Wong Symbol @LastEditors: Wong Symbol @LastEditTime: 2020-06-02 11:30:09 ''' ''' DFS ''' class Graph(): def __init__(self): # 以字典的结构模拟 邻接表 结构 self.data = { 'a' : ['b', 'c'], 'b' : ['a', 'c', 'd'], 'c' : ...
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): # base case: # if the length of the word is...
#!/usr/bin/env python3 from memory_profiler import profile NUM = 5 TOTS = 100000000 lrange = lambda size : list(range(size)) def fun_flat(): alist = lrange(TOTS) alen = len(alist) print(alen) blist = lrange(TOTS) blen = len(blist) print(blen) clist = lrange(TOTS) clen = l...
name = 'gitoo' description = 'Odoo third party addons installer.' url = 'https://github.com/numigi/gitoo' email = 'contact@numigi.com' author = 'numigi'
# -*- encoding:utf-8 -*- # __author__=='Gan' # Given a set of candidate numbers (C) (without duplicates) and a target number (T), # find all unique combinations in C where the candidate numbers sums to T. # The same repeated number may be chosen from C unlimited number of times. # Note: # All numbers (including targe...
from django.shortcuts import render from rest_framework import viewsets, permissions, status from rest_framework.response import Response from .serializers import userSerializer, ImageUserSerializer from django.contrib.auth.models import User from .models import ImageUser from rest_framework.decorators import action fr...
# Generated by Django 2.1.11 on 2020-01-06 12:54 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Jpyutc', fields=[ ('id', models.AutoField(...
import mcpi.minecraft as minecraft import mcpi.block as block mc = minecraft.Minecraft.create() # desenha uma parede de 5 x 8 à frente do jogador [x,y,z] = mc.player.getPos() i = 0 while i < 5: j = 0 while j < 8: mc.setBlock(x+i,y+j,z+3,block.STONE) j += 1 i += 1
from rply import LexerGenerator from rply import Token def build_lexer(): lexer = LexerGenerator() # Lexer Analysis Rules lexer.ignore(' ') lexer.add("WHATEVR", r"WHATEVR") lexer.add("VISIBLE", r"VISIBLE") lexer.add("KTHXBAI", r"KTHXBAI") lexer.add("GIMME", r"GIMME") lexer.add("MKAY",...
import os # get the file path from the user and change the path path = input('enter the file path :') file_name = input('input file name :') os.chdir(path) file_counter = 1 number_of_digits=int((len(os.listdir(path))/10+1))#to organize the format using .zfill function # list all file in the direc...
# coding: utf-8 # # Hypothesis Testing # This code does the following: # * Reads the FC files for all the subjects # * Z-Standardize all the voxel-roi correlation values of each ROI # * Perform two tailed t-test for each voxel-roi pair correlation across subjects (Autism vs TD) # In[192]: import nibabel as nib imp...
from router_solver import * import pygame import game_engine.constants from game_engine.constants import * class SpriteSheet(object): def __init__(self, file_name): # Load the sprite sheet. BLACK = (0, 0, 0) self.sprite_sheet = pygame.image.load(file_name).convert() self.sprite_she...
# Generated by Django 2.1.2 on 2018-10-06 03:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='NbaNews', fields=[ ('id', models.AutoField(...
import argparse # defaults DEF_MODEL_PATH = "ssdlite_mobilenet_v2_coco_2018_05_09.pb" DEF_LABEL_PATH = "label/mscoco_label_map.pbtxt" DEF_CONFIDENCE = 0.5 DEF_CAMERA_ID = 0 DEF_VERBOSE_LOG = False DEF_TARGET_CLASS = 1 # detect people DEF_LOST_FRAME = 20 DEF_TRACKING_HISTORY = 10 # argument description parser_cfg = a...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from typing import List import pytest from pants.backend.project_info.dependents import DependentsGoal from pants.backend.project_info.dependents import rules as dependent_rules from pan...
import PIL from PIL import ImageFilter from sklearn.cluster import KMeans import matplotlib.pyplot as plt from skimage.filters import scharr from skimage import color,morphology import numpy as np import pdb num_segs = 3 DEBUG = False # this draws the segmentation clustering for illustration def CNR(nparr_img,method...
import pandas as pd import numpy as np import tensorflow as tf import os from sklearn.model_selection import train_test_split from data_generation import load_data, get_field_vocab_size from model import model from recommendation import final_recommendation, write_recommendation_file target_df = './dataframe/test_df_2...
import itertools import sys import time import warnings from functools import partial from threading import Event from typing import Tuple, Union from ._log import SceneLog from ._user_namespace import UserNamespace from ._vis_base import VisModel, Control, Action from .. import field, math from ..field import Scene, ...
## GIS2BIM Library def GIS2BIM_CreateBoundingBox(CoördinateX,CoördinateY,BoxWidth,BoxHeight,DecimalNumbers): XLeft = round(CoördinateX-0.5*BoxWidth,DecimalNumbers) XRight = round(CoördinateX+0.5*BoxWidth,DecimalNumbers) YBottom = round(CoördinateY-0.5*BoxWidth,DecimalNumbers) YTop = round(CoördinateY+0...
#!/usr/bin/python import numpy as np import pylab as py from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv from scipy import integrate import COMMON as CM from USEFUL import time_estimate from matplotlib import colors from scipy import interpolate as ip #Input parameters: zbins=500 #Number of z-bin...
import numpy as np import matplotlib.pyplot as plt def analyse(filename): """ Reads data from the specified file and plots the average, maximum and minimum along the first axis of the data. Parameters ---------- filename : str Name or path to a file containing data to be plotted. Data ...
char_1 = input() char_2 = input() char_3 = input() # print(char_1 + char_2 + char_3) print(f"{char_1}{char_2}{char_3}")
# -*- coding: utf-8 -*- """ Created on Fri Dec 20 11:26:56 2019 @author: szelagp """ from argparse import ArgumentParser from datetime import datetime from Config import disable_utf8 from board import Board from colors import WHITE, BLACK from display import display_board from pieces import StraightMover, King, Knigh...
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import login from django.shortcuts import redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from Aluno.views.utils import aluno_exist from annoying.decorators import render_to from django.contrib...
#!/usr/bin/env python3 #import fire from fire.core import Fire from tensor_tracer import ttracer import sys class TtracerCmd(object): """...""" def start(self, target_file): print(sys.argv) sys.argv = sys.argv[2:] print(sys.argv) ttracer.start(target_file) if __name__ == '__main__': Fire(T...
R=input(float()) L=2*3.14*float(R) S=3.14*float(R)*float(R) print(L) print(S)
import sys, os import numpy as np import spectral from hylite.hyimage import HyImage from .headers import matchHeader, makeDirs, loadHeader, saveHeader # spectral python throws depreciation warnings - ignore these! import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) def loadWithGDAL(path, d...
#-*-coding:utf-8-*- import RPi.GPIO as GPIO import weather as we import finedust as dust import FND import time import threading from multiprocessing import Process def setGPIO(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #----------------------LCD-------------------------- #Define GPIO to LCD mapping LC...
class DATASET_PATH(object): JULY = "../data/sts/csv/2018_08_05/" JUNE = "../data/sts/csv/2018_05_04/" BRT = "../data/shapefiles/brt_lines/brt" class DATASET(object): JUNE = 'june' JULY = 'july' BRT = 'brt' BRT_1 = 'brt1' DATASETS = { DATASET.JUNE : DATA...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 模拟发送串口数据 """ import struct def dec2hl8(dec): s = struct.pack('>h', dec) print dec, '-------------=', repr(s) n = len(s) # print n, n/2 # print s[:n / 2], s[n / 2:] # print hex(ord(s[:n / 2])), hex(ord(s[n / 2:])) return ord(s[:n / 2]), ord(s[n ...
def union_all(graphs, rename=()): ... def disjoint_union_all(graphs): ... def compose_all(graphs): ... def intersection_all(graphs): ...
dollars = float(input('Dollars to convert: ')) yen = dollars * 111.47 yuan = dollars * 6.87 euro = dollars * 0.86 pound = dollars * 0.77 Canada = dollars * 1.31 print("Yen:",yen) print("Yuan:",yuan) print("Euro",euro) print("Pound",pound) print("Canadian dollar",Canada)