text stringlengths 38 1.54M |
|---|
#!/bin/python
# This is an example app which post a shortcode and the desination url the redirect
#
# The intention is to gerenate personal short code URLs allowing analytics
# of the clicks, do to which user received them on for what product and which
# day of the week it was sent, and which position in the message... |
import os
import yaml
import sys
import errno
import winreg
from re import match as re_match
from pathlib import Path
class Data():
def __init__(self, core_app):
self.app = core_app
self.app_data = os.getenv('LOCALAPPDATA')
self.app_data_path = os.path.join(self.app_data, 'eDrawingFinder')
self.log_path = o... |
#! /bin/python3
import requests
from bs4 import BeautifulSoup
session = requests.Session()
url = "http://infinite.challs.olicyber.it/"
res = session.get(url)
res = res.text
# print(res)
# 1 in qualcosa per vedere se `e veramente dentro
# 2 cerca la stringa con find
# 3 beautfiulsoup
# Parse the html content
so... |
number1= float(input('enter first number:'))
number2 =float(input('enter number2:'))
if number1 > number2:
number1bigger =True
else:
number1bigge=False
print('number1bigger:', number1bigger)
|
# coding: utf-8
# ### 1. 数据预处理。
# In[1]:
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb
max_features = 20000
maxlen = 80
batch_size = 32
# 加载数据并将单词转化为ID,max_features给出了最多使用的单词数。... |
# -*- coding: utf-8 -*-
"""Generate a default configuration-file section for fn_clamav"""
from __future__ import print_function
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_clam... |
# Professor, fui fazendo na pressa e não me liguei que precisava usar orientação de arquivos para realizar os objetivos do exercício.
# O programa funciona como deveria, mas funciona como se fosse uma máquina de arcade nova e todos os recordes precisassem ser escritos
# do começo. Ta bonitinho, pode ver ai. Espero que ... |
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Map
df_tb = pd.read_excel('./data.xlsx')
def func(m):
a = []
for i in range(0, 35):
b = (df_tb['地区'][i], int(df_tb[m][i]))
a.append(b)
return a
#
datas2 = func('2016年')
print('=============... |
import numpy as np
__all__ = ['wswd2uv', 'uv2wswd']
# Using np.multiply and np.add and np.square to keep scaler.
def wswd2uv(ws, wd):
"""Convert wind speed and wind direction to u, v.
ws: wind speed
wd: wind direction (in degrees, north wind is 0, east wind is 90, etc)
Returns: u, v
"""
wd = n... |
#
# Sample Controlller for SIGVerse
#
import sys
import os
import time
import sig
import math
#
# Sample controller for SIGVerse
#
class AgentController(sig.SigController):
def onInit(self, evt):
try:
obj = self.getObj()
if not obj.dynamics() :
obj.setJointAngle("LARM_JOINT2", math.radians... |
# Load dataset
import pandas as pd
from datetime import datetime
cluster_dataset = pd.read_csv("https://raw.githubusercontent.com/MoH-Malaysia/covid19-public/main/epidemic/clusters.csv")
cluster_dataset = pd.DataFrame(cluster_dataset)
new_cluster_dataset = cluster_dataset.reset_index(inplace=True)
new_cluster_dataset... |
import numpy as np
import itertools
from collections import defaultdict
from datetime import datetime
import math
import sys
import os
from scipy.stats import percentileofscore
import graphlab as gl
import graphlab.aggregate as agg
gl.set_runtime_config('GRAPHLAB_CACHE_FILE_LOCATIONS','/home/mraza/tmp/')
gl.set_runtime... |
"""
persistor base class
"""
class PersistorBase():
def __init__(self):
pass
def write(self, feature, dumps, **kwargs):
raise NotImplementedError("Persistor write method implementation error!")
def read(self, uid, **kwargs):
raise NotImplementedError("Persistor read method... |
# Generated by Django 3.0.6 on 2020-05-07 16:38
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('mall', '0013_auto_20200508_0028'),
]
operations = [
migrations.RemoveField(
model_name='cart',
... |
# Complete the following exercises
# a. Find the average of following numbers, assign it to a variable, print the average
# and total numbers used for the average:
# i. For Example: For numbers 44, 64, 88, 53, 89, when you run the file it
# should print something like: The average of 5 given numbers is : 67.6.
num1 ... |
import pandas as pd
import matplotlib.pyplot as plt
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
data_tables = {
'services_exports':{'filename':os.path.join(ROOT_DIR, 'SGP_services.csv')},
'services_imports': {'filename': os.path.join(ROOT_DIR, 'SGP_services_imports.csv')},
'employment'... |
from flask_wtf import FlaskForm
from wtforms.validators import InputRequired, Length, EqualTo, Email, DataRequired, Optional
from wtforms import Form, StringField, SelectField, TextAreaField, PasswordField, IntegerField, SubmitField, DateField, FileField, validators
from wtforms.fields.html5 import EmailField
class Lo... |
class Solution:
def strStr(self, haystack: 'str', needle: 'str') -> 'int':
# 当needle是空字符串时我们应当返回0 。这与C语言的strstr()以及Java的indexOf()定义相符
if len(needle) == 0 :return 0
# 不存在满足条件的子串
if len(needle) > len(haystack) :return -1
# 遍历比对
for h in range(len(haystack) - len(needle)... |
def extractFmgandalfWordpressCom(item):
'''
Parser for 'fmgandalf.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
chp_prefixes = [
('BS ', 'Black Summoner', ... |
import logging
import http.server
import socketserver
import getpass
#Classe MyHTTPHandler herdar de http.server.SimpleHTTPRequestHandler
#Reescrever o método log_message, personalizar
#Logar IP e Data e passar os argumentos
class MyHTTPHandler(http.server.SimpleHTTPRequestHandler):
def log_message(self, format,... |
import random
choices = ["Pierre", "Papier", "Ciseaux"]
print("if you want to end write 'End'")
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Pierre, Papier, Ciseaux?").capitalize()
if player == computer:
print("Play Again")
elif pl... |
def initL1RSSubsystemsExt( tagBaseVec = [],
# L1MuDTTFMasksRcdKey = 'dummy',
):
import FWCore.ParameterSet.Config as cms
from CondTools.L1TriggerExt.L1CondEnumExt_cfi import L1CondEnumExt
initL1RSSubsystemsExt.params = cms.PSet( recordInfo = cms.VPSet() )
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2015 Civic Knowledge. This file is licensed under the terms of the
Revised BSD License, included in this distribution as LICENSE.txt
"""
import argparse
from itertools import islice
from six import binary_type
import tabulate
from .mpf import MPRowsFile
from .__meta__ impo... |
IN_H_HEADER = r"""
#include <Arduino.h>
#include "SerialCommand.h"
#include "inodriver_user.h"
const char COMPILE_DATE_TIME[] = __DATE__ " " __TIME__;
void ok();
void error(const char*);
void error_i(int);
void bridge_loop();
"""
IN_CPP_HEADER = r"""
#include "inodriver_bridge.h"
SerialCommand sCmd;
void ok() {... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-23 10:42
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('content', '0088_expensecategory_order'),
('content', '0087_report_permissions'),
]
... |
# from . import archive_outputs
from pypyr.context import Context
from pypyr.errors import KeyNotInContextError
from . import cmd, py
def get_formatted_or_default(self: Context, key: str, default):
try:
return self.get_formatted(key)
except (KeyNotInContextError, KeyError):
return default
... |
import random
import smtplib
import string
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from flask import render_template, request, url_for, redirect, session
from project import app
from project.com.controller.LoginController import adminLoginSession, adminLogoutSession
from pr... |
# -*- coding: utf-8 -*-
import json
f = codecs.open("keywords.txt", encoding='utf-8', mode='r')
kw=f.readlines()
f.close()
searches=[]
for i in range(len(kw)):
s=kw[i][:-1].split("\t")
if len(s)>1:
searches.append(s)
output=[]
for s in searches:
s1=s[0].replace("/search?","").split("&")
s2=[... |
#Code for the Rotten Tomatoes Kaggle contest
#Import libraries
print('Importing needed libraries...')
import pandas as pd
import numpy as np
from nltk.tokenize import word_tokenize
import itertools
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn import metrics
from ... |
#! bin/python
from pylab import *
from matplotlib import patches
from Function import *
rcParams['xtick.direction'] = 'in'
rcParams['ytick.direction'] = 'in'
class Cursor():
def __init__(self, ax):
self.Inc = 45.
self.PA = 0
self.Vr10 = 10
self.vmax = 5
self.vmin = -5
... |
from importlib import import_module
mod = import_module('testclass')
met = getattr(mod, 'Complex')
t= met(4.0, -4.5)
print t.__module__
print dir(t) |
import numpy as np
def smooth_x(wave, x, s, g,):
xx = x.shape[0]
xy = x.shape[1]
smooth = np.zeros([xx, xy])
for i in range(s+1, xy-s):
sa = np.mean(x[:, int(i - s):int(i + s)], axis=1)
smooth[:, i] = sa
return smooth
|
# Написать программу сложения и умножения двух шестнадцатеричных чисел. При
# этом каждое число представляется как массив, элементы которого — цифры числа.
# Например, пользователь ввёл A2 и C4F. Нужно сохранить их как [‘A’, ‘2’] и
# [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’],
# произведени... |
"# -*- coding"
"""
@author:xda
@file:fund_share_update.py
@time:2021/01/20
"""
# 基金份额
import sys
sys.path.append('..')
from configure.settings import DBSelector
from common.BaseService import BaseService
import requests
import warnings
import datetime
import math
import re
warnings.filterwarnings("ignore")
from sqlal... |
# -*- coding: utf-8 -*-
from twisted.internet.protocol import Protocol
import logging
from twisted.internet import reactor
import struct
import ipaddress
from c2w.main.constants import ROOM_IDS
logging.basicConfig()
moduleLogger = logging.getLogger('c2w.protocol.tcp_chat_server_protocol')
class c2wTcpChatServerProto... |
# Generated by Django 2.2.12 on 2020-11-02 06:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('barang', '0006_auto_20201102_0655'),
]
operations = [
migrations.AlterField(
model_name='online',
name='jumlah',
... |
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'rex/proto/ntlm/message'
require 'rex/proto/http'
require 'metasploit/framework/credential_collection'
class MetasploitModule < Msf::Auxiliary
include Msf::Auxiliary::Rep... |
import mandrill
import requests
import json
from datetime import datetime
API_KEY = 'j3VdGCRj9OsJiY5LZQlT5g'
mandrill_client = mandrill.Mandrill(API_KEY)
mandrill_link = 'https://mandrillapp.com/api/1.0/'
class Verify():
data = {
"key": API_KEY
}
responseStruct = requests.post(mandrill_link + 'us... |
from datetime import datetime, timedelta
from ._base import BarReader
def show_bars(bars):
import pandas as pd
frame = pd.DataFrame([bar.__dict__ for bar in bars])
print(frame.set_index("datetime")[["open", "high", "low", "close", "volume", "vtSymbol"]])
def test(reader, symbol):
import tra... |
#python selenium应用javascript
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
url="https://www.12306.cn/index/"
driver=webdriver.Firefox()
driver.get(url)
date = ['2019-10-17', '2020-1-17', '2020-2-17']
for i in date:
js = "document.getElementById('train_date').va... |
from google.appengine.ext import ndb
class User(ndb.Model):
email = ndb.StringProperty()
password = ndb.StringProperty()
role = ndb.StringProperty()
|
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html
import numpy as np
from scipy import signal
from scipy.fftpack import fftshift
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, figsize=(8, 7))
t = np.arange(0, 1, 0.002)
fs = 1.0 / (t[1] - t[0])
x = 4 * np.sin(2 * np.pi *... |
#!/usr/bin/python3
import argparse
import typing
import os
import pathlib
import sys
EXTENSIONS = ['adoc', 'anaconda', 'conf', 'html', 'json', 'md', 'pp', 'profile', 'py', 'rb',
'rst', 'rules', 'sh', 'template', 'toml', 'var', 'xml', 'yaml', 'yml']
EXCLUSIONS = ['/shared/references/', '/logs/', '/tests/... |
def warmup1(line: list)->list:
warmup1 = []
for i in warmup1:
warmup1.remove(0)
return list(warmup1)
num = int(input("Enter a sequence of numbers:"))
found = []b
for numbers in num:
found.append() |
import pickle
import numpy as np
import cv2
import os
from copy import *
class Data_loader:
def __init__(self, filelist, scale_size, img_dir):
self.scale_size = scale_size
self.img_dir = img_dir
# self.img_mean = np.float32([[[104., 117., 124.]]])
with open(filelist, 'r') a... |
#!/usr/bin/env python
import os
import sys
from bluetooth import BluetoothSocket, L2CAP
import dbus
import dbus.service
import gobject
from dbus.mainloop.glib import DBusGMainLoop
import blinkt
from client import Keyboard
PROFILE = "org.bluez.Profile1"
ADDRESS = "B8:27:EB:EC:E9:95"
DEVICE_NAME = "PiZero"
PROFILE_DBU... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 14:38:58 2018
@author: Dyass
"""
"""
Topics:
Examples with a Dictionary:
1:Create a frequency distribution mapping str:int
2:Find a word that occurs the most and how many times:
use a list,in case there is mote than one word
... |
# -- coding: utf8 --
import sys
sys.path.insert(0,'..')
from model.data_model import *
import common.common as common
def main():
daylist = common.getdaylist('20151201','20151222')
for day in daylist:
print day
tablename = 'devpower_detail_' + day
data_model(tablename).drop()... |
#!/usr/bin/env python2
from __future__ import print_function
import sys, os, time
import shutil
from pdb import set_trace
from glob import glob
import re
########################## Parsing and environment ############################
import subprocess
from helpers import submitjob, createClusterInfo, resetJobOutput... |
from django.contrib.auth import login as auth_login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from .models import Item, Tag
from .forms import ItemForm, Ta... |
import cosmolopy
import pymc
from pymc import Metropolis
from McMc import mcmc
from astropy.io import fits
from McMc import cosmo_utils
import scipy
# post intéressant pour mettre son propre likelihood
#https://groups.google.com/forum/#!topic/pymc/u9v3XPOMWTY
################ SNIa ###################################... |
"""
Markdown parsing and rewriting for embedding narrative images.
Contains a Parsing Expression Grammar (PEG) for parsing Markdown with
:py:mod:`pyparsing`. The grammar expects a complete Markdown document, but
only parses the minimal number of Markdown constructs required for our needs
(namely, embedding narrative ... |
"""
Copyright 2013 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... |
import logging
from hashlib import sha1
from pylru import lrucache
from py2neo import Node
from aleph.graph.util import BASE_NODE, GraphType
log = logging.getLogger(__name__)
class NodeType(GraphType):
_instances = {}
def __init__(self, name, fingerprint='fingerprint', indices=[],
hidden=F... |
import numpy as np
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
# np.set_printoptions(precision=3)
ROWS = 1
COLS = 5
LABELS = ['LOCATION', 'X', 'Y', 'Z', 'MAGNITUDE']
DECIMALS = 3
class Table(QVBoxLayout):
def __init__(self, parent):
... |
"""
Messi's Goal Total
Use variables to find the sum of the goals Messi scored
in 3 competitions
Information
Messi goal scoring statistics:
Competition Goals
La Liga 43
Champions League 10
Copa del Rey 5
Task
Create these three variables and store the appropriate
values using the table above:
la_liga... |
"""Code to interact with the login server from a python shell.
Usage:
$ python
...
>>> from client import *
>>> admin.addUser('fred', 's3cr3t')
>>> fred = login.login('fred', 's3cr3t')
The 'fred' value is a proxy to a persistent UserCaps object to which
we can add 'capabilities', other persistent objects t... |
from __future__ import print_function
from install_requirements import is_dependencies_satisfied
import sys
if not is_dependencies_satisfied():
print("some packages are missing, please type: \"python install_requirements.py\"", file=sys.stderr)
exit(1)
from utils import err_print
import requests
import re
impo... |
import socket
from ip2geotools.databases.noncommercial import DpIpCity
url = input("can abi, lütfen linki girermisin? : ")
IP = socket.gethostbyname(url)
response = DpIpCity.get(IP, api_key='free')
print("IP adresi:", IP)
print("bulunduğu şehir:", response.city)
print("bulunduğu bölge:", response.region)
print("bulund... |
from collections import defaultdict
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
d[k].add(v)
print(d)
s = 'mississippi'
d = defaultdict(int)
for k in s:
d[k] += 1
print(d)
from collections import defaultdict
s = [('red', 1), ('blue', 2), ... |
from django.db import models
# apps tercero
from PIL import Image
from . managers import CursoManager
# Create your models here.
class Curso(models.Model):
""" Modelo para tabla curso """
nombre = models.CharField('Nombre', max_length=60)
direccion = models.CharField('Destino', max_length=60)
fecha = ... |
# Generated by Django 3.2.3 on 2021-06-03 00:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Reco... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 21:07:40 2017
@author: katsuhisa
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# for visualization
import matplotlib.pyplot as plt
import seaborn as sns
# import data
train = pd.read_csv('../input/tra... |
from telegram.ext import Updater, CommandHandler,MessageHandler,Filters,InlineQueryHandler,CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,ReplyKeyboardMarkup,ReplyMarkup,KeyboardButton,InputTextMessageContent,InlineQueryResultArticle,KeyboardButton
import telegram
import os
TOKEN... |
# TODO pages not supported
# TODO tables not supported
# TODO multi dimensional array in binary are not supported
# struct format
# >: big
# <: little
# |: machine
# x: pad byte (no data);
# c:char;
# b:signed byte;
# B:unsigned byte;
# h:short;
# H:unsigned short;
# i:int;
# ... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
app.config['SECRET_KEY'] = '3c81070f775a7e7ac6a67c22'
db.init_app(app)
# https://flask-sqlalchemy.palletsprojects.com/e... |
from ValueTreeViewItem import ValueTreeViewItem
class HistoryDataDisplayTreeViewEnumTypeItem(ValueTreeViewItem):
def __init__(self, name, value, attribute, parent):
super(HistoryDataDisplayTreeViewEnumTypeItem, self).__init__(item_data=[name, value],
... |
def get_floats():
try:
a_list = [float(x) for x in input("Enter elements of a list separated by space: ").split(' ')]
if len(a_list) > 2:
return a_list
else:
raise ValueError
except ValueError:
print("At least two scores needed!")
quit()
def summ... |
# -*- coding:utf-8 -*-
import os
import json
import datetime
import sys
import threading
from time import sleep
from threading import Thread
import time
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
def runFuncWithTimeLimit(... |
def solution(n, arr1, arr2):
answer = []
for i in range(n):
plus = ''
ans = bin(arr1[i] | arr2[i])[2:]
if len(ans) != n:
plus = '0' * (n-len(ans))
ans = plus + ans
ans = ans.replace('1','#')
ans = ans.replace('0',' ')
answer.appe... |
# Generated by Django 3.1 on 2020-09-15 00:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='course',
name='course_description',
... |
#!/usr/bin/python3
import sys
if len(sys.argv) != 2:
sys.exit("[ERROR] Bad parameter(s)")
fname = sys.argv[1]
text = ""
try:
file = open(fname, encoding='utf-8')
text = file.read()
except IOError:
sys.exit("[ERROR] Could not read file \"" + fname + "\"")
else:
file.close()
while True:
a = ... |
# coding: utf-8
# flake8: noqa
"""
OANDA v20 REST API
The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. To authenticate use the string 'Bearer ' followed by the token which can be obtained at https://www.oanda.com/demo-a... |
from lively_tk_ros.configuration.config_manager import ConfigManager
import os
from pprint import PrettyPrinter
pprinter = PrettyPrinter()
pprint = lambda content: pprinter.pprint(content)
script_dir = os.path.dirname(__file__)
urdf_file = os.path.join(script_dir,'./launch/ur3e.xml')
with open(urdf_file) as file:
... |
import os
import cv2 as cv
# Original image
image = cv.imread("./Resources/Photos/group 2.jpg")
cv.imshow("Original", image)
gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("Gray", gray_image)
# haar cascade clasifier
haar_face = cv.CascadeClassifier(
cv.data.haarcascades + "haarcascade_frontalface_... |
import numpy as np
import scipy
if tuple(map(int, scipy.__version__.split('.'))) < (1, 0, 0):
from scipy.misc import logsumexp
else:
from scipy.special import logsumexp
import time
from tqdm.autonotebook import tqdm
def normalize_features(features):
'''features: n by d matrix'''
assert(len(features.sha... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
# Generated by Django 3.1.2 on 2020-11-13 08:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20201113_1032'),
]
operations = [
migrations.AlterField(
model_name='productop... |
from django.views.generic import FormView
from .mixins import AjaxableResponseMixin
from .forms import EmailSendForm
from .utils import email_send
# Create your views here.
class EmailSendView(AjaxableResponseMixin, FormView):
form_class = EmailSendForm
http_method_names = [u'post']
def form_valid(self,... |
def notas(*n, sit = False):
notas = dict()
notas['total'] = len(n)
notas['maior'] = max(n)
notas['menor'] = min(n)
notas['média'] = sum(n)/len(n)
if sit:
if notas['média'] >= 7:
notas['situação'] = 'Boa'
if notas['média'] >= 5:
notas['situação'] = 'Razoáve... |
# Library Imports
import os
os.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = '1'
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import numpy as np
import gym
from MultiTD3 import Agent
import random
from gym.wrappers.time_limit import TimeLimit
from custom_pendulum import C... |
list = []
getNum = int(input('How many numbers: '))
for n in range(getNum):
numbers = int(input('Enter number: '))
list.append(numbers)
def addList(numbers):
sum = 0
for num in numbers:
sum += num
return sum
result = addList(list)
print(result) |
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QPushButton, QCheckBox, QGridLayout, QLineEdit, QLabel, QSizePolicy
class AboutUsWindow(QDialog):
def __init__(self, controller, *args, **kwargs):
super().__init__(*args, **kwargs)
self.controller =... |
import Diary2
print("문단을 입력해보세요")
para=input()
print("슬픔, 중립, 행복, 불안, 분노, 예외 리스트입니다.")
response = Diary2.predict(para)
print(response)
#print(Diary2.predict("너무 슬퍼요"))
|
#!/usr/bin/env python
# encoding: utf-8
# @author: liusir
# @file: demo_04.py
# @time: 2020/11/29 9:47 上午
import json
json_obj = {"access_token":"39_qHfCmB0GdutZ2MXC0G5IbzrM3WY7ES3JQF_bY04G-ceI-umT7_9E7-m0e3lVx-YFJRcTMnmKga-ijt45IFCrBPeIbbq0PsFphgzjAyaAeYhk8Po13Ix7oQQAi-a85xplVyuERp_rIci3wiP1CRKiAFAIXQ","expires_in":... |
from django.contrib import admin
# Register your models here.
# Register your models here.
from .models import *
#model admin options
class PostModelAdmin(admin.ModelAdmin):
list_display = ["id","mainlocation","othername",]
#list_display_links = ["updated"]
class Meta:
model = tree
admin.site.reg... |
# Here we include the weather-api so we can use it in our Python application.
from weather import Weather, Unit
# Then we use the module to search for the weather at a location
weather = Weather(unit=Unit.CELSIUS)
location = weather.lookup_by_location('Anchorage, AK')
condition = location.condition
print(condition.tex... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
åååæææøøø
lengde_meter_streng = input("Skriv inn lengde i meter: ")
bredde_meter_streng = input("Skriv inn bredde i meter: ")
lengde_meter = float(lengde_meter_streng)
bredde_meter = float(bredde_meter_streng)
areal = lengde_meter*bredde... |
from LoginApp import login_app
import unittest
uname = "prakash"
pwd = "Prakash123"
class Test_Login_App(unittest.TestCase):
def test_user_creation_success(self):
login_app.__init__(self)
result=login_app.register(self,uname,pwd)
self.assertTrue(result)
def ... |
class ErrorCodes:
COMBINATION_DOES_NOT_EXIST = 'COMBINATION_DOES_NOT_EXIST'
GAME_DOES_NOT_EXIST = 'GAME_DOES_NOT_EXIST'
GAME_IS_FINISHED = 'GAME_IS_FINISHED'
WORD_HAS_BEEN_ADDED_ALREADY = 'WORD_HAS_BEEN_ADDED_ALREADY'
INCORRECT_LENGTH = 'INCORRECT_LENGTH'
INCORRECT_SEQUENCE = 'INCORRECT_SEQUEN... |
from item import Item
from filemanager import setup
def fractional_knapsack(capacity, items):
'''
This algorithm solves the problem by calculating the profit per weight
and adds the items with highest value first to the knapsack
until no more items fit
Assumption: Each item can only... |
import string
from helpers import alphabet_position, rotate_character
def encrypt(text, word):
vigenere = ""
counter = 0
for n in range(len(text)):
if text[n] in string.ascii_letters:
text_letter = text[n] #I think the reason for this is because our text is already at a certain length(s... |
a = (1, 2), (3, 4), (1, 3), (2, 3), (3, 1), (3, 2)
def my_map(key, values):
temp_list = []
for x in values:
temp_list.append((x[0], 1))
return temp_list
# print(my_map('Q1', a))
def my_reducer(intermediates):
temp_list = []
for key in dict(intermediates).keys():
sumv = 0
... |
import functools
from nltk.stem.snowball import SnowballStemmer
import numpy as np
import pandas as pd
import scipy.sparse
import sklearn.feature_extraction.text
import sklearn.metrics
stemmer = SnowballStemmer('english')
def stemming_preprocessor(data):
return stemmer.stem(data)
@functools.lru_cache(maxsize=... |
import random
import json
f = open('json.json', 'a')
def generate(x, y):
str = input("Enter a text (or number): ")
length = len(str)
h = x + y + length
h = h * x
h = h + y
s = random.randint(1,100)
h = h + s
return h
for i in range(0,10):
a = generate(random.randi... |
score1 = int(input('숫자를 입력하세요 : '))
if score1 % 3 == 0:
print('3의 배수입니다.')
else :
print('3의 배수가 아닙니다.')
|
from setuptools import setup
#from Cython.Build import cythonize
setup(
name="cgmspec",
version="0.1",
description="Python software for modeling and synthetic spectra from an idealized CGM model",
author="M. Hamel",
author_email="magdalena.hamel@gmail.com",
url="https://github.com/ntejos/cgmspe... |
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import gettext_lazy as _
from .forms import AdminUserChangeForm
from .models import Room, User
cl... |
# coding = utf-8
import time
import selenium
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://118.178.253.144:8080/itsm") # 打开网页
browser.maximize_window()
# #填写用户名
browser.find_element_by_id('accountNameId').send_keys('admin#jingyu')
# #填写密码
browser.find_element_by_id('passwo... |
from KerasWrapper.Wrappers.LayerWrapper import LayerWrapper
from typing import List
from abc import abstractmethod
from abc import ABC
from keras.models import Sequential
class NeuralNetWrapper(ABC):
def __init__(self, input_size, output_size, problem_type):
# Hyperparameters that are configured ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.