text stringlengths 8 6.05M |
|---|
def prime_factors(num):
cur_num = int(num)
cur_div = 2
prime_factors = []
while cur_num > 1:
remainder = cur_num % cur_div
if remainder == 0:
prime_factors.append(cur_div)
cur_num = cur_num // cur_div
else:
cur_div += 1
return prime_factors
def euler(num):
... |
import sys
sys.path.append('Config/')
import config
import cls_DataBase
from cls_ParserDataSource import ParserDataSource
import cls_Keeper
#
class DataFactoryErp():
def __init__(self):
self.conf = config
def create_data_source(self):
return cls_DataBase.DatabaseErp(self.conf.config['database']['erp'])
def ... |
import pylab as plt
import numpy as np
# def show_scatter(times, epochs, data):
# # scatter
# plt.figure(figsize=(8, 5))
# # 2-dimensions #
# # plt.scatter(epochs, data, 'o')
#
# # 3-dimensions #
# c = np.random.randint(0, 10, 100)
# plt.scatter(epochs, data, c=c, marker='o')
# plt.colo... |
# # File holds the class to solve various problems classically (for example: using brute force methods)
import pandas as pd
import numpy as np
from itertools import combinations
from utils.data import parse_profit_dataframe
def binary_profit_optimizer(profit: list[float], cost: list[float], budget: float) -> tuple[lis... |
class Solution:
def lengthOfLongestSubstring(self, s):
stringMap = {}
start = 0
end = 0
res = 0
for i in range(len(s)):
end = i+1
# print(s[i],stringMap.get(s[i]))
if stringMap.get(s[i])==None:
stringMap[s[i]]=True
... |
"""
while 循环:根据缩进为一个代码块
基本语法
while 条件(判断、计数器、是否到达目标次数):
条件满足执行的语句
...
处理条件(计数器+1)
"""
def while_test(test):
if not test:
return
i = 0
while i < 10:
print("i love you !")
i = i + 1
if i == 7:
print("说了 7 遍了")
continue
if i == 9:
... |
# -*- coding: utf-8 -*-
# 中國剩餘定理
# 求基本同餘式組的通解
from .NTLExceptions import DefinitionError
from .NTLUtilities import jsrange
from .NTLValidations import int_check, list_check, tuple_check
__all__ = ['CHNRemainderTheorem', 'solve', 'iterCalc', 'updateState']
nickname = 'crt'
'''Usag... |
'''
Created on Dec 23, 2014
@author: desposito
'''
class HopsSchedule(object):
'''
A list of hops used for a recipe along with where they are used and what time they are used.
'''
def __init__(self):
'''
Creates a new empty list object for the schedule.
'''
self.clearA... |
#Project Euler Problem 12
#What is the value of the first triangle number to have over five hundred divisors?
import math
divisor=500
A=0
j=1
i=0
while i<divisor:
A+=j
i=0
j+=1
#print('New Number')
#print(i)
for k in range(1,A+1):
if math.fmod(A,k)==0:
i+=1
if k==A:
print(i)
if i>=divisor:
sta... |
# Generated by Django 3.0.8 on 2020-11-26 08:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('learners', '0003_auto_20201029_2101'),
]
operations = [
migrations.AddField(
model_name='lqueries',
name='status',
... |
from osv import fields, osv
class account_invoice_electronic_state(osv.Model):
_name = "account.invoice.electronic.state"
_columns = {
'state_electronic' : fields.char('Estado electronico'),
'active' : fields.boolean('Activo'),
}
account_invoice_electronic_state()
class account_invoice(osv.Model):
_name = "a... |
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class PrivateMediaStorage(S3Boto3Storage):
def __init__(self, *args, **kwargs):
kwargs['bucket_name'] = settings.AWS_PRIVATE_BUCKET
super(PrivateMediaStorage, self).__init__(*args, **kwargs)
location = ''
... |
from rest_framework import serializers
from ..models import Cocktail
from django.contrib.auth import get_user_model
User = get_user_model()
class CocktailSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.id')
class Meta:
model = Cocktail
fields = ["id... |
import pickle
import socket
def digit_sum(number):
s = 0
while number > 0:
s += number%10
number //= 10
return s
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 9999))
data, addr = s.recvfrom(100)
dig_s = digit_sum(addr[1]) + int(data.decode())
print(addr[1])
s.sen... |
# examples of using for loops
for num in range(0,3):
print("Hello")
# print numbers between 18 and 22
for num in range(18,23):
print(num)
# for loop print by 2s
for num in range(0,21,2):
print(num)
#for loop with variables
start_num = int(input("Enter a start value"))
stop_num = int(input("Enter a stop v... |
import csv
import os
import math
import os.path
def formatUnc(unc):
return "{0:4.3f}".format(unc)
tableHeader=["","systematic"]
tableTotal=["","total uncertainty"]
tableRows=[
['stat', "statistical"],
["line"],
#fitting
['fiterror', "ML-fit uncertainty"],
['diboson', "Diboson fraction"],
['dyjets', "Dr... |
from django.shortcuts import render,redirect
from django.contrib import messages,auth
from django.contrib.auth.models import User
# Create your views here.
def register(request):
if request.method == "POST":
first_name = request.POST["fname"]
last_name = request.POST["lname"]
email = reques... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the roadsAndLibraries function below.
'''
Initially tried with union find but the algorithm is not efficient and also
there is some bug, later tried with DFS
class UF:
def __init__(self,N):
self.id = [i for i in range(N+1)... |
# Generated by Django 2.1.4 on 2019-01-11 15:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('clientele', '0005_clientele_services'),
('services', '0002_auto_20190109_1816'),
('psychologues', '0010_psychologues_linked_in'),
]
operatio... |
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
def perceptrona(w_init, X, Y):
# PERCEPTRONA Find weights for linear discrimination problem.
# PERCEPTRONA(w_init, X,Y) finds and returns the weights w as well as e, the number of
# epochs it took to reach convergence to solve the linear dis... |
a = "Hello my world today we try to find the number of spaces"
print(a.count(" "))
|
# @Title: 最长重复子数组 (Maximum Length of Repeated Subarray)
# @Author: 2464512446@qq.com
# @Date: 2020-07-01 15:15:37
# @Runtime: 6484 ms
# @Memory: 37.9 MB
class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
n, m = len(A), len(B)
dp = [[0] * (m + 1) for _ in range(n + 1)]
... |
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
file = pd.read_csv("landslide_data3.csv")
#QUES1
print("\n******QUESTION-1*******")
def mean(x):
return np.mean(x)
def median(x):
return np.median(x)
def mode(x):
return stats.mode(x)
def minimum(x):
re... |
# if elif else statements
# hungry = False
# if hungry:
# print('Feed Me!')
# else:
# print('Im not hungry')
# loc = "Bank"
# if loc == "Auto Shop":
# print("Cars are nice")
# elif loc == "Bank":
# print("Money is nice")
# else:
# print("I dont know much")
# name = "Sammy"
# if name == "Fran... |
def quickSort(A):
quick_sort2(A, 0, len(A)-1)
def quick_sort2(A, low, hi):
p = partition(A, low, hi)
# low hi and pi are indexes of the array
quick_sort2(A, low, p-1)
quick_sort2(A, p+1, hi)
def get_pivot(A, low, hi):
mid = (hi + low) // 2
pivot = hi
if A[low] < A[mid]:
if A[m... |
from keras.callbacks import Callback
from CSVDataFrame import CSVDataFrame
import numpy as np
class EvaluateCallBack(Callback):
def __init__(self,model,encoder,model_name,x_val,y_val,obj_val,test_fn,pool = None,max_wait=5):
self.x_val = x_val
self.y_val = y_val
self.obj_val = obj_val
... |
class Solution(object):
def findOrder(self, numCourses, prerequisites):
from collections import deque
graph = { i:set() for i in range(numCourses)} # v:income number
neigh = [set() for i in range(numCourses)] # graph
res, cnts = [], 0
for [x, y] in prerequisites:
... |
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.core.mail import send_mail
from django.shortcuts import render
def home(request):
nothing = {}
if r... |
#performing all Ec2 instance operations
import boto3
aws_mgm_con = boto3.session.Session()
ec2_dashboard_res = aws_mgm_con.resource(service_name='ec2')
ec2_dashboard_client = aws_mgm_con.client(service_name='ec2')
#print(dir(ec2_dashboard_res.instances.all()))
#print(dir(ec2_dashboard_client.start_instances))
# ins... |
from django.urls import include, path
from rest_framework import routers
from rest_framework_simplejwt.views import TokenObtainPairView, \
TokenRefreshView
from .views import DeleteReservation,ReservationsAll, RoomsAll, UserViewSet
router = routers.DefaultRouter()
router.register('users', UserViewSet, basename=... |
print('hello')
print('ahhh')
|
# -*- coding: utf-8 -*-
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import (
StandardScaler as ScikitStandardScaler,
PolynomialFeatures as SkPolynomialFeatures
)
import numpy as np
from sktutor.utils import dict_with_default, dict_default, bitwise_oper... |
def validate_instructor_counts(df):
'''Confirm that a post is either tagged as `instructor` or `student` but not both.
Args:
df: Pandas DataFrame
Returns:
tuple: Tuple representing the counts of `is_instructor` and `is_student` labeled posts.
'''
return df['is_instructor'].value_... |
# *를 표현하기 위해
__all__=['test'] |
# Generated by Django 2.1.5 on 2019-02-08 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('library', '0002_auto_20190208_0227'),
]
operations = [
migrations.AddField(
model_name='booklend',
name='total_borro... |
def main():
l = [1,2,3,4,5]
for i in range(len(l)):
print i, l[i]
if __name__=='__main__':
main()
|
# Generated by Django 2.2 on 2019-04-16 01:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0002_service_data_charge'),
]
operations = [
migrations.AddField(
model_name='service_data',
n... |
from flask import Flask
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////LOCAL/Data/github/python/python-flask-rest-api/database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
|
msg = "Hello World. Huzzah!"
print(msg)
|
import random
def OptionZero():
randFunc = [OptionOne(), OptionTwo(), OptionThree(), OptionFour(), OptionFive(), OptionSix(), OptionSeven(), OptionEigth()]
pass
def OptionOne():
chapter = 3.2
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
randNums = random.choice(nums)
print('\nDo problem #{} from ch... |
"""empty message
Revision ID: 9b12acd8f289
Revises:
Create Date: 2021-05-09 21:50:01.208225
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '9b12acd8f289'
down_revision = None
branch_labels = None
depends_on = None
d... |
"""
文件操作的权限:
文件操作权限主要有:读数据(read),写数据(write),追加数据(append)
r:读取文件:如果文件存在,则可以读取文件,如果文件不存在,则直接宝座
如果权限只有r 的时候,是只能读,不能写。
r:文件的操作权限是只读
r+:文件的操作权限是可读可写
rb:按照只能的模式打开二进制文件,例如音频,视频,图片等
rb+:安扎可读可写的方式打开二进制数据
w:写入文件:如果... |
from flask import render_template,Blueprint,jsonify,request
import json
import datetime
from slugify import slugify
from config import Setup
from templates import mongo
api_bp = Blueprint('api',__name__)
@api_bp.route('/api_status')
def api_status():
data = {
'status': 'Server Running'
}
return js... |
from BusinessLogicLayer.cluster.master import ActionMasterGeneral
class ActionWgCloud(ActionMasterGeneral):
def __init__(self, register_url='https://www.wiougong.space/auth/register', silence=True):
super(ActionWgCloud, self).__init__(register_url=register_url, silence=silence, life_cycle=153,
... |
import multiprocessing as mp
def washer(dishes, output):
for dish in dishes:
print('Washing', dish, 'dish')
output.put(dish)
def dryer(input):
while True:
dish = input.get()
print('Drying', dish, 'dish')
input.task_done()
if __name__ == '__main__':
dish_queue = mp... |
# %%
import os
import sys
import pickle
import numpy as np
import multiprocessing
import mne
import sklearn.manifold as manifold
from sklearn import svm
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
sys.path.insert(0, os.path.join(os.path.dirname(__file__... |
import math
val = -0.5*2*math.log(0.5, 2)
print (val)
print (math.log(1,2))
information_gain = 1 - .75*val
print (information_gain)
|
# encoding: utf-8
from marrow.mongo.core import Document, Field
class Example(Document):
name = Field()
age = Field()
EXAMPLE = Example("Alice", 27)
TRUTHY_CASES = [
# Comparison
# $eq
(EXAMPLE.name == "Alice"),
(EXAMPLE.age == 27),
# $gt
(EXAMPLE.name > "Aa"),
(EXAMPLE.age > 18),
# $gt... |
import sys
import os
from collections import defaultdict
from text_preprocess import txt_preprocesser
import math
import json
"""KMAMIN 62182275 KRISHAN AMIN"""
class bayesian_classifier:
def trainNaiveBayes(self,train_list):
preprocesser = txt_preprocesser()
class_doc_counts = defaultdict(int)
... |
from db import dataBase as database
from validator import Validator as validator
validator = validator()
class carmodel:
def __init__(self):
self.carmodelid = 0
self.carmodelname = ""
self.carmodeltype = ""
self.carmodelprice = 0
self.camodelyear = 0
self.mfid=0
... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3102 ._SN',
MapName = 'Zeiss',
Location = 'T3102.x',
MapIndex = 1,
MapDefaultBGM = "ed60013",
Flags = 0,
En... |
age = int(input("What is your dog age? "))
age = age * 7
print("Your dog age in dog years is", age) |
import gitwrapper
import solventwrapper
import shutil
import os
import unittest
import upseto
import osmosiswrapper
import tempfile
import subprocess
class Test(unittest.TestCase):
def setUp(self):
for key in list(os.environ.keys()):
if 'SOLVENT' in key:
del os.environ[key]
... |
# -*- coding: utf-8 -*-
from django.utils.timezone import utc
import datetime
def utcnow():
return datetime.datetime.utcnow().replace(tzinfo=utc)
|
import pandas as pd
from datetime import datetime as dt
import re
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource, FactorRange, Label
from bokeh.models.tools import HoverTool
from bokeh.transform import factor_cmap
from math import pi
from bokeh.layouts import layout, col... |
# Generated by Django 2.0.2 on 2018-03-10 16:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestion_table', '0005_auto_20180310_1633'),
]
operations = [
migrations.AlterField(
model_name='table',
name='galeri... |
from helpers.proxy_utils import deploy_proxy
from brownie import *
from helpers.constants import *
from helpers.registry import registry
from config.badger_config import sett_config
from dotmap import DotMap, pprint
from enum import Enum, auto
from rich.console import Console
console = Console()
"""
Sett is a subsystem... |
# 实现 strStr() 函数。
#
# 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如
# 果不存在,则返回 -1 。
#
#
#
# 说明:
#
# 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
#
# 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
#
#
#
# 示例 1:
#
#
# 输入:haystack = "hello"... |
from django.shortcuts import render, get_object_or_404
from django.template import loader
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from login.models import User
from .models import Address
from os import sys
def index(request):
return render(request, 'mainpage/index.h... |
import sys
import psycopg2
def connect_database(dbname, user, pwd, host_ip, port="5439"):
"""
connect to database on redshift cluster
Args:
dbname: database name to connect to server
user: user name
pwd: user password
host_ip: ip for database server
port: port ... |
import sqlite3
import hashlib
con = sqlite3.connect('racunalniske_igre.db')
con.row_factory = sqlite3.Row
def najdi_podjetje(ime):
sql = '''
SELECT id
FROM podjetja
WHERE ime = ?
'''
print(ime)
id = con.execute(sql, [ime]).fetchone()
if id is None:
sql = '''insert into podjetja... |
import numpy as np
from time import time
import os
from Model.model import Model
m = Model(print_obj={
# 'start_conf': True,
# 'end_conf': True
"pivot": True,
# "timing": True,
"save_tab": True
})
instance = 'examples/data/newman1'
def read_cpit(dataset):
f = open(dataset + ".cpit", 'r')
c... |
# Generated by Django 2.1.7 on 2019-04-01 01:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0009_auto_20190401_0031'),
]
operations = [
migrations.AddField(
model_name='prof',
name='suffix',
... |
# Degree Array
#http://rosalind.info/problems/deg/
with open('rosalind_deg.txt', 'r') as contents:
edges = [[int(i) for i in c.split(' ')] for c in contents.read().strip().split('\n')]
def getDegrees(edges):
# get the no. of vertices and no. of edges from meta[0] and meta[1] respectively
meta = edges.pop(0)
num_v... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=
"""
File : url_utils.py
Author : Valentin Kuznetsov <vkuznet AT gmail dot com>
Description:
"""
from __future__ import print_function
# system modules
import os
import sys
import urllib
import urllib2
import httplib
import json
def get_key_cert... |
import math
N = input()
N = int(N)
Group_of_students = list(map(int,input().split()))
Group_of_students.sort(reverse = True)
groups = {1: 0, 2: 0, 3: 0,4: 0}
taxis = 0
for i in range(0,N):
groups[Group_of_students[i]] = groups[Group_of_students[i]] + 1
taxis = taxis + groups[4]
groups[4] = 0
m = min(groups[1],grou... |
a = 'dead'
b = 'parrot'
c = 'sketch'
print (a, b, c)
|
#!env python3
# -*- coding: utf-8 -*-
import csv
import trace
nobel_winners = [{
'category': 'physics',
'name': 'Albert Einstein',
'nationality': 'Swiss',
'sex': 'male',
'year': 1921
}, {
'category': 'physics',
'name': 'Paul Dirac',
'nationality': 'British',
'sex': 'male',
'yea... |
#packing dictionary
def packer(**kwargs):
print(kwargs)
print("{first_name} {last_name}".format(**kwargs))
#unpacking dictionary
def unpacker(first_name,last_name,job):
if first_name and last_name:
print("{} {}".format(first_name,last_name))
else:
print(job)
packer(first_name="karen",last_name="ku... |
import raspi_dashboard as rd
rd.start()
|
import math
import vtk
from PythonMetricsCalculator import PerkEvaluatorMetric
# Adapted from: Hofstad et al., A study of psychomotor skills in minimally invasive surgery: what differentiates expert and nonexpert performance, Surgical Endoscopy, 2013.
class BimanualDexterity( PerkEvaluatorMetric ):
# Static methods... |
from flask import Flask, render_template
from datetime import date
app = Flask(__name__)
@app.route('/')
def home():
birthDate = date(2001,11,21)
today = date.today()
status = birthDate.month == today.month and birthDate.day == today.day
return render_template('index.html',status = status)
... |
#coding:utf-8
from dao.dao import Dao
class TaskSerialNumberDao(Dao):
def __init__(self, db, id_, serial_no, project_id, task_id):
self.db = db
self.id_ = id_
self.serial_no = serial_no
self.project_id = project_id
self.task_id = task_id
def get(self):
sql ... |
from tkinter import *
import math as m
#створення вікна
window=Tk()
window.title("olya`s calculator <3")
window.geometry('470x330')
#створення поля вводу
box=Entry(window, width=150,bg='#edd4f0',fg="#fbfbfb",font=("Cambria Math",20))
box.place(x=10,y=10,height=50,width=400)
#створення кнопок
buttons=['=','1','2','3'... |
from tkinter import *
import time
root = Tk()
canv = Canvas (root, width = 600, height = 600)
canv.pack()
from math import *
import time
f = 0
R = 100
g = 0
while True:
g += 0.05
r = g / 360 * 2 * pi
x = 1000
canv.create_rectangle (300 + (R * sin (x * r)) * cos (r), 300 + (R * cos (x * r)) * sin (r),... |
print({"random": 3})
|
# python 2.7.3
import sys
import math
[m, d1, d2] = map(int, sys.stdin.readline().split())
workload = m * d1
# print 'workload is: %d' % workload
if workload % d2 == 0:
n = workload / d2
else:
n = workload / d2 + 1
for i in range(d2):
if workload >= n:
print str(n),
else:
print st... |
# write a program that prints out all the elements of the list that are less than 10.
def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
predicated = [x for x in a if x < 10]
print (predicated)
if __name__ == "__main__":
main() |
from django import forms
from django.forms import ModelForm
from erp_app.models import Customers
class ExpenseForm(forms.Form):
name = forms.CharField(max_length=150)
description = forms.CharField(widget=forms.Textarea(
attrs={'rows':10, 'cols':30}))
date_paid = forms.DateField()
amount_paid = form... |
import copy
import time
from collections import OrderedDict
from operator import itemgetter
import random
class node:
board= None
def __init__(self,mat,level,val,x,y,cr,cc):
self.board = mat
self.depth=level
self.score=val
self.row=x
self.col=y
self.cr... |
from home.url_management.base import BaseUrlRule
from accounts.models import VenueType
class VenueTypesUrlRule(BaseUrlRule):
@classmethod
def create_url(cls, identifier):
url = cls.get_stored_url(identifier)
if not url:
try:
venue_type = VenueType.active_types.get(n... |
# 1. 입력이 빈 문자열인 경우, 빈 문자열을 반환합니다.
# 2. 문자열 w를 두 "균형잡힌 괄호 문자열" u, v로 분리합니다. 단, u는 "균형잡힌 괄호 문자열"로 더 이상 분리할 수 없어야 하며, v는 빈 문자열이 될 수 있습니다.
# 3. 문자열 u가 "올바른 괄호 문자열" 이라면 문자열 v에 대해 1단계부터 다시 수행합니다.
# 3-1. 수행한 결과 문자열을 u에 이어 붙인 후 반환합니다.
# 4. 문자열 u가 "올바른 괄호 문자열"이 아니라면 아래 과정을 수행합니다.
# 4-1. 빈 문자열에 첫 번째 문자로 '('를 붙입니다.
# ... |
#! python3
# To write files and make a directory
import os
# To filter string
import re
# For sleeping
import time
# Googles Text to speech lib
from gtts import gTTS
# File info reader, in this case, it is for determening the length of a mp3
from mutagen.mp3 import MP3
def format_text(text: str):
"""
Rem... |
# Generated by Django 2.0 on 2018-10-03 08:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mili', '0006_check'),
]
operations = [
migrations.DeleteModel(
name='Check',
),
]
|
a = "ㅈ디ㅏㅓ기ㅏㄷ적" \
"wekljrlkwejrklewjr" \
"welkjrlkjerklwejr"
print(a) |
# Generated by Django 3.1.5 on 2021-01-22 08:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cars', '0003_car_photo'),
]
operations = [
migrations.AlterField(
model_name='car',
name='gear',
field=m... |
# question https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
# solution
if __name__ == '__main__':
a = int(input())
b = int(input())
print(f"{a+b}")
print(f"{a-b}")
print(f"{a*b}") |
from http.server import HTTPServer, CGIHTTPRequestHandler
def run(server_class=HTTPServer, handler_class=CGIHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == '__main__':
run()
|
from . import activity, vo2
from measurement.measures import Distance, Mass, Speed
from datetime import timedelta
def calculate_calories_burned(
activity: activity.Activity,
distance: Distance,
bodyweight: Mass,
elevation_gain: Distance,
duration: timedelta
) -> int:
"""
Calculates the ... |
#!/usr/bin/python3
from pyrob.api import *
@task(delay=0.01)
def task_9_3():
x = 1
while not wall_is_on_the_right():
move_right()
x = x + 1
move_left(x - 1)
for i in range(x):
for j in range(x):
if not (i == j or i + j == x - 1):
if i:
... |
s = "I am an NLPer"
def ngram(words, N=2):
d = {}
for idx in range(len(words)):
if idx + N - 1 >= len(words):
continue
key = tuple(words[idx:idx + N])
if key in d:
d[key] += 1
else:
d[key] = 1
return d
print(ngram(s))
print(ngram(s.spl... |
# python 2.7.3
import sys
import math
m_cnt = {}
m_price = {}
for i in range(6):
name = raw_input()
device = raw_input()
price = input()
if device in m_cnt:
m_cnt[device] += 1
if price < m_price[device]:
m_price[device] = price
else:
m_cnt[device] = 1
m_... |
import email
from calendar import timegm
from email.message import EmailMessage
import imaplib
from pteromyini.lib.web.liteemail.liteemail import LiteEmail
from pteromyini.lib.web.liteemail.message import Message
from pteromyini.lib.web.liteemail.parser import EmailBodyParser
from pteromyini.lib.web.liteemail.... |
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("SOURCE", help="String to be decoded")
parser.add_argument("-v","--vigenere",metavar='KEY', help="Decode with vigenere cipher")
parser.add_argument("-b","--binary",metavar='BITS', type=int, help="Decode binary string")
parser.add... |
from pyspark import SparkContext, SparkConf
def parse_line(line):
tokens = line.split(",")
age = tokens[2]
friends = int(tokens[3])
return (age, friends)
if __name__ == "__main__":
conf = SparkConf().setMaster("local").setAppName("key_value")
sc = SparkContext(conf=conf)
lines = sc.textF... |
"""
@File: operate_mongo.py
@CreateTime: 2019/12/10 上午10:09
@Desc: 使用MongoDB数据库
使用链接 https://www.cnblogs.com/aademeng/articles/9779271.html
"""
import pymongo
from bson.objectid import ObjectId
from operate_database.settings import URI, DB_NAME, DOC_NAME, USERNAMR, PASSWORD
class MongoAction(object):
"""
mon... |
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
# Create a new chat bot named Charlie
chatbot = ChatBot(
'Charlie',
trainer='chatterbot.trainers.ListTrainer'
)
chatbot.train(
[
"Hello. How are you?",
"I really like the new album of Shinedown",
"I have already booked a ticket... |
from util.db import DatabaseConnection
import ibm_db
class ItemModel():
def __init__(self, name=None, price=None):
self.name = name
self.price = price
def get_all_item(self):
dbconn=DatabaseConnection()
sql = "SELECT * from ITEM"
lst=[]
try:
conn = db... |
from logger.models import Log
def log_cron(cron, action, data=''):
log = Log(cron=cron, action=action, data=data)
log.save()
def log_mop(mop, action, data=''):
cron = mop.player.cron
log = Log(cron=cron, mop=mop, action=action, data=data)
log.save() |
"""
Analysis dashboards module.
"""
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import copy
from datetime import datetime, timedelta
import json
import logging
import re
import numpy as np
import pandas as pd
from flask_login import login_required
from flask... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.