text
stringlengths
8
6.05M
from PyQt5.QtCore import * from dao.nutzer_dao import NutzerDao from dao.kassen_dao import KassenDao from dao.historie_dao import HistorieDao import os import numpy as np from time import gmtime, strftime import logging class HistorieController(QObject): def __init__(self, nutzermodel, nk_model, historiemodel): ...
from ..FeatureExtractor import FeatureExtractor class pair_slope_trend_extractor(FeatureExtractor): """percentage of pairs of points which continually rise, over total number number of pairs. We only want to run this on the last MAX_PAIRS points to see if there is an overall trend to the rise/fall. To acco...
"""Tests for treadmill.rest.*""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os.path import tempfile import unittest from unittest import mock from treadmill import rest # W0212: Access to a protected me...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from typing import Iterable import pytest from internal_plugins.test_lockfile_fixtures.lockfile_fixture import ( JVMLockfileFixture, JVMLockfi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' get_nvl_position_list_query = """ SELECT hmup.id AS id, hmup.user_id AS user_id, hmup.traceable_object_id AS traceable_object_id, hmup.hw_modu...
import os from configparser import ConfigParser, NoSectionError, NoOptionError from elasticsearch import Elasticsearch, ConnectionError, ElasticsearchException class ES: def __init__(self): self.path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.__get_config() try: ...
a = input ("Digite o nome do cliente:") b = input ("Digite o dia de vencimento:") c = input ("Digite o mês de vencimento:") d = input ("Digite o valor da fatura:") print("Olá,", a) print("A sua fatura com vencimento em", b, "de", c, "no valor de R$", d, "está fechada.")
from django.contrib.auth.tokens import default_token_generator from templated_mail.mail import BaseEmailMessage from rest_framework.views import APIView from authentication.conf import settings from django.core.mail import send_mail from api.models import CompanyStuff from django.template import Context from django.tem...
import csv import os from typing import Any, Callable, List, Optional, Tuple from PIL import Image from .utils import download_and_extract_archive from .vision import VisionDataset class Kitti(VisionDataset): """`KITTI <http://www.cvlibs.net/datasets/kitti/eval_object.php?obj_benchmark>`_ Dataset. It corre...
import prefpy import io import math from .preference import Preference from .profile import Profile ''' if __name__ == "__main__": #profile is not defined? p = Profile() # need to make filename first #the designed file name is pretty confusing based on the read_election_file function # Preflib Election Da...
T1=(1,2) T2 = (3,4) print(T1) T3 = T1+T2 print(T3) # Concatenation print(T2*4) # Repetition print(T3[0]) # Indexing print(T3[1:3]) # Slicing
from django.db import models from products.models import Products class Categories(models.Model): title = models.CharField(max_length=50, blank=True) sub_categories = models.ForeignKey('self', blank=True, null=True) def __unicode__(self): return self.title class ProductToCategories(models.Model...
#This code simulates the airline luggage problem #Running in O(n^2) string='1,2,3,4,5,6,7,8' def airline_luggage(string): weights = string.split(',') length=len(weights) container_size=3 if(length%(container_size)==0): num_containers=(length)/(container_size) else: ...
# extended from https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino import time import threading import board import busio import sys i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1015(i2c) chan = AnalogIn(a...
# Generated by Django 3.0.4 on 2020-04-25 08:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('apps', '0021_auto_20200425_1121'), ] operations = [ migrations.AddField( model_name='vacancy', name='visible', ...
# Create a Book class, that has an author, a title and a release year # Create a constructor for setting those values # Book should be represented as string in this format: # Douglas Adams : The Hitchhiker's Guide to the Galaxy (1979) # Create a BookShelf class that has a list of books in it # We should be able to add ...
# -*- coding:utf-8 -*- """ @author:cuibo @file:sample.py @time:2018/4/2015:00 """ " 表达式" a= 10; b= 20; print(a and b) "数据结构" print("------数据结构") list1 = ['abc','lkl',1991,2002]; list2 = [1,2,3,4,5,6,7,8]; print('list1[0]: ',list1[0]) print('list1[1:5]: ',list1[1:3]) list1 = ('abc','lkl',1991,2002); list2 = (1,2,3,4,...
import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Twist import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader import time import matplotlib.pyplot as plt from numpy.linalg import inv import math import torch from torch.utils.data import TensorDataset, DataLoad...
# Hello Variable World ## Instructions country = "Mali" name = "Jayahama" age = 29 hourly_wage = 20.50 satisfied = False daily_wage = hourly_wage * 8 print(name + " " + country + " " + str(age) + " " + str(hourly_wage)) print(f"name country daily_wage satisfied") ## **Hint**
from battle.battleeffect.EffectType import EffectType from battle.battleeffect.BattleEffect import BattleEffect from battle.targetselection.SingleAllyTargetSelection import SingleAllyTargetSelection import random class HealSpell(BattleEffect): def __init__(self, source_fighter): super().__init__(source_fi...
#!/usr/bin/env python #======================================================================================= # formationEnergiesFit.py # Takes formation energies from the file 'formationEnergies.dat' and fits them with # polynomials in two steps: # - fits formation energies = f(He/V) for each vacancy number with...
#!/usr/bin/python import numpy as np import pylab as py from scipy import integrate from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv,kpc,mchirpfun,fmaxlso #I will produce a plot of h as a function of z for a given physical chirp mass and a given frequency (that will show the amplification). #On t...
import random import math print("Digite o valor A: ") a= int(input()) b= math.floor(random.uniform(2,20)) flag= True if a%b==0 : print(str(flag)) else: flag= False print(flag) print(str(b))
from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def announce_new_user(sender, instance, created, **kwargs): if crea...
# Generated by Django 3.1.7 on 2021-03-07 06:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0017_auto_20210307_0405'), ] operations = [ migrations.AlterField( model_name='enrolled', name='tag', ...
import h5py import pylab as pl f=h5py.File('logs/data.h5') x = f['x'][:] y = f['y'][:] X = f['X'][:] f.close() F = pl.figure(figsize=(5,5)) f = F.add_subplot(111) f.scatter(x,y,c=X,s=3) pl.show()
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, portrait from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.lib.units import cm import openpyxl import pathlib import datetime from PIL import Image def load_informatiom()...
# Generated by Django 3.1.3 on 2021-01-07 17:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reddituser', '0001_initial'), ] operations = [ migrations.AlterField( model_name='reddituser', name='bio', ...
[print(i) for i in range(10) if i % 2 == 0]
from flask_wtf import FlaskForm from wtforms import StringField, validators, SelectField, FormField, FieldList, IntegerField, PasswordField, BooleanField from werkzeug.datastructures import MultiDict # some web forms and what not class LoginForm(FlaskForm): email = StringField('Email', [validators.Email(message = 'P...
# -*- coding: utf-8 -*- #: #: Author: redkern #: Date: 26/12/2016 #: Version: 0.1 #: License: MIT #: """Data convertion module.""" def bytes_sanitizer(data): """Ensure that data is from types bytes.""" if isinstance(data, str): return data.encode("utf-8") else: return data def str_to_b...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import re from pants.testutil.pants_integration_test import ensure_daemon, run_pants from pants.util.contextutil import overwrite_file_content from pants.util.dirutil import read_file @...
# 机试题 # 1.lis = [['哇',['how',{'good':['am',100,'99']},'太白金星'],'I']] (2分) # # o列表lis中的'am'变成大写。(1分) # # o列表中的100通过数字相加在转换成字符串的方式变成'10010'。(1分) # lis = [['哇',['how',{'good':['am',100,'99']},'太白金星'],'I']] # print(len(lis)) # print(len(lis[0])) # print(len(lis[0][1])) # print(len(lis[0][1][1])) # print(lis[0][1][1]['good']...
import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from coffeebot import config from coffeebot.models import Base database_uri = config.DATABASE_URI print(datetime.datetime.now()) print("Creating database...") engine = create_engine(database_uri) Base.metadata.create_all(e...
a,b=map(int,input().split()) m=max(a,b) l=[] for i in range(1,m+1): if(a%i==0 and b%i==0): l.append(i) print(max(l))
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2019-01-26 21:10 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migration...
from os.path import dirname, join, abspath from pyrep import PyRep from pyrep.objects.shape import Shape from pyrep.objects.vision_sensor import VisionSensor import numpy as np import time import math from occupancyGrid import OccupancyGrid class Pose: def __init__(self, x, y, theta): self.x = x self.y = y ...
import warnings #GetAptUrls() Supresses warning warnings.filterwarnings('ignore') #GetAptUrls() Supresses warning from bs4 import BeautifulSoup #GetAptUrls() GetAptInfo(AptUrls) import requests #GetAptUrls() import re #GetAptInfo(AptUrls) MakeRentInt(df) import pandas as pd #Everything import time #MakeCurrentTimeStrin...
#Multiple of 3 or 5 def multiple(n): if (n==0 and n<0): return -1 sum_mul=0; for i in range(1,n): if(i%3==0 or i%5==0): sum_mul=sum_mul+i; return sum_mul output=multiple(1000) if(output==-1): print "Enter a valid input!!" else: print "The sum of multi...
# Generated by Django 3.2.3 on 2021-05-17 17:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('interact', '0001_initial'), ] operations = [ migrations.RenameField( model_name='likeunlikefilm', old_name='trueOrNot', ...
from matplotlib import pyplot as plt import vectorEntrenamiento as vE from MLP import matplotlib class Grafica(object): def __init__(self, figure): self.seguirDibujando = True self.estaProbando = False self.verctorEntradas = [] self.vectoresEntrenamiento = [] self.vectorPrueba = [] self.figure ...
from sklearn.feature_extraction.text import TfidfVectorizer # list of text documents #text = ["The The The The The quick brown fox jumped over the lazy dog.", # "The dog.", # "The fox"] text=["the house had a tiny little mouse", "the cat saw the mouse", "the mouse ran away from the house", "...
import pygame import time import random pygame.init() white = (255, 255, 255) black = (0, 0 , 0) red = (255, 0, 0) green = (0, 155, 0) display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("snake game") clock = pygame.time.Clock() f...
cipher = 'tMlsioaplnKlflgiruKanliae' \ 'beLlkslikkpnerikTasatamkD' \ 'psdakeraBeIdaegptnuaKtmte' \ 'orpuTaTtbtsesOHXxonibmkse' \ 'kaaoaKtrssegnveinRedlkkkr' \ 'oeekVtkekymmlooLnanoKtlst' \ 'oepHrpeutdynfSneloietbol' length = len(cipher) mid = length // 2 cipher = li...
import math import sympy def cifras(v, c): return round(v, c - int(math.floor(math.log10(abs(v)))) - 1) def aprox(v, a, n): x = sympy.Symbol('x') ex = x**(1/2) r = ex.evalf(subs={x: a}) for i in range(1, n + 1): ex = sympy.diff(ex) r = r + ((ex.evalf(subs={x: a})/math.factorial(i))*(v - a)**i) re...
""" Espresso ~~~~~~~~~~~~~~~~~~~ Ratchet Robotics's custom Slack bot Written from scratch, too! :copyright: (c) 2015 by Liam Marshall :license: BSD, see LICENSE for more details. """
import uuid from tests.graph_case import GraphTestCase from office365.directory.group import Group from office365.directory.group_profile import GroupProfile class TestGraphTeam(GraphTestCase): """Tests for teams""" target_group = None # type: Group @classmethod def setUpClass(cls): super...
# Faça um Programa que peça dois números e imprima a soma. # entrada de dados numero_1 = int(input('Digite um número: ')) numero_2 = int(input('Digite mais um número: ')) # processamento soma = numero_1 + numero_2 mensagem = '{} + {} = {}'.format(numero_1, numero_2, soma) # saída de dados print(mensagem)
lower=int(input('lower:')) upper=int(input('upper:')) for num in range(lower,upper+1): if num>0: s=0 for i in range(1,num): if num%i==0: s+=i if s==num: print(num,end=' ')
class Point: WIDTH =5 # __slots__ = ["__x", "__y", "W"] def __init__(self, x=0, y=0): self.__x = x self.__y = y def __checkValue(x): if isinstance(x, int) or isinstance(x, float): return True return False def setCoords(self, x, y): if Point.__...
# 6042 a = input() b = round(float(a), 2) print(b) # 6043 a, b = input().split() c = float(a)/float(b) print(format(c, '.3f')) # 6044 a, b = input().split() print(int(a)+int(b)) print(int(a)-int(b)) print(int(a)*int(b)) print(int(a)//int(b)) print(int(a) % int(b)) print(format(int(a)/int(b), '.2f')) # 6045 a, b, c =...
from django.shortcuts import render, redirect from . import forms from django.contrib.auth.models import User from django.contrib import auth from .models import ArrobaModel from django.shortcuts import get_object_or_404 from . import twitter_api from . import twitter_database import pandas as pd import json import uni...
from django.shortcuts import get_object_or_404 from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.viewsets import ModelViewSet from titles.models import Title from .models import Review from .permissions import IsOwnerAdminModeratorToEdit from .serializers import CommentSerializer, Re...
import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions sum_all = tf.math.reduce_sum from VariationalPosterior import VariationalPosterior class BayesianLSTMCell_Untied(tf.keras.Model): def __init__(self, num_units, training, init, prior, **kwargs): super(BayesianLSTMCell_Untie...
# -*- coding: utf-8 -*- import logging import psycopg2 import sys import smtplib from email.mime.text import MIMEText if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) if len(sys.argv) <= 4: logging.warn('argumentos insuficientes') logging.warn('usuariodb clavedb dni usuar...
import random from past.builtins import range import numpy as np from GeneticAlgorithm.Fixed import Fixed from GeneticAlgorithm.Population import Population from GeneticAlgorithm.Tournament import Tournament from GeneticAlgorithm.CycleCrossover import CycleCrossover from GeneticAlgorithm.Candidate import Candidate rand...
import requests from urllib.parse import urljoin class seller: def __init__(self, url_prefix): self.url_prefix = urljoin(url_prefix, "goods/") def addGoods(self, goodsId, goodsName, goodsauth, goodsPrice, goodsNum, goodsType, goodsDsr,sellerName) -> bool: json = {"goodsId": goodsId,"goodsName"...
import scipy from numpy import * import scipy.integrate from fractions import Fraction #variable declarations a = array([1,1,0]) b = array([2,2,0]) def C1(x): return 1 path1_1, err1 = scipy.integrate.quad(C1, 1, 2) # calculating part1 of path1 def C2(y): return 4*(y+1) path1_2, err2 = scipy.integrate.quad(...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ############################################################################################# # # # plot_sim_position.py: create sim positional trend plot...
from marshmallow import Schema, fields, EXCLUDE, post_load from summary.model import Commodity, CostSnapshot, StockSummary, Station, DockSummary class BaseSchema(Schema): class Meta: unknown = EXCLUDE class CostSnapshotSchema(BaseSchema): system_name = fields.String(required=True) station_name ...
''' This one line outlines the module content Here we see the detailed Discription of the Module: Make clear how to comment and structure your code so that other can read and use it. Have a look at the content of https://github.com/alnkpa/pycc/wiki/Coding-style ''' # import in the beginning import sys class OurClass...
import time import requests from keys import BOT_CHATID, BOT_TOKEN def send_telegram_message(bot_message): vacio = {} if bot_message != vacio: send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + \ '/sendMessage?chat_id=' + BOT_CHATID + \ '&parse_mode=Markdown&text=' + bot...
# # Arquitetura e Redes de Comunicação de Sistemas Embarcados # # Projeto I – Transporte confiável de dados utilizando protocolo de bit alternante # # sender.py (script para envio dos dados) # receiver.py (script para envio dos dados) # # Instrucoes para uso disponiveis no arquivo README.md # # MATHEUS ARCANGELO ESPERA...
from keras.models import Model, Input from keras.models import Sequential from keras.layers import GRU from keras.layers import Dense from keras.layers import Concatenate from keras import optimizers from keras_layer_normalization import LayerNormalization #general def GRU_model(x_length, n_features, n_aux, n_classes,...
keywords = [ "Word", "Excel", "PowerPoint", "Power Point", "Outlook", "Afrikaans", "Albanian", "Arabic", "Armenian", "Basque", "Bengali", "Bulgarian", "Catalan", "Cambodian", "Chinese", "Croatian", "Czech", "Danish", "Dutch", "English", ...
import json path = "./testData.json" #xValues = range(1,46,1) xValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45] yValues = [66, 56, 70, 72, 67, 68, 70, 71, 74, 69, ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-27 08:30 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depen...
from server.response.code import *
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """ Demo script showing detections in sample i...
""" ================================================ Dataset ================================================ """ import numpy as np import pandas as pd class Dataset: def __init__(self): self.dataset = None self.target = None self.column_stats = {} self.corr_threshold = 0.80 ...
from sqlalchemy import Column, String, Float, DateTime from .base import Base class BaseCollegeBase(Base): __tablename__ = 'base_college_base'.lower() inst_id = Column('inst_id', Float, primary_key=True, index=True) # UNITID inst_nm = Column('inst_nm', String(120)) # INSTNM inst_alias = Column('in...
import requests from PIL import Image from io import StringIO from tesserocr import PyTessBaseAPI import urllib # column = Image.open('chin-emo.png') # gray = column.convert('L') # blackwhite = gray.point(lambda x: 0 if x < 200 else 255, '1') # blackwhite.save("chin-emo_bw.jpg") def process_image(url): _get_i...
#!/usr/bin/env python # Jim Blaney # Hood College # 2 May 2014 # CS 319 - Algorithm Analysis # Problem: You are given an array, A, of real numbers. Find the set, T, # of contiguous numbers in A that provide the maximum sum. The # set T must contain at least one number. import os; # find the positi...
# Create your views here. ''' Uma view é um “tipo” de página Web em sua aplicação Django que em geral serve a uma função específica e tem um template específico. Por exemplo, => em uma aplicação de blog, você deve ter as seguintes views: -Página inicial do blog - exibe os artigos mais recentes. -Página de ...
#Guímel Madrigal Uecker #B54060 import numpy as np from scipy import stats from scipy import signal from scipy import integrate import matplotlib.pyplot as plt #Lectura de los datos: bits = [] f = open("bits10k.csv") for line in f: bits.append(int(line)) f.close() #Parte1--------------------------------------...
# -*- coding: utf-8 -*- from collections import deque from typing import List class Solution: def calPoints(self, ops: List[str]) -> int: stack = deque() for op in ops: if op == "+": p2 = stack.pop() p1 = stack.pop() stack.append(p1) ...
from django.views.generic import ListView from django.views.generic.edit import FormView, UpdateView from django.shortcuts import HttpResponseRedirect, get_object_or_404 from django.core.urlresolvers import reverse from guardian.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required ...
# Generated by Django 3.2.4 on 2021-07-15 05:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('database', '0012_statement_unique_statement'), ] operations = [ migrations.RenameField( model_name='statement', old_name='st...
number_rooms = int(input()) free_chairs = 0 is_game_on = True for room in range(1, number_rooms + 1): chairs_and_people = input().split() people = int(chairs_and_people[-1]) # chairs = len(chairs_and_people[0]) chairs = chairs_and_people[0].count("X") if people > chairs: is_game_on = False...
from django.contrib import admin from .models import * from django.forms import Textarea class CommentAdmin (admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Textarea( attrs={ 'rows': 3, 'cols': 50, 'style': 'height: 3.5em;...
import os import random import cv2 import ffmpeg from sqlalchemy import ForeignKey from family_foto.config import BaseConfig from family_foto.models import db from family_foto.models.file import File from family_foto.utils.image import resize class Video(File): """ Class of the video entity. """ id ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import fractions a = fractions.Fraction(1, 3) b = fractions.Fraction(4, 6) print(a) print(b) print(a + b) print(a - b) c = fractions.Fraction('0.25') print(c) # float类型转fraction类型 d = 2.55 e = fractions.Fraction(*d.as_integer_ratio()) print('2.55.as_integer_ratio()后:\n\t'...
from django.contrib.auth.models import User from rest_framework import serializers from .models import OtherUser, Category, Item, ItemImageAndVideos, Offers, Searches, Message, Notifications, ShipmentDetails, ContactUs class UserSerializer(serializers.ModelSerializer): class Meta: model = User ...
# Generated by Django 3.0.3 on 2021-04-01 21:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0010_merge_20210401_1845'), ] operations = [ migrations.AlterField( model_name='resource', name='category', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 6 11:34:33 2020 @author: ramakrishnadevarakonda """ import csv from pathlib import Path input_file = Path('Resources','election_data.csv') output_file = Path('Analysis','Election_Result.txt') total_no_of_votes=[];list_of_candidates=[];candidate_v...
#!/usr/bin/python3 jegy = input("Adj meg egy számot 1 és 5 között! ") jegy = int(jegy) if jegy == 5 and jegy != 4 and jegy != 3 and jegy != 2 and jegy != 1: print(int(jegy), " jeles", sep= "") if jegy != 5 and jegy == 4 and jegy != 3 and jegy != 2 and jegy != 1: print(int(jegy), " jó", sep= "") if ...
# python program to check the user input is a leap year or not? #Solution: year = int(input("Enter the year to check leap year: ")) def year_check(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) ...
class Animal(object): MATURE_AGE = 5 name = None age = 0 def __init__(self, name, age=6): self.name = name self.age = age def __str__(self): return f"name: {self.name}, age: {self.age}" def is_mature(self): if self.age >= 18: return True el...
import socket import threading def re_msg(conn,addr): while True: print('message form ',addr) msg =conn.recv(1024) msg=msg.decode('utf8') print(msg) if msg =='fin': conn.send(b'disconnect ') server.close() break remsg = input('typ...
import preprocess import numpy as np import forward_pass x1 = np.array([[2,2,3,4,5], [1,3,3,4,5], [1,2,4,4,5], [1,2,3,5,5]]) x2 = np.array([[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]]) wst = np.array([1,20,20,2...
import warnings warnings.filterwarnings('ignore') import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import scipy.stats as stats color = sns.color_palette() #get_ipython().run_line_mag...
import getopt import sys import good_usage import get_package_info import check_package if len(sys.argv[1:]) is 0: good_usage.good_usage() else: try: opts, args = getopt.getopt(sys.argv[1:], "s:c:hd", ["search=", "check=", "help", "debug"]) except getopt.GetoptError: sys.exit(2) for op...
# -*- coding: utf-8 -*- # pylint: disable=exec-used """ Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files. """ import glob import inspect import os import sys import types __all__ = ['optional', 'include'] def optional(filen...
from ._title import Title from plotly.graph_objs.scattergeo.marker.colorbar import title from ._tickformatstop import Tickformatstop from ._tickfont import Tickfont
# coding: utf-8 # ##AIP Friday September 12 # To do list: # - events : get information from keyboard and mouse # - pygame and time # - open, write and save a data file # - (if we have time) images # ###Events # Here is a little script to help you grasp the way events are coded. # # Run the script either ...
import re from twisted.python import log # This file contains rules for processing input files # # regexp -> function to manipulate input nameRules = {} # all rules are functions. input is the parse tree ?!? # output is the modified parse tree def slashdot(soup): log.msg('rules.slashdot(): processing slashd...
from django.db import models from django.contrib.auth.models import User from core.utils import generate_slug class BetInvite(models.Model): INITIAL_STATE = 'pending' INVITE_STATES = ( ('pending', 'Pending'), ('accepted', 'Accepted'), ('rejected', 'Rejected'), ) creator = model...
from license import p from time import sleep i = 1341 while i >= 1244: content = f"https://boxnovel.com/novel/the-legendary-mechanic-boxnovel/chapter-{i}" print(f'add {content}') p.add(content) i -= 1 sleep(1)
array = [] d = 0 a = int(input("How many numbers would you like to check for? ")) for i in range(0,a): b = int(input("Enter the number? ")) array.append(b) while d < a: for j in range(0,len(array) - 1): if array[j] < array[j + 1]: c = array[j] array[j] = array[j + 1...
#!/usr/bin/env python # coding=utf-8 from point import *