text stringlengths 38 1.54M |
|---|
import json
import logging
import time
import warnings
from collections import namedtuple
from os.path import join
import torch
from flask import Flask, request
from flask_ngrok import run_with_ngrok
from omegaconf import OmegaConf
from dataset.idDataModule import IdDataModule
from model.idTransformerModel import IdT... |
def solution(N, number):
if number == N:
return 1
dp = [set() for _ in range(8)]
for i in range(8):
dp[i].add(int(str(N) * (i + 1)))
for i in range(1, 8):
for j in range(i):
for num1 in dp[j]:
for num2 in dp[i - j - 1]:
dp[i].add(nu... |
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Kyaw Kyaw", "Zaw Zaw", "Maw Maw") |
from datetime import datetime
# print(dir(datetime))
dt = datetime(year=2021, month=5, day=12) # "dt" is object for date class
dt1 = datetime(year=2021, month=5, day=12, hour=15, minute=10, second=45)
print(dt)
print(dt1)
ct = datetime.now()
print(ct)
print(ct.day)
print(ct.... |
import matplotlib.pyplot as plt
import numpy as np
import lmfit
def gauss_peak_function(pars, x, data=None):
amp = pars['amp'].value
off = pars['off'].value
f_res = pars['f_res'].value
linewidth = pars['linewidth'].value
model = off + amp*np.exp(-((x-f_res)**2)/(2*linewidth**2))
if data is None:
return mode... |
from flask import render_template
from app import app
from app.mars.marsdate import MarsDate
@app.route('/zubrin_calendar')
def zubrin_calendar():
return render_template('zubrin_calendar.html', title='Grid')
@app.route('/')
def calendar_index():
# get todays zubrin calendar date
marsdate = MarsDate()
... |
#!/usr/bin/env python
import math
import numpy
import numpy as np
def temperature_sensor(c_x,c_y,fire_x,fire_y):
value=[]
a=10000
b=6
distance=math.sqrt(pow((c_x - fire_x), 2) + pow((c_y - fire_y), 2))
temperature=a/(distance+b)
value.append(temperature)
return temperature
def create_array(x_grid, y_grid,z_gr... |
# Setter and Property Decorators
# main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
# We use getters & setters to add validation logic around getting and setting a value.
# To avoid direct access of a class field i.e. private variables cannot be accessed directly... |
'''
前几天看了几集斗破苍穹电视剧,突然想重新看看原版小说,奈何只能在网页看,无法下载。
一生气,就把斗破苍穹爬了下来....
'''
import requests
import re
import os
folder_path = 'D:/1/project/car/txt/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
url_qian = 'https://doupocangqiong1.com'
url = 'https://doupocangqiong1.com/1/20.html'
headers =... |
from __future__ import division, print_function
import os
import argparse
import numpy as np
import tensorflow as tf
import scipy
import time
import sys, os
sys.path.append('./wct/')
from utils import preserve_colors_np
from utils import get_files, get_img, get_img_crop, save_img, resize_to, center_crop
from wct impo... |
from tkinter import *
# Cria uma janela simples
class Janela:
def __init__(self, instancia_de_Tk):
pass
raiz=Tk()
Janela(raiz)
raiz.mainloop() |
# blender modules
import bpy
# addon modules
from . import ui
from . import ops
from . import props
from . import preset
from .. import utils
class XRAY_addon_preferences(bpy.types.AddonPreferences):
bl_idname = 'io_scene_xray'
props = props.plugin_preferences_props
if not utils.version.IS_28:
... |
# -*- coding: utf-8 -*-
# 状态表示 集合:所有将a[1~i]变成b[1~j]的操作方式
# 属性:min
# 状态计算
n = int(input().strip())
str_a = input().strip()
m = int(input().strip())
str_b = input().strip()
dp = [[0] * (len(str_b) + 1) for _ in range(len(str_a) + 1)]
for i in range(1, len(str_a) + 1):
dp[i][0] = i
for j in range(1, len(st... |
'''
unit тесты модуля клиента
'''
import time
import unittest
import sys
sys.path.append('../')
from ClientCore.client import Client as client
from Utilitis.errors import *
# тестируем функцию формирования сообщения от клиента
class TestClientCreatePresence(unittest.TestCase):
# action формируется корректно
... |
import calendar
import datetime as dt
import re
def figure_time(str_time):
if not str_time or not str_time.strip():
return None
# strip everything non-numeric and consider hours to be first number
# and minutes - second number
numbers = re.split("\D", str_time)
numbers = filter(lambda x: x... |
'''
@date:13/10/2017
@author:AshrafAbdul
'''
import tensorflow as tf
import numpy as np
import pandas as pd
import tflearn
NSL_KDD_TRAIN = '/home/aabdul/projects/enids/data/NSL-KDD/master/train_cs.csv'
NSL_KDD_VAL = '/home/aabdul/projects/enids/data/NSL-KDD/master/val_cs.csv'
NSL_KDD_TEST = '/home/aabdu... |
# coding=utf-8
import csv
class TextComplexity:
def __init__(self):
pass
text_name = None
author = None
href = None
type = None
Flesch_index = None
percent_of_unique_words = None
avg_term_frequency = None
nouns_percent = None
verbs_percent = None
adjectives_perc... |
def equalStacks(h1, h2, h3):
s1 = [0]
s2 = [0]
s3 = [0]
for i in h1[::-1]:
s1.append(s1[-1] + i)
for i in h2[::-1]:
s2.append(s2[-1] + i)
for i in h3[::-1]:
s3.append(s3[-1] + i)
while True:
if s1[-1] >= s2[-1] and s1[-1] > s3[-1]:
s1.pop(-1)
... |
rs=int(input())
dol=int(input())
euro=int(input())
mindol=dol
mineuro=euro*5
m=0
minde=0
mined=[]
#while(m<=rs//mindol):
# l=rs-mindol*m
# minde.append(l%mineuro)
# m+=1
minde=rs%mindol
n=0
while(n<=rs//mineuro):
k=rs-mineuro*n
mined.append(k%mindol)
n+=1
print(min(minde,min(mined)))
|
from Rotor import _Rotor
class Rotors:
ROTOR_I_CIPHER = 'EKMFLGDQVZNTOWYHXUSPAIBRCJ' # rotor I cipher via the 1930 Enigma I
ROTOR_II_CIPHER = 'AJDKSIRUXBLHWTMCQGZNPYFVOE' # rotor II cipher via the 1930 Enigma I
ROTOR_III_CIPHER = 'BDFHJLCPRTXVZNYEIWGAKMUSQO' # rotor III cipher via the 1930 Enig... |
import os
from dask.distributed import Client, as_completed
import sys
# Get the directory containing the script
test_dir = os.path.dirname(__file__)
# Add BLM and test directory to file path
sys.path.insert(0, test_dir)
sys.path.insert(0, os.path.dirname(test_dir))
# Import test generation and cleanup
from genera... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
START_DT = datetime(2018,5,8,10)
default_args = {
'owner': 'cdwanze',
'depends_on_past': False,
'start_date': START_DT... |
from django.contrib import admin
from .models import Evaluation
admin.site.register(Evaluation)
|
########################################################################################################################
## Mabrains Company LLC
##
## Mabrains Via Generator for Skywaters 130nm
########################################################################################################################
from ... |
from Player import *
print('Team A')
player1 = Player('Jens')
player1.set_birtdate('29-05-1989')
player2 = Player('Brage')
player2.set_birtdate('29-05-2000')
player2.player_info(player1)
player1.player_info(player2)
|
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.cross_validation import ShuffleSplit
from sklearn import metrics
from sklearn.cross_validation import cross_val_score
from sklearn.naive_bayes impo... |
from app import db
class EdgeType(db.Model):
__tablename__ = 'edge_type'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(120), unique = True, nullable = False)
description = db.column(db.Text)
def __init__(self, name, description):
self.id = id
... |
import torch
import unittest
from decomp import UDSCorpus
from event_type_induction.modules.induction import (
EventTypeInductionModel,
FactorGraph,
LikelihoodFactorNode,
PriorFactorNode,
VariableNode,
VariableType,
)
from event_type_induction.modules.likelihood import (
Likelihood,
Pre... |
"""Build commands for VBSP and VRAD."""
from pathlib import Path
from PyInstaller.utils.hooks import collect_submodules
import contextlib
import pkgutil
import os
import sys
# THe BEE2 modules cannot be imported inside the spec files.
WIN = sys.platform.startswith('win')
MAC = sys.platform.startswith('darwin')
LINUX ... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import json
from unittest import TestCase
import mock
from django.template import RequestContext
from django.template import Template
from rest_framework.test import APITestCase
from kolibri.core.cont... |
import sys
from os import listdir, mkdir
from os.path import isfile, join, exists
import re
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifi... |
# -*- coding: utf-8 -*-
"""
Factories to build Vertex and Edge model for Directed Acyclic Graph structure.
"""
from django.db import models
from closuredag.models import VertexBase
def edge_factory(vertex_model,
child_to_field="id",
parent_to_field="id",
concrete=T... |
from tkinter import *
from tkinter import ttk, messagebox
from dao.db_init_dao import DBInitDao
from dao.db_source_dao import DBSourceDao
from ui.win_db_mgmt import DataSourceMgmtWindow
from ui.win_table_choice import TableChoiceWindow
from utils.window_util import WindowUtil
class HomeWindow:
def __init__(self,... |
# List qualities
[1, 2, 3] is not [3, 2, 1] # Ordered
['cat', 5, (4, 2), 2.5, True] # Can contain any type of data
[1, 2, 3, 4, 5].append([6]) # Mutable
# Swapping elements in a list
# Can you understand why this is buggy?
def swap_elements_buggy(elem1, elem2):
temp = elem1
elem1 = elem2
elem2 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from sklearn.externals import joblib
import pandas as pd
from load_dataset import processing_null
from load_dataset import load_dataset
import os
from ctb_mysql import CMySql
#数据预处理
def test(line):
text_classifier = joblib.load('text_classifier.pkl')
content=text_classifier.p... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.utils.http import is_safe_url
from django.conf import settings
from .models import Student, Project
ALLOWED_HOSTS = settings.ALLOWED_HOSTS
# Create your views here.
def home_view(request, *args, **kwargs):
... |
import requests
from bs4 import BeautifulSoup
import re
import xlwt
data = requests.get("http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery11240949503730119142_1561385255779&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCOIATC&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C.2&st... |
import redis
import rediscluster
# For standalone use.
DUPEFILTER_KEY = 'dupefilter:%(timestamp)s'
PIPELINE_KEY = '%(spider)s:items'
REDIS_CLS = redis.StrictRedis
REDIS_ENCODING = 'utf-8'
# Sane connection defaults.
REDIS_PARAMS = {
'socket_timeout': 30,
'socket_connect_timeout': 30,
'retry_on_timeout': ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2019, Abdó Roig-Maranges <abdo.roig@gmail.com>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE fi... |
from constants import *
import pygame
class Paddle:
def __init__(self, name, x, player_count):
self.id = player_count
self.name = name
self.x = x
self.y = WINDOW_HEIGHT / 2 - 50
self.rect = pygame.Rect(self.x, self.y, 20, 100)
def draw(self, win):
pygame.draw.r... |
from flask import Flask
from pymongo import MongoClient
app = Flask('MusiCon', template_folder= "./app/templates", static_folder='./app/static')
db = MongoClient('localhost',27017)
from models.features import features
features_collection = features().getall()
import routes |
"""
Solution for 1296. Divide Array in Sets of K Consecutive Numbers
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
"""
from collections import Counter
from typing import List
class Solution:
"""
Runtime: 460 ms, faster than 64.18% of Python3 online submissions for Divide Array in Set... |
#return L, assignments, post
#cholupdate() defined outside
import numpy as np
import scipy
import scipy.linalg as sl
import math
from logsumexp import logsumexp
def gaussian_dpmixture_gibbsstep(X, assignments, prior, post):
##post: posteriors
#N sample
(N,dim) = np.shape(X)
#assignments = np.zeros... |
print(str(5))
print(str(5.6))
print(int("5"))
print(str(True))
print(bool("True"))
print(len([1, 2, 4, 6, 8, 66, 88, 44, 89, 67]))
print(len([1,2,4,6 ]))
print(len("HELLO"))
print(len(["HELLO", "Sumit"]))
print(sorted([1,5,33,765,32,11,2,8888,454,67]))
print(sorted(["B", "R", "C", "G"]))
print(sorted(["B", "R", "C", ... |
'''
This script uses Python's `contextlib.contextmanager`
to allow for easier readability of code.
Credits to Stefan Schnell for setting up the baseline code.
https://blogs.sap.com/2017/09/19/how-to-use-sap-gui-scripting-inside-python-programming-language/
'''
from contextlib import contextmanager
import win32com.cli... |
# Generated by Django 3.1.6 on 2021-07-22 05:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0003_subcategory'),
]
operations = [
migrations.CreateModel(
name='Product',
... |
#coding=utf-8
import requests
import time
import random
import sys
from urllib import parse
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-f... |
import sys
import hashlib
def hashfile_sha256(file): """Program to calculate the md5 and sha256 hash"""
# An arbitrary (but fixed) buffer size (change accordingly)
# 65536 = 65536 bytes = 64 kilobytes
BUF_SIZE = 65536
# Initializing the sha256() method
sha256 = hashlib.sha256()
# O... |
# python字符串
# name = 'wangdawei'
# 字符串 拼接
# print('欢迎 ' + name + ' 光临!')
# 多个参数
# print('欢迎', name, '光临!')
# 占位符
# print('欢迎 %s 光临!' % name)
# 字符串格式化
# print(f'欢迎 { name } 光临!')
# 布尔值Ture相当于1,False相当于0
# None 空值
# type() 用来检查值的类型
# print(type(1))
# print(type(1.5))
# print(type(True))
# print(type('wang'))
# print(t... |
# !/usr/bin/python/env
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.contrib.auth import forms as auth_forms
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.auth.tokens import default_token_g... |
from django.urls import re_path, path
from apps.order.views import OrderPlaceView, OrderCommitView, OrderPayView, CheckPayView, CommentView, OrderDelete
app_name = 'order'
urlpatterns = [
path('place', OrderPlaceView.as_view(), name='place'), # 提交订单页面显示
path('commit', OrderCommitView.as_view(), name='commit'... |
import pytest
from selenium.webdriver import DesiredCapabilities
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# @pytest.fixture(scope="function")
# def browser():
# grid_url = "http://localhost:4444/wd/hub"
# desired_caps = DesiredCapabilities.CHROME
# browser = w... |
#!/usr/bin/env python
""" http://wiki.dominionstrategy.com/index.php/Coven """
import unittest
from dominion import Game, Card, Piles
import dominion.Card as Card
###############################################################################
class Card_Coven(Card.Card):
def __init__(self):
Card.Card.__i... |
import os
from flask import Flask, request, render_template,url_for,Blueprint
from flask_cors import CORS, cross_origin
import shutil
import models.braintumor.src.predict as predict
import base64
import numpy as np
from io import BytesIO
#brainapp = Flask(__name__)
brainapp=Blueprint("brainapp",__name__,template_folde... |
import setuptools
from distutils.core import setup
setuptools.setup(
name = 'fenics_wrinkle',
version = '0.1',
packages = setuptools.find_packages(),
)
|
import logging
from pathlib import Path
from bs4 import BeautifulSoup
from fluidtopics.connector import ResourceBuilder
from antidot.connector.html.neo_topics import NeoTopic
LOGGER = logging.getLogger(__name__)
class HtmlToTopics:
def __init__(self, html_splitter, render_cover_page=False):
self.path =... |
from IPython import embed
import sys
import numpy as np
import pickle
import os.path
import os
from collections import defaultdict
from inverse_dynamics import LearnInverseDynamics
from rs_baseline import RandomSearchBaseline
from cma_baseline import CMABaseline
import curriculum as cur
DIR_FMT = 'data/{}/'
N_EVAL_TR... |
from flask import Flask, url_for, request, redirect, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
sched = BackgroundScheduler()
trigger = CronTrigger(hour='0', minute='5')
app = Flask(__name__)
app.config.from_object('config')
# db... |
'''
#x = 5
if x == 5:
print('Equals 5')
if x > 4:
print('Greater than 4')
#x = 5
if x < 10:
print('Smaller')
if x > 20:
print('Bigger')
print('Finis')
#x = 5
if x == 5:
print('Equals 5')
if x > 4:
print('Greater than 4')
if x >= 5:
print('Greater than or Equals 5')
if x < 6: print('Less t... |
import sqlite3
class Database:
def __init__(self):
connect = sqlite3.connect('db/SQLite.db')
cursor = connect.cursor()
self.connection = connect
self.cursor = cursor |
# Import the Libraries
import streamlit as st
import pickle
import pandas as pd
# Nice Concrete Photo
from PIL import Image
im = Image.open("taylor-smith-PJMKu7RQNJ8-unsplash.jpg")
st.image(im, width = 700, caption = "by Taylor Smith, unsplash.com")
# App Title
html_temp = """
<div style="background-color:blue;pad... |
'''
13. col1.txtとcol2.txtをマージ
12で作ったcol1.txtとcol2.txtを結合し,元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.
確認にはpasteコマンドを用いよ.
'''
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_file1")
parser.add_argument("input_file2")
parser.add_argument("output_file")
args = parser.parse_args()
# 読み込み
with ope... |
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render
from lib.RSA import RSA
from lib.Resource import Resource
from datetime import datetime
import PyPDF2
import PythonMagick
import json
import urllib
import hashlib
import sys
import os
import time
if sys.versio... |
import math
num = int(input('Digite um numero '))
raiz = math.sqrt(num)
print ('Raiz de {} é igual a {}'.format(num,raiz)) |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
# This progr... |
from future.utils import string_types
from . import colors
from .palette import get_color
from .styles import Style
class InvalidStyleError(Exception):
pass
ATTRIBUTE_NAME_MAP = {
"bold": "bold",
"strong": "bold",
"bright": "bold",
"dim": "dim",
"italic": "italic",
"strike": "strike",
... |
from django.shortcuts import render, redirect
from .models import *
def index(request):
# if already logged in
if request.session.get('uid'):
return redirect('/home')
else:
return render(request, 'index.html')
def login(request):
# when added to session, user is considered 'logged in... |
class Matrix(object):
def __init__(self, matrix_string):
self.matrix_int = []
for row in [i.split(' ') for i in matrix_string.splitlines()]:
self.matrix_int.append([int(i) for i in row])
def row(self, index):
return self.matrix_int[index]
def column(self, index):
... |
import time
from collections import defaultdict
ms = time.time()*1000
x = [
178, 135, 78, 181, 137, 16, 74, 11, 142, 109, 148, 108, 151, 184, 121, 58, 110, 52, 169, 128, 2, 119, 38, 136, 25, 26, 73, 157, 153, 7, 19, 160, 4, 80, 10, 51, 1, 131, 55, 86, 87, 21, 46, 88, 173, 71, 64, 114, 120, 167, 172, 145, 130, 33, 20, ... |
"""
Calculating the average execution time of a function
"""
import time
# decorator as a function
def time_this(num_runs):
# num_runs - number of repeats of the function
def decorator(func):
def wrapper(*arg, **kwarg):
# arg & kwarg needed in case if function has parameters
avg... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# $Id: forms.py 425 2009-07-14 03:43:01Z tobias $
# ----------------------------------------------------------------------------
#
# Copyright (C) 2008-2009 Caktus Consulting Group, LLC
#
# This file is part of ... |
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.0.125'
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
led_pins = [18, 24, 25]
led_states = [0, 0, 0]
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
def html_for_led(led):
l = str(led)
r... |
# We often need to make decision based certain factors.
# Imagine checking if someone is allowed to ride a rollercoaster:
#
# Are they older than 18?
# If so, then they can definitely ride it
# In Python
print('Can you ride this rollercoaster?')
age = int(input('What is your age?: '))
if age > 18:
print('Definite... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#caculate the repeated times according source .
import os
import sys
from utils.urlutils import UrlUtils
class Processor():
def __init__(self):
self.counts = {}
self.lines = {}
def process(self, file_path):
if not os.path.exists(file_path... |
from math import log
from statistics import stdev
class Variant( object ):
def __init__( self, position, ancestral, substitution, coverage, frequency, totalCounts ):
self.position = position
self.ancestral = ancestral
self.substitution = substitution
self.coverage = list()
... |
#!/usr/bin/env python
"""
Setup script for circleclient.
"""
import os
import sys
from setuptools import setup, find_packages
from codecs import open
this_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_dir, 'README.rst'), encoding='utf-8') as f:
LONG_DESCRIPTION = '\n' + f.read()... |
import os
import glob
import numpy as np
from shutil import copyfile
def shuffle_and_move_images(IMAGES_DIR, DATA_HOME_DIR):
g = glob(IMAGES_DIR + '*.jpg')
shuf = np.random.permutation(g)
for i in range(2000):
os.rename(shuf[i], DATA_HOME_DIR+'/valid/' + shuf[i])
def shuffle_and_copy_images(IMA... |
# -*- coding: utf-8 -*-
import logging
from lncrawl.core.crawler import Crawler
logger = logging.getLogger(__name__)
class IdqidianCrawler(Crawler):
base_url = "https://www.idqidian.us/"
def read_novel_info(self):
logger.debug("Visiting %s", self.novel_url)
soup = self.get_soup(self.novel_ur... |
# %%
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns
from kneed import KneeLocator
var1="Beauty%"
var2="Baby%"
df = pd.read_csv("ulabox_orders_with_categories_partials_2017.csv")
dfp = df[[var1, var2]]
ssd = []
ks = range(1,11)
for k in range(1,11):
k... |
import itertools
s = 0
for i in range(2,200000):
a = [int(x) for x in str(i)]
a = reduce(lambda x,y: x+y**5, a, 0)
if i == a:
print a
s += a
print s
|
import os, numpy, arcpy, time
from multiprocessing import Process, Queue, current_process, freeze_support
def elapsed_time(t):
""" Return a string of format 'hh:mm:ss', representing time elapsed between
t (generally: t = time.time()) and funcion call.
Result rounded to nearest second"""
... |
#!/usr/bin/env python3
from scripts.basis import logger
from threading import Thread
import logging
import subprocess
import sys
# #
# redirect stdout, stderr to logger
#
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, l... |
import json
import os
import socket
import struct
i = 0
while 1:
print('---------receive {} files: {}'.format(i ,i))
ip_port = ('', 12345)
sk = socket.socket()
sk.bind(ip_port)
sk.listen()
buffer = 1024
conn, addr = sk.accept()
pack_len = conn.recv(4)
head_len = struct.unpack('i', ... |
# TWO
# +TWO
# ------
# FOUR
#
import constraint
problem = constraint.Problem()
# Definisemo promenljive i njihove vrednosti
problem.addVariables("TF",range(1,10))
problem.addVariables("WOUR",range(10))
# Definisemo ogranicenje za cifre
def o(t, w, o, f, u, r):
if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*... |
# -*- coding: utf-8 -*-
"""Functions to read from existing JSON files"""
import json
from .config import QUANTITIES, find_by_key
from .adsorbates import AdsorbateWithControls
CATEGORY_CONV = [('exp', 'Experiment'), ('sim', 'Simulation'), ('mod', 'Modeling'), ('ils', 'Interlaboratory Study'),
('qua', ... |
'''
Impementing queue with 2 stacks
Using list data structure
'''
class Queue():
def __init__(self):
self.stack1 = [] #Using for enqueue
self.stack2 = [] #Using for dequeue
def enqueue(self, item):
self.stack1.append(item)
print("Item {} added to stack".fo... |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Generator(nn.Module):
def __init__(self):
super(Generator,... |
# m报数
def lastRemaining(n, m):
if n < 1 or m < 1:
return -1
# 初始值
temp = 0
# 对n进行迭代
for i in range(1,n+1):
# 套公式
temp = (temp + m) % i
return temp
print(lastRemaining(10,12))
print(lastRemaining(10,123))
|
from tkinter import *
from tkinter import ttk, messagebox
from eveplanner.config.configuration_reader import ConfigurationReader
from eveplanner.eveapi_wrapper.character_wrapper import CharacterWrapper
from eveplanner.eveapi.cache_handler import CacheHandler
from eveplanner.eveapi_wrapper.eve_wrapper import EveWrapper... |
"""
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`calendar.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should... |
# Create a function called make_operation, which takes in a simple arithmetic operator as a first parameter
# (to keep things simple let it only be ‘+’, ‘-’ or ‘*’) and an arbitrary number of arguments (only numbers)
# as the second parameter. Then return the sum or product of all the numbers in the arbitrary parameter... |
import requests
import json
class Fanyi:
def __init__(self, query_string):
self.url = "https://fanyi.baidu.com/basetrans"
self.query_string = query_string
self.headers = {
'User-Agent': 'Mozilla/5.0 (iPhone;CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML,... |
import copy
import pickle
from block_gen import Block, Event, gen_dummy_block
from typing import List
from simple_rollup import generate_rollup
def test_generate_rollup():
l1_chain: List[Block] = []
expected_l2_chain: List[Block] = []
for i in range(100):
block = gen_dummy_block(i)
expecte... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import qrcode
import barcode
from qrcode.constants import ERROR_CORRECT_L
from qrcode.constants import ERROR_CORRECT_M
from qrcode.constants import ERROR_CORRECT_Q
from qrcode.constants import ERROR_CORRECT_H
from barcode.writer import ImageWriter
__ec_levels__ ... |
from Classes.Main import MainClass
class UserClass(MainClass):
def __init__(self, data):
self.data = data
def columns(self):
return ['user_email','user_password','login_count']
def values(self, id):
return (self.data['Email'],'20eabe5d64b0e216796e834f52d61fd0b70332fc',1)... |
# Aidan O'Connor - G00364756 - 22/03/2018
# Programming_Project - Investigate the iris data set and
# create analysis based on research previously conducted
# References:
# Link to csv file = https://archive.ics.uci.edu/ml/datasets/iris
# Below code adapted from following link = https://www.geeksforgeeks.org/g... |
from tkinter import *
def imprima_mes():
print(radioValue)
app = Tk()
app.geometry('300x300')
radioValue = IntVar()
rdioOne = Radiobutton(app, text='Enero',
variable=radioValue, value=1)
rdioTwo = Radiobutton(app, text='Febrero',
variable=rad... |
import os
import subprocess
import pexpect
import logging
from PySide2 import QtCore, QtWidgets, QtGui, Qt
from mainwindow import Ui_MainWindow
from .login_window import Login
logger = logging.getLogger(__name__)
common_error = "Error occurred.\nFor more information, view the log file."
US_C = "US Central"
US = "US... |
num=int(input("enter the number of rows:\n"))
n_list=[[0 for x in range(num)] for y in range(num)]
n=1
low=0
high=num-1
count=int((num+1)/2)
for i in range(count):
for j in range(low,high+1):
n_list[i][j]=n
n=n+1
for j in range(low+1,high+1):
n_list[j][high]=n
n=n+1
for j in ... |
import unittest
import mincut as mc
class TestMinCut(unittest.TestCase):
def test_can_contract(self):
testdict = {1:[2,3],2:[1,3],3:[1,2]}
mc.contract(testdict)
self.assertTrue(len(testdict) < 3)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.