text
stringlengths
38
1.54M
import json import sqlite3 class Member(): def __init__(self, name, title, role, course_id=-1, user_id=-1): self.name = name self.title = title self.role = role self._course_id = course_id self._user_id = user_id @property def course_id(self): return self._c...
# 3. Longest Substring Without Repeating Characters # https://leetcode.com/problems/longest-substring-without-repeating-characters/ def lengthOfLongestSubstring(self, s): d = "" f = "" for i in range(len(s)): if s[i] not in f: f += s[i] else: if len(d) < len(f): ...
from django import forms class LaporanForm(forms.Form): tgl_awal = forms.CharField(max_length=20) tgl_akhir = forms.CharField(max_length=20)
class Predication: #Constructor def __init__(self,txt,status,startTime=None,endTime=None): self.status=status self.txt=txt self.startTime=startTime self.endTime=endTime class Segment: #Constructor def __init__(self,txt,startTime=None,endTime=None,words=None)...
# -*- coding: utf-8 -*- """ Telemetry class distributing real-time metrics to external server author: @miro (Meir Tseitlin) 2020 Note: """ import os import queue import time import json import logging import numpy as np from logging import StreamHandler from paho.mqtt.client import Client as MQTTClient logger = logg...
# coding=utf-8 class ResultBean(dict): def __init__(self): # dict.__init__(self) # 继承pyton字典类的方法和属性 super(ResultBean, self).__init__() def data(self, data): self.dict_set("data", data) return self def success(self): self.code(1) return self def succes...
# http://aumhaa.blogspot.com from Codec import Codec def create_instance(c_instance): """ Creates and returns the Codec script """ return Codec(c_instance)
#!/usr/bin/env python # Searches for all vivado_implement direcories present in current working directory # (eg:/processor/Aa_v2/) and runs on vivado, implement.tcl present in them, which # synthesizes the design and generates post synth vhd files and dcp files. # # The script then implements the entire processor mo...
from rest_framework import generics from django.shortcuts import get_object_or_404 from .serializers import RepondASerializer from rest_framework import viewsets from rest_framework.response import Response from api.models import RepondA, Devoir from django_filters import rest_framework as filters from .filters import ...
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from util import * class EmptyLayer(nn.Module): def __init__(self): super(EmptyLayer,self).__init__() class DetectionLayer(nn.Module): def __in...
from flask import (Blueprint,flash,g,redirect,render_template,request,url_for,session) from werkzeug.exceptions import abort from flask.json import jsonify import datetime import pandas as pd import numpy as np import json from OPTICS import myOPTICS,OpticsEncoder bp = Blueprint('ShowOPTICS',__name__) @bp.route('/'...
""" Define constraint plane and origin nodes Inputs: TM: (topological diagram) The topological diagram used for the calculation of the structural model constraintPlane: (plane) The constraint planes constraintPlaneID: (int) The index of the vertices where the constraint planes are applied ...
import random from nose.plugins.skip import SkipTest import time from proboscis import test import unittest from reddwarf.guest import pkg from reddwarf.guest.pkg import PkgAgent GROUP = "nova.guest.pkg" # To prevent a joker from making a package with this name... _r = random.Random() _INVALID_PACKAGE_NAME = "fake_pa...
''' objects used to model the spreading of oil Include the Langmuir process here as well ''' import copy import numpy as np from repoze.lru import lru_cache from colander import SchemaNode, Float, drop from gnome.utilities.serializable import Serializable, Field from gnome.environment import constant_wind, WindSchema...
x = int(input('Digite um numero de 0 a 9999: ')) u = x // 1 % 10 d = x // 10 % 10 c = x // 100 % 10 m = x // 1000 % 10 print('Unidade: {}'.format(u)) print('Dezena: {}'.format(d)) print('Centena: {}'.format(c)) print('Milhar: {}'.format(m))
from protocol_element import ProtocolElement class ProtocolDocumentation(ProtocolElement): def __init__(self, protocol, file_name, xml, **kwargs): ProtocolElement.__init__(self, protocol, 'doc', file_name, xml, required_keys= [ ...
#!/usr/bin/env python """ USAGE: python clipsync.py [-p pidfile] [-f] [-x xsel_path] python clipsync.py -k This should work fine with Python 2 or Python 3. Note that it requires xsel and assumes it can read /proc/. A simple Linux tool for synchronising all X11 clipboards. Any of the following actions should...
import pygame import pygame_classes cars = ['car.png', 'blue_car.png', 'green_car.png', 'orange_car.png', 'yellow_car.png'] chosen_color = 0 def customize_car(): global chosen_color screen_width = pygame.display.Info().current_w screen_height = pygame.display.Info().current_h screen = pygame.display...
import pyautogui from python_imagesearch.imagesearch import imagesearch import time pyautogui.FAILSAFE = False TIMELAPSE = 1 acceptButtonImg = './sample.png' acceptedButtonImg = './sample-accepted.png' championSelectionImg_flash = './flash-icon.png' championSelectionImg_emote = './emote-icon.png' playButtonImg = './p...
# -*- coding=utf-8-*- #每个tuple元素都包含两个元素,for循环又可以进一步简写成index和name rank=range(1,5) L=['Adam','Lisa','Bart','Paul'] for s in zip(rank,L): print s[0],'-',s[1]
""" @package mi.dataset.driver.flort_dj.dcl.driver @file marine-integrations/mi/dataset/driver/flort_dj/dcl/driver.py @author Steve Myerson @brief Driver for the flort_dj_dcl Release notes: Initial Release """ __author__ = 'Steve Myerson' __license__ = 'Apache 2.0' from mi.core.common import BaseEnum from mi.core.e...
from unittest import TestCase from unittest.mock import Mock from unittest.mock import patch from ipykernel.comm import Comm from ipykernel.kernelbase import Kernel from iclientpy.jupyter import MapView, TileMapLayer class TileMapLayerTest(TestCase): @patch.object(Comm, 'send') def test_tile_map_lay...
# -*- coding: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from ..one_drive_object_bas...
#!/usr/bin/env python # # routines.py - A collection of disparate utility functions related to OpenGL. # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # """This module contains a collection of miscellaneous OpenGL and geometric routines. """ from __future__ import division import logging import ...
'Test of pack/unpack functionality' import numpy as np from struct import unpack from random import getrandbits from videocore.assembler import qpu from videocore.driver import Driver @qpu def boilerplate(asm, f, nrows): #mov(rb0, uniform) setup_dma_load(nrows=nrows) start_dma_load(uniform) wait_dma...
from flask import current_app as app import ext.app.eve_helper as eve_helper import json from bson.objectid import ObjectId def before_insert(items): print('Before POST content to database') print(items) # payload = json.loads(response.get_data().decode('UTF-8')) for document in items: # upda...
# Only for the KEMRI study. This whole file is dropped for generic study apps STUDY_APPS = ('Captopril Study',) # CommCare case type of OpenClinica study subjects CC_SUBJECT_CASE_TYPE = 'subject' # Names of case properties used in report CC_SUBJECT_KEY = 'screening_number' CC_STUDY_SUBJECT_ID = 'subject_number' CC_EN...
def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" def chips_and_dip(bags_of_chips, containers_of_dip): print "You have %d ba...
import tensorflow as tf import scipy.io import numpy as np import matplotlib.pyplot as plt from PIL import Image from skimage import io from skimage import data, exposure, img_as_float import os input_nodes = 8 * 8 hidden_size = 100 output_nodes = 8 * 8 os.environ["CUDA_VISIBLE_DEVICES"] = "0" # def sampleImage(fil...
# definicion/urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('crear_proyecto/', views.CrearProyecto.as_view(), name='crear_proyecto'), path('proyectos/', views.Proyectos.as_view(), name='proyectos'), ]
p= float(input('Digite seu peso: ')) h= float(input('Digite sua altura: ')) imc= p/(h*h) print(f'O IMC dessa pessoa é de {imc:.1f}') if imc <18.5: print('Você está abaixo do peso ideal') elif imc <25: print('VocÊ está no peso ideal') elif imc <30: print('Você está acima do peso ideal, ou seja, está com so...
from slyguy import userdata, util from slyguy.session import Session from slyguy.exceptions import Error from slyguy.mem_cache import cached from .language import _ from .constants import API_URL, HEADERS, UUID, APPID, LOCALE, BRIGHTCOVE_URL, BRIGHTCOVE_ACCOUNT, BRIGHTCOVE_KEY class APIError(Error): pass class A...
""" 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 14:45:30 2019 @author: Libra """ import shlex import subprocess import os # import time def run(command): try: result = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT) return 0, result except subprocess.CalledProcessE...
#!/usr/bin/env python import sys import pkgconfig from Cython.Build import cythonize from setuptools import setup, find_packages, Extension # See https://pypi.python.org/pypi?%3Aaction=list_classifiers cyvips_classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intend...
import xml.etree.cElementTree as et #ElementTree表示元素数 tree = et.parse('movies.xml')#把文件movies.xml传进来,python会自动 # 封装成一棵树,此处赋给tree, root = tree.getroot()#获取树的根节点 print(root.get('shelf'))#get是获取节点的内容(此时表示的是属性) for movie in root.findall('movie'): title = movie.get('title') print(title) type = movie.find('t...
''' Write a method to print the last K lines of an input file using C++. Hints: 449, 459 ''' def lastKlines(s): pass if __name__ == '__main__': assert lastKlines('') == assert lastKlines('') == assert lastKlines('') == assert lastKlines('') == assert lastKlines('') ==
import scrapy import urllib2 from bs4 import BeautifulSoup from wogmascrap.items import WogmascrapItem def getReview(path): try: response=urllib2.urlopen(path) Doc=response.read() soup = BeautifulSoup(''.join(Doc)) value=soup.findAll("div",{"class":"review large-first-letter"})[0].g...
import math import numpy as np from sklearn.linear_model import Ridge, Lasso from sklearn.preprocessing import StandardScaler from sklearn.base import BaseEstimator class HybridRegressionTree(BaseEstimator): def __init__(self, min_node_size=10, mode='Ridge', min_split_improvement=0): self.min_node_size = ...
import socket dest_ip = "127.0.0.1" dest_port = 50000 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((dest_ip,dest_port)) while True: message = input("Please enter your message: ") if(len(message)==0): break message = message.encode('utf-8') client.send(message) ...
# -*- coding: utf-8 -*- # @Time : 2018/5/21 17:05 # @Author : Inkky # @Email : yingyang_chen@163.com ''' PAA DRAW FIG ''' from tslearn.generators import random_walks from tslearn.preprocessing import TimeSeriesScalerMeanVariance from tslearn.piecewise import PiecewiseAggregateApproximation import numpy ...
import nltk from nltk.stem.snowball import SnowballStemmer import os,glob import re import string import json #Cleaning iniziale da dare in pasto al PreEmbedder class TextPreparation: tag = set() unique_words = set() vocab_size = 0 word2int = {} int2word = {} stopWords = {} #no white-s...
import os print ("Bienvenido\n") print ("1.Imprimir numeros de telefono") print ("2.Agregar numeros de telefono") print ("3.Quitar numeros de telefono") print ("4.Buscar numeros de telefono") print ("5.Salir") directorio = {} nombres = directorio.keys() numeros = directorio.values() elementos = directorio.items() var...
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import AppointmentModel from .forms import AppointmentCreateForm, ConfirmAppointment from django.http import HttpResponse from User.models import UserModel, DoctorTypeModel, DoctorModel from django.core....
# This file is part of Checkbox. # # Copyright 2012, 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki <zygmunt.krynicki@canonical.com> # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundati...
from selenium import webdriver import time import math def calc(x): return str(math.log(abs(12*math.sin(int(x))))) try: link = "http://suninjuly.github.io/alert_accept.html" browser = webdriver.Chrome() browser.get(link) button1 = browser.find_element_by_tag_name("button") button1.click() time.sleep(2) con...
# -*- coding: utf-8 -*- filename = '193_programming.txt' with open (filename, 'a') as file_object: # w означает что файл должен быть открыт в режиме записи file_object.write('I live programming.\n') file_object.write('I live programming and ruby\n') file_object.write('I live \n') #r для чтения,(по умолчанию...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, LoginManager import os, sys from app.config import Config app=Flask(__name__) from app import routes WIN=sys.platform.startswith('win') if WIN: prefix='sqlite:///' else: prefix='sqlite:////' ...
### mortgage graph ''' x3 = np.arange(0.0, 50.0, 1.0) y3 = [profitcalc.mortgage_calc(profitcalc.start_amnt, )] '''
import libadalang as lal def format_object_decl(decl): return "<AnonymousExprDecl {} = {}>".format( decl.p_type_expression.text, decl.f_expr.text ) ctx = lal.AnalysisContext() u = ctx.get_from_file("test.adb") for call in u.root.findall(lal.DottedName): called = call.p_referenced_decl()...
def new_password(oldpassword,newpassword): for cijfers in newpassword: if cijfers in '0123456789': cijfergevonden = True else: cijfergevonden = False if newpassword != oldpassword and len(newpassword) >= 6 and cijfergevonden: return ('Je wachtwoord is gewijzigd') ...
import math for z in range(int(input())): s1,s2=map(int,input().split()) s2=abs(s1-s2) s1=abs(s1) d=s1*s2 a=math.gcd(s1,s2) a=a*a print(d//a)
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from ..models.students import Student from ..models.groups import Group from dateti...
from sklearn.model_selection import GroupKFold from sklearn.model_selection import KFold from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.model_selection import ShuffleSplit seed = 0 def split(tipo="KFold", n_splits=5 ,random_state=seed, n_repeats=10 ,shuffle=True, test_size=None, train_size=No...
import h5py import numpy as np from matplotlib import pyplot as plt import fastmri from fastmri.data import transforms as T from fastmri.data.subsample import RandomMaskFunc from fastmri.data.subsample import EquispacedMaskFunc from scipy.ndimage import gaussian_filter from scipy.ndimage import sobel from PIL import Im...
from Question import Question questions_answers = [ 'What is the capital of Italy \n (a) Rome \n (b) Milan \n (c) Florence \n', 'What shape is a footbal? \n (a) Square \n (b) Round \n (c) Rectangle \n', 'What colour are apples? \n (a) Yellow \n (b) Red \n (c) Black \n' ] questions = [ Question(questions_answ...
#!/usr/bin/python # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 import argparse, sys parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-18") parser.add_argument("--input", default="input.txt") args = parser.parse_args() def draw_row(row): for space in row: ...
import django_tables2 as tables from agagd_core.models import Games class GameTable(tables.Table): pin_player_1 = tables.LinkColumn( 'agagd_core.views.member_detail', kwargs={"member_id":tables.A('pin_player_1.member_id')}) pin_player_2 = tables.LinkColumn( 'agagd_core.view...
import json import os Session = {} if os.path.exists("session.json"): print("Found session file.") with open('session.json') as json_file: Session = json.load(json_file) else: print("Session file not found. Creating new one at " + os.path.abspath("session.json")) f = open("session.json", "w") ...
import os import sys script_path = os.path.dirname(__file__) parent_path = os.path.dirname(os.path.dirname(__file__)) data_path = os.path.join(parent_path, 'data/clean/loads') default_path = os.path.join(parent_path, 'data/default/') output_path = os.path.join(parent_path, 'data/switch_inputs/')
from patient.models import Patient from rest_framework import generics from rest_framework.response import Response from patient.serializers import PatientSerializer class PatientList(generics.ListCreateAPIView): queryset = Patient.objects.all() serializer_class = PatientSerializer class PatientDetail(ge...
n, m = input().split(' ') m = int(m) n = int(n) INF = float('INF') matric = [] for i in range(n): s = input().split(' ') tmp =[] for j in s: tmp.append(int(j)) matric.append(tmp) # print(matric) note ={} def dfs(i, j, dir): #通过向哪个方向到达当前位置的 if (i, j, dir) in note: return not...
class StringManipulation: def compare(self, str): local_str = "Hello" if local_str == str: print("matched") else: print("Not matched") def manipulate(self, str): length_str = len(str) print("Length of a string ", length_str) count_of_i =...
from __future__ import print_function import os from skimage.transform import resize from skimage.io import imsave import numpy as np np.random.seed(1234) import tensorflow as tf tf.set_random_seed(1234) from tensorflow import keras import tensorflow.keras.utils from tensorflow.keras.models import Model from tens...
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import multiprocessing,threading import socket import os from multiprocessing import Queue from msgutils import recv_msg, send_msg import time, datetime, sys q1=Queue() lock=threading.Lock() lock1=threading.Lock() adress=('127.0.0.1',33653) q = Q...
#!/usr/bin/env python3 """ Re-create the cells starting with the paired files Take six mandatory arguments, the two files of sequences, the three files containing pairs ab, aa and bb and the output file Modify the list of sequences to add columns containing their paired alphas/betas, the number of clon...
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.dummy_operator import DummyOperator from datetime import datetime, timedelta default_args = { 'owner': 'AirFlow', 'start_date': datetime(2015, 6, ...
import os, sys import time import numpy as np import inspect, struct from tqdm import tqdm import sigpyproc.HeaderParams as conf from sigpyproc.Utils import File from sigpyproc.Header import Header from sigpyproc.Filterbank import Filterbank, FilterbankBlock from sigpyproc.TimeSeries import TimeSeries from sigpyproc.F...
import hashlib import re import time import urllib2 from datetime import datetime from selenium import webdriver TIME_SLEEP = 1 # Second TIME_IMPLICIT_WAIT_LONG = 10 # Second TIME_IMPLICIT_WAIT_SHORT = 0.5 # Second BUFFER_SIZE = 8192 # byte ITEMS_PER_PAGE = 20 class FileDownloader: """ Manage download jobs ...
import sys sys.path.append('./dataCollection') from screenScrape import Scraper def gatherHostelData(url): scrpr = Scraper(url) hostelsData = [] hostels = scrpr.search('div', klass='fabresult') for h in hostels: hData = {} # Find images images = scrpr.search('div', klass='fabresult-image', portion='data-ima...
import json import responses from nio.signal.base import Signal from nio.testing.block_test_case import NIOBlockTestCase from ..intercom_tag_users_block import IntercomTagUsers class TestIntercomTagUsers(NIOBlockTestCase): @responses.activate def test_tag_user_post_request(self): blk = IntercomTagU...
"""Example of use of the AvoidChanges as an objective to minimize modifications of a sequence.""" from dnachisel import ( DnaOptimizationProblem, CircularDnaOptimizationProblem, random_dna_sequence, AvoidChanges, AvoidPattern, EnforcePatternOccurence, sequences_differences, EnforceGCCon...
class main(object): def __init__(self): def get_num(): while True: try: num = int(input("how many fibonnacis? ")) return num except: print('put in a number, wise guy') fib(get_num()) ...
import math class Solution: def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ # Initialize the number of ways for all amounts from 1-amount to inf min_ways = [math.inf] * (amount+1) # Base c...
# # # Program: makeGOAnnot.py # # Original Author: Lori Corbani # # Purpose: # # Create GO annotation files for the following areas: # # GO/EC J:72245 # GO/InterPro J:72247 # GO/UniProt J:60000 # # Usage: # # makeGOAnnot.py # # Env Vars: # # The following environment variables are set by the configurat...
""" script for computing the fid of a trained model when compared with the dataset images """ import argparse import tempfile from pathlib import Path import imageio as imageio import torch from cleanfid import fid from torch.backends import cudnn from tqdm import tqdm from pro_gan_pytorch.networks import create_gene...
"""Top-level package for Scikit-Learn Wrapper for Keras.""" __author__ = """Adrian Garcia Badaracco""" __version__ = "0.2.0" # Monkey patch log_cosh reference # See https://github.com/tensorflow/tensorflow/pull/42097 # Will be removed whenever the # min supported version of tf incorporates the fix from tensorflow.py...
import numpy as np import matplotlib.pyplot as plt from scripts.hmf.larger_sim import hmf_analysis as ha from mlhalos import parameters from mlhalos import distinct_colours import sys if __name__ == "__main__": kernel = sys.argv[1] volume = sys.argv[2] pred_spherical_rescaled = sys.argv[3] colors = di...
import imageio import glob import sys import os from tqdm import tqdm def generate_gif(source, dest=None, filename=None, duration=0.005): print(source, dest, filename) if not dest: dest = source if not filename: filename = 'gif' images = [] files = sorted( glob.glob("{}*.png".format(source)) ) ...
import time from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from seleniumDemo import object_store class Doclever(object): def __init__(self, p_driver): self.driver = p_driver #登陆docle...
import sys #import argparse id_string=[] name=[] surname=[] age_string=[] for i in range (0,int(sys.argv[1])): idn, n, s, a = input("ID Name Surname Age\n").split() id_string.append(idn) name.append(n) surname.append(s) age_string.append(a) id_no=[int(j) for j in id_string] age=[int(j) f...
"""클러스터 모듈.""" import os from os.path import expanduser import re import json import datetime import warnings import time import webbrowser import tempfile from urllib.request import urlopen from urllib.error import URLError import botocore import boto3 import paramiko from bilbo.profile import read_profile, DaskProf...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib.util import itertools import json from os import path as osp from typing import Any, Dict import ...
# encoding='utf-8' # _*_ coding:utf-8 _*_ from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from pymongo import MongoClient from django.conf import settings from django.views.decorators.csrf import csrf_exempt, csrf_protect # Add this from bson.objectid import Obj...
v = 0 i = 1 while i < 11: v = v + 1 print(i, "を足すと", v) i += i print("1から10を足すと...", v)
from django.contrib import admin from post.models import Post, Comment, Report admin.site.register(Post) admin.site.register(Comment) admin.site.register(Report)
# time_unit = 1us import numpy as np import matplotlib.pyplot as plt # plot the effect of cold start time and cold start ratio def cold_start_effect(): exec_time = 100 warm_start = 1 index = np.arange(1, 5, 0.1) cold_start = 10 ** index cold_start_ratios = np.arange(0.2, 1, 0.2) for cold_star...
import logging import asyncio from urllib.parse import urlparse from models import Event, Match, MatchScore, Ranking from helpers import YouTubeVideoHelper from db.orm import orm class MatchHelper: class MatchRender: def __init__(self, match: Match, scores, event: Event): self.year = event.year...
from django.core.management.base import BaseCommand from pylint.lint import Run # from pylama.main import check_path, parse_options ERROR_COUNT = 5 CONVENTION_COUNT = 5 WARNINGS = 5 CODEBASE = './src/' THRESHOLD_LINT_SCORE = 9.5 class Command(BaseCommand): def run_pylint(self, path): results = Run(['-...
# Adams-Bashforth-Moulton法による数値解導出(Scipyのodeintを使用) # うまく収束しないので使えないかも? import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt import math def func(X, a=0.4, b=0.5, c=1, r0=0.5, g0=0.8, P=1, k=50, G=0.005, K1=100, K2=100): return [X[0] * (r0 * (1 - X[0] / K1 - c * X[2]) - a * P * (...
from Ball import Ball from tkinter import * class BounceBalls: def __init__(self): self.ballList = [] # create a list to store balls window = Tk() # create a window window.title("Bouncing Balls") # set a title self.width = 350 # width of canvas self.height = 150...
#!/usr/bin/env python3 ######## #Yang Lei, Jet Propulsion Laboratory #November 2017 import xml.etree.ElementTree as ET from numpy import * import scipy.io as sio ##import commands import subprocess import os import time import argparse import pdb import os import isce import shelve import string import sys from osgeo...
number_of_breads = float(input("Enter the number of breads you want to buy: ")) discount = 60 price = 3.49 answer = number_of_breads * price * ((100 - discount) / 100) print("\nThe regular price is -- $ " + "{0:.2f}".format(int(number_of_breads * price))) print("The discount is -- " + str(discount) + " %") print("Th...
from django.shortcuts import render from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseServerError from django.views.decorators.csrf import csrf_exempt from django.db import connection import json import string import random from datetime import date import log...
import numpy as np import scipy.linalg as sla import scipy.optimize as sop from utils import Arguments, eig_thr import matplotlib.pyplot as plt class BeAgent(): def __init__(self, args): self.args = args self.lmax = args.lmax def _make_eargs(self, A, y): args = self.args ei...
import numpy as np from numpy.linalg import eigvalsh, eigh import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.colors from matplotlib.colors import Normalize import os class Plot: def __init__(self, Hamiltonian): self.Hamiltonian = Hamiltonian def Plot_Fermi_surf...
from rest_framework import serializers from .models import Playlist class PlaylistSerializer(serializers.ModelSerializer): class Meta: model = Playlist fields = ('inner', 'real_id', 'channel_id', 'name', 'channel_title', 'description', 'thumbnails')
from __future__ import print_function import pickle import numpy import theano numpy.random.seed(42) def prepare_data(seqs, labels): """Create the matrices from the datasets. This pad each sequence to the same lenght: the lenght of the longuest sequence or maxlen. if maxlen is set, we will cut all ...
from django.db import models from django.contrib import admin from django.template.loader import render_to_string # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='dataset/selfie2anime/testA/') name= models.CharField(max_length=30) def __unicode__(self...
#example pertaining to scoping of function def f(): print(x) def g(): print (x) x=1 x=3 f() x=3 g()