text stringlengths 8 6.05M |
|---|
import tensorflow as tf
import numpy as np
xy = np.loadtxt('xor.txt', unpack=True)
x_data = xy[0:-1]
y_data = xy[-1]
print (x_data)
print (y_data)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
W = tf.Variable(tf.random_uniform([1, len(x_data)], -1. , 1.))
h = tf.matmul(W, X)
hypothesis = tf.div(1... |
SAFE_ZONE = 7
WIDTH_IN_BLOCKS = 31
HEIGHT_IN_BLOCKS = 12
|
# -*- coding: utf-8 -*-
# @Author: Fallen
# @Date: 2020-04-03 21:44:14
# @Last Modified by: Fallen
# @Last Modified time: 2020-04-03 21:53:36
#2.键盘输入多个人名保存到一个列表中,如果里面有重复的则提示此姓名已经存在
def func():
name = []
while True:
temp = input("输入名字(输入'q'退出):")
if temp.lower()=="q":
return nam... |
import pandas as pd
import numpy as np
from tqdm import tqdm
import os
import math
directory = os.fsencode('../data/csv/')
list_df=[]
for file in os.listdir(directory):
filename = os.fsdecode(file)
df=pd.read_csv(os.path.join('../data/csv/', filename))
if(df.shape[0]!=0):
list_df.append(df)
#df=pd.read_csv("..... |
from functools import lru_cache
from typing import Dict
def fib1(n:int) -> int:
return fib1(n-1) + fib1(n-2)
def fib2(n:int) -> int:
if n <= 2:
return n
return fib2(n - 1) + fib2(n -2)
memo: Dict[int, int] = {0: 0, 1: 1}
def fib3(n: int) -> int:
if n not in memo:
memo[n] = fib3(n... |
from __future__ import division
import sys
import csv
import pandas as pd
import numpy as np
import re
import math
"""
fill missing age data
"""
if __name__ == '__main__':
# finding out average of age according to "Mr.","Mrs.", etc. and store it in "age_grp_avg"
known = ['Miss.','Mrs.','Mr.','Master.']
age_grp =... |
from django.urls import path
from .views import home,product_single,category_product,about,contact,SearchView
urlpatterns = [
path('',home,name='home'),
path('about/',about, name='about'),
path('contact/',contact, name='contact_dat'),
path('product/<int:id>/',product_single,name='product_single'),
... |
import torch
from fairseq.data import data_utils
import numpy as np
from fairseq.data.language_pair_dataset import FairseqDataset
from tqdm import tqdm
def collate(
samples, pad_idx, eos_idx, word_max_length, left_pad_source=True, left_pad_target=False,
input_feeding=True,
):
if len(samples) == 0... |
def is_partition(G, communities): ...
|
suits = ["heart", "diamond", "spade", "club"]
cards = ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"]
class Card:
def __init__(self, _suit, _value):
self.suit = _suit
self.value = _value
def get_suit(self):
return suits[self.sui... |
import os
import numpy as np
import yaml
import math
from PIL import Image
import pandas as pd
import skimage
from skimage.morphology import remove_small_objects, remove_small_holes, disk
from skimage.filters import rank, threshold_otsu
from skimage.transform import resize
import scipy.ndimage as ndimage
from scipy.ndi... |
from gevent import * |
#-*- coding:utf-8 -*-
import httplib,urllib
from html import search_result
class ishare_client():
def __init__(self):
self.cookie = ""
self.base_url = "ishare.iask.sina.com.cn"
self.search_url = "http://ishare.iask.sina.com.cn/search.php?key=%s&format=%s"
self.down_page_url = "/dow... |
#!/usr/bin/python3
cities = ["san fran", "new york", "chicago", "dallas"]
for i, city in enumerate(cities):
print(i, city)
|
#!/usr/bin/python
import sys
import os
import urllib2
import config
def get_url(dist, section, arch):
repo = config.REPOS[dist]
return '%(base)s/dists/%(dist)s/%(section)s/binary-%(arch)s/Packages.gz' % \
dict(base=config.BASE_URLS[repo],
dist=dist,
section=section,
... |
# Generated by Django 2.2.2 on 2019-06-18 18:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='book',
name='language',
fie... |
class LinkedList:
def __init__(self, node):
self.node = node
def add(self, next_node):
node = self.node
while node.next:
node = node.next
node.next = next_node
def remove(self, value):
node = self.node
if node.value == value:
self.nod... |
from hage.Multiply import Main4
from hage.Minus import Main2
from hage.Plus import Main1
from hage.Division import Main3
class Main(Main1,Main2,Main3,Main4):
def __init__(self, q1, q2, v):
self.q1 = q1
self.q2 = q2
self.v = v
def show(self):
vvod = (self.q1 + self.q2 + sel... |
#!/usr/bin/env python2.6
#
# Copyright (c) Members of the EGEE Collaboration. 2006-2009.
# See http://www.eu-egee.org/partners/ for details on the copyright holders.
#
# 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 ... |
from __future__ import division
import numpy as np
import numpy.random as npr
from scipy.stats import multivariate_normal as mvn
from svae.lds.synthetic_data import generate_data, rand_lds
from lds_inference_alt import filter_forward
from test_util import bmat
npr.seed(0)
### util
def get_n(lds):
return lds[0... |
# -*- coding: utf-8 -*-
# Алиса владеет интересной информацией, которую хочет заполучить Боб.
# Алиса умна, поэтому она хранит свою информацию в зашифрованном файле.
# У Алисы плохая память, поэтому она хранит все свои пароли в открытом виде в текстовом файле.
# Бобу удалось завладеть зашифрованным файлом с интересной... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
################################################################################
# Практичне завдання № 3.2
# Програма має розраховувати числа послідовності Фібоначчі.
# Послідовність Фібоначчі... |
import numpy as np
from keras.callbacks import Callback
from keras.optimizers import SGD
from keras.models import Sequential
from keras.layers import Dense
from scipy.stats import logistic
from copy import deepcopy, copy
from sklearn.metrics import r2_score, explained_variance_score
from keras import backend as K
from ... |
#!/usr/bin/python2.7
#coding=utf8
r'''
Fuction: wrapper of multitask.py with threading
Created: Tuyj
Created date:2015/02/07
'''
if __name__ == '__main__': import _env
import t_com as t_com
import multitask
from multitask import Queue,recvfrom,Timeout,sleep,recv,read,send,sendto
import types
import threading,signal
im... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# validate_op_limits.py: compare the current op_limits.db to the standard #
# ... |
#!/usr/bin/env python3
"""Executes a SSM Document which captures in S3 a list of all installed packages for selected hosts."""
import time
import logging
import os
import csv
import datetime
import json
import boto3
from botocore.exceptions import ClientError
from tabulate import tabulate
from utils import (
config... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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 ap... |
# Given a m * n matrix mat of ones (representing soldiers) and zeros
# (representing civilians), return the indexes of the k weakest rows
# in the matrix ordered from the weakest to the strongest.
#
# A row i is weaker than row j, if the number of soldiers in row i is
# less than the number of soldiers i... |
#!/usr/bin/env python
import pyspark
import sys
from operator import add
from operator import itemgetter
import random
zone = ["TKO", "SKM", "QRC", "Tai Ko", "North Point", "Fanling", "Lam Tin", "HBT", "Tai Po"]
def get_district(zone):
if( zone == "TKO" or zone == "SKM" or zone == "Fanling" or zone == "Tai Po" )... |
#!/usr/bin/env python3
import os
from tempfile import gettempdir
from torchvision import datasets
from torchvision import transforms
from tqdm import tqdm
import numpy as np
import torch.nn as nn
import torch
from eval_history import EvalHistoryFile
from utils import freeze, new_classifier, new_processor, apply_trans... |
Marks = {
"math" : 90,
"chemistry" : 100,
"physics" : 100,
"hindi" : 95,
"english" : 89
}
# minimum marks
print(min(Marks.values()))
# maximum Marks
print(max(Marks.values()))
# average marks
print(sum(Marks.values()) / len(Marks.values())) |
c = 0
for x in range(0, 5):
v = float(input())
if v % 2 == 0:
c += 1
print('{} valores pares'.format(c)) |
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
import cv2
from PIL import Image
class ElasticTransform(object):
@classmethod
def generate(cls, image, alpha_factor, sigma_factor, random_state=None):
open_cv_image = np.array(... |
from types import SimpleNamespace
import boto3
from treadmill.infra import constants
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
resource = kwargs.get(
'resource',
(constants.EC2 if (len(args) == 0) else args[0])
)
instance_resour... |
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import selectivesearch
import cv2
def AlpacaDB(img):
"""
Generate bounding box and show images with them
:param img: image to process
:return: nothing
"""
img_lbl, regions = selectivesearch.selective_search(
img, sca... |
#!/usr/bin/python3
"""
Copyright (c) 2015, Joshua Saxe
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 list of con... |
#All information
'''import boto3
client = boto3.client('ec2')
Myec2=client.describe_instances()
print(Myec2)
#Instances information
import boto3
client = boto3.client('ec2')
Myec2=client.describe_instances()
for pythonins in Myec2['Reservations']:
print(pythonins)
#Instance ID
import boto3
client = boto3.client('ec2... |
from .BaseBrush import BaseBrush
from .controls.BooleanControl import BooleanControl
from bsp.leveleditor import LEUtils
from panda3d.core import Point3
class TetrahedronBrush(BaseBrush):
Name = "Tetrahedron"
def __init__(self):
BaseBrush.__init__(self)
self.useCentroid = self.addControl(Bo... |
import json,os,time,pickle,time
import numpy as np
import scipy.io.wavfile as wavfile
import librosa
from PIL import Image
MEL_N = 40
WAV_T = (32*2) #2s
def compute_log_mel_fbank_fromsig(signal, sample_rate,n=80):
MEL_N = n
# 3.分帧
frame_size, frame_stride = 0.032, 0.032
frame_length, frame_step = in... |
# Generated by Django 3.0.3 on 2020-07-29 05:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('Device', '0003_auto_20200727_1225'),
]
operations = [
migrations.CreateModel(
... |
from styx_msgs.msg import TrafficLight
from sim_model import SimModel
from real_model import RealModel
import os
import cv2
import time
class TLClassifier(object):
def __init__(self, scenario):
#if scenario == "sim":
#self.model = SimModel()
#else:
self.model = RealModel("light_clas... |
import os
import config
import zipfile
from kaggle.api.kaggle_api_extended import KaggleApi
api = KaggleApi()
api.authenticate()
print('Downloading data ...')
api.competition_download_files('lish-moa',path=os.path.join(config.ROOT_DIR,'input'))
with zipfile.ZipFile(os.path.join(config.ROOT_DIR,'input','lish-moa.zip... |
number = int(input('Please type a number:'))
if number % 2 == 0:
print('{} is even number'.format(number))
else:
print('{} is a odd number'.format(number))
|
# gone/typesys.py
'''
Gone Type System
================
This file implements basic features of the Gone type system. There is
a lot of flexibility possible here, but the best strategy might be to
not overthink the problem. At least not at first. Here are the
minimal basic requirements:
1. Types have names (e.g., 'i... |
#!/usr/bin/env python3
"""Show the current job queue.
"""
import qmk_redis
print('*** There are %s jobs on the queue.' % (len(qmk_redis.rq.jobs)))
for i, job in enumerate(qmk_redis.rq.jobs):
print()
if job.func_name == 'qmk_compiler.compile_firmware':
args = ', '.join([str(arg) for arg in job.args[:3]... |
import math
import gym
from gym import spaces, logger
from random import seed
from random import randint
from PIL import Image
from gym.utils import seeding
import numpy as np
from numpy import asarray
import cv2
def init_map(size, num_obs, border_size):
# Drawing a empty map
global_map = np.one... |
import tensorflow as tf
class PearsonCorrelationCoefficient(object):
def __init__(self, sess=tf.Session()):
"""
Compute the pairwise Pearson Correlation Coefficient (https://bit.ly/2ipHb9y)
using TensorFlow (http://www.tensorflow.org) framework.
:param sess a Tensorflow session
... |
import pyautogui
import cv2
import pytesseract
import os
import time
import numpy as np
from utils.image import image_resize
import PIL.ImageGrab
# The order of the colors is blue, green, red
lower_color = np.array([124, 132, 80])
upper_color = np.array([182, 255, 120])
# take a screenshot of the screen and store it ... |
import tkinter as tk
from tkinter.messagebox import showinfo
import tkinter.filedialog as filedialog
import os
fileName = ''
def author():
showinfo('作者信息', '该Note是由Yanbin完成')
def copyRight():
showinfo('版权信息', '该Note归属于Yanbin\n个人博客:blog.luoyanbin.cn')
def open_file():
global fileName
fileName = f... |
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, PROJECT_ROOT)
sys.path.insert(0, os.path.join(PROJECT_ROOT, '..'))
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'mosbius.settings'
application = WSGIHandler()
|
# Generated by Django 2.0.5 on 2018-06-19 08:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('calculation', '0026_auto_20180618_1214'),
]
operations = [
migrations.AlterUniqueTogether(
name='contractor',
unique_togethe... |
from sklearn.datasets import *
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
def average(x):
""" x is a collection of numbers """
return sum(x) / len(x)
def standardize(x):
""" we ... |
from sentence_splitter import SentenceSplitter, split_text_into_sentences
import argparse
import nltk
def post_proc(lines):
import re
new_lines = []
for l in lines:
new_l = nltk.sent_tokenize(l)
new_l = [l for l in new_l if len(l) > 0]
new_lines += new_l
return new_lines
def ... |
#MatthewMascolo.py
#I pledge my honor that I have abided
#by the Stevens Honor System. Matthew Mascolo
#
#This program takes a list of New York Knicks players
#and staff in Before.txt, then it capitalizes all
#players' first and last names and prints them out in After.txt
def main():
inFile = 'Before.txt'
... |
from django.shortcuts import render
from django.forms.models import model_to_dict
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework import generics
from nba_news.models import NbaNews
from nba_news.serializers import NbaNewsSerializer
from datetime import datetime
import subproce... |
list_of_insults = [
"fart smeller"
, "I can't tell if I'm talking to your face or your asshole"
, "dickweed"
, "buttpirate"
, "douchenozzle"
, "bitch"
, "dick"
, "jackass"
, "turtledick"
, "shut your cockholster"
, "fudgepacker"
, "I think you'd be in hufflepuff"
, "w... |
def lowercase_count(strng):
return sum(a.islower() for a in strng)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 17:22:55 2020
@author: thomas
"""
#Import modules
import numpy as np
import pandas as pd
import os, sys
import time as t
import matplotlib as mpl
import pathlib
import copy
#CONSTANTS
cwd_PYTHON = os.getcwd() + '/'
#config = sys.argv[1]
Re = sy... |
# try to ingest some candidates
import astropy.units as u
from astropy.time import Time
import marshaltools
avro_id = '634445152015015010'
# use wisely
#avro_ids = [
# 634209464915015007, 634313330115015002, 634242335115015022, 628140190315015023,
# 634209464415015033, 634258942115015000, 627195522015015005... |
from state import myenv
from ops import mine, ProjTask
import schemas
class rollback(ProjTask):
def work(self, *args, **kw):
schema = schemas.Cap(myenv.home)
curr = schema.current_release()
prev = schema.get_previous()
schema.switch_current_to(prev)
mine("rm -rf '%s'" % cu... |
from common.run_method import RunMethod
import allure
@allure.step("极题库")
def questionMaterial_uploadImages_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认... |
import os
from authomatic.providers import oauth2, oauth2, openid
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
#aut... |
import click
import screed
import tempfile
import sys
import os
from Bio import SeqIO
def estimate_num_reads(input_file, num_reads, lines_per_read):
""" Return int estimate of reads"""
fd, path = tempfile.mkstemp()
try:
with os.fdopen(fd, 'w') as tmp:
with open(input_file) as fasta:
... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.experimental.helm.register import rules as helm_rules
from pants.backend.experimental.helm.register import target_types as helm_targe... |
#! /usr/bin/env python
from numpy import ma
from numpy.lib.function_base import append
import open3d
import numpy as np
from ctypes import * # convert float to uint32
import tf
import rospy
from std_msgs.msg import Header, String, Float64MultiArray
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import ... |
def getPrime(n):
ret = n
if n == 0 or n == 1:
return
if n == 2 or n == 3:
return ret
for i in range(3, n+1, 2):
for j in range(3, n, 2):
a = i%j
if a == 0:
break
else:
ret = i
break
return... |
N=eval(input())
M=N
i=1
while N>0:
a='*'*i
print('{0:^{1}}'.format(a,M))
#槽{}内嵌套槽{}需要指定各个槽对应的format中的变量序号
#print(a.center((M+1)//2))为什么这里用center函数不行
N-=2
i+=2
|
"""
Output related helper functions
"""
import re
from colorama import Fore, Back, Style
def style_reset():
"""Resets all font colors"""
print(Style.RESET_ALL)
def write_header(filename, match_count):
"""Outputs the filename and number of matches"""
print(Back.WHITE)
print(Fore.BLACK)
prin... |
import argparse
from functions.rename import main
parser = argparse.ArgumentParser()
parser.add_argument('a', type=str, help='rename directory')
args = parser.parse_args()
main(args.a)
|
import copy
with open("input.txt") as f:
data = f.readlines()
data = [int(n.strip()) for n in data]
# Define the search area
start = 0
end = 25
target = 104054607 # The number from part 1
# First get rid of any numbers that are bigger than the target
smaller_data = [n for n in data if n < target]
# Reverse... |
class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
#分治, 递归
ans = []
for i in range(0, len(input)):
if input[i]=='*' or input[i]=='+' or input[i]=='-':
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute... |
from flask_restful import Resource
from flask import request
from auth.mail_manager import generate_email_token, email_verify
from exception import MyException
class EmailToken(Resource):
@classmethod
def post(cls):
data = request.get_json()
if not data:
raise MyException('field ca... |
import operations.negative as negative
from color.grayscale import GrayscaleMatrix
from operations.convolution import ConvolutionMask
from operations.convolution import convolve
def normalize(value, lowerBound, upperBound):
return (value - lowerBound) / (upperBound - lowerBound)
def apply(matrix, mask):
res... |
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('',views.home ,name='home'),
path('cart/',views.cart ,name='cart'),
path('update_add/<slug>',views.update_add ,name='update_add'),
path('update_remove/<slug>',views.update_remove ,... |
import time
from djikstrasto import *
def askdata(): #Kysytään datan sisältävän tiedoston nimi
txt = ".txt"
print("Anna datan sisältävän .txt tiedoston nimi (ilman päätettä!):")
file = input("> ")
filename = file+txt
try:
data = open(filename, "r") #avataan tiedosto, jos sellainen löytyy annetulla... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
f = request.files['file']
f.save('test.txt')
return 'アップロードされました'
@app.route('/upload-fil... |
import string
import random
import requests
import os
import numpy as np
import re
def get_mapping():
char_set = list(string.ascii_lowercase)
shuffled_char_set = char_set.copy()
random.shuffle(shuffled_char_set)
true_mapping = {}
for key, value in zip(char_set, shuffled_char_set):
true_ma... |
#!/proj/sot/ska3/flight/bin/python
#############################################################################
# #
# update_limit_table.py: update html limit table for display #
# ... |
N = int(input())
while N != 0:
mp = {}
for _ in range(N):
line = input()
name = line.split()[0]
for food in line.split()[1:]:
l = mp.get(food, [])
l.append(name)
mp[food] = l
foods = list(mp.keys())
foods.sort()
for food in foods:
... |
# SPDX-License-Identifier: 0BSD
# Copyright 2018 Alexander Kozhevnikov <mentalisttraceur@gmail.com>
"""Raise exceptions with a function instead of a statement.
Provides a minimal, clean and portable interface for raising exceptions
with all the advantages of functions over syntax.
Note:
This is the "no traceback... |
from itertools import groupby
def repeating_fractions(numerator, denominator):
integer, fractional = str(numerator / float(denominator)).split('.')
grouped = []
for k, g in groupby(fractional):
try:
next(g)
next(g)
grouped.append('({})'.format(k))
except... |
from loss import *
from optimizer import *
import numpy as np
losses = {'mse': mse, 'ce': ce}
sgd = SGD()
class FNN:
''' Full-connection Neural Network
It is a simple network with multiple layers
'''
def __init__(self, input_dim=1):
self.layers = []
self.input_dim = input_dim
... |
from office365.runtime.client_value import ClientValue
class GroupProfile(ClientValue):
def __init__(self, name):
"""
:param str name: Group name
"""
super(GroupProfile, self).__init__()
self.mailNickname = name
self.displayName = name
self.description = No... |
#!/usr/bin/python
'''
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0... |
import asyncio
from unittest.mock import Mock
import pytest
from .context import initial_bot_state
@pytest.mark.asyncio
async def test_expand():
bot = initial_bot_state([])
bot.can_build_building = Mock(return_value=True)
expand_stub = Mock(return_value=None)
bot.expand_now = asyncio.coroutine(expan... |
# coding: utf-8
# In[41]:
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import numpy as np
# In[42]:
def sigmoid_activation(x):
return 1.0/(1+np.exp(-x))
# In[43]:
def predict(X,... |
from PySide2.QtCore import QObject, Signal
from time import sleep, time
from random import randint
from freebitcoin.API import API
from helpers.RucaptchaAPI import RucaptchaAPI
class User(QObject):
signal_update_column_color = Signal(int, list)
signal_update_column_text = Signal(int, str)
signal_update_c... |
# https://wikidocs.net/28
class Cookie:
pass
a = Cookie()
b = Cookie()
print(a)
print(b)
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
return self.first + ... |
import cv2
import sys
import os
import logging as log
import datetime as dt
from time import sleep
import time
import click
import platform
def get_lock_screen_cmd():
cmd_dict = {
'Linux' : 'gnome-screensaver-command --lock &',
'Darwin': '/System/Library/CoreServices/Menu\ Extras/user.menu/Content... |
#cash register
#Ayo Akinrinade 08.12.18
cs = 0
ff = 0
h = 0
s = 0
sd = 0
md = 0
ld = 0
ss = 0
ms = 0
cashier_name = input("Cashier Name: ")
print("------Cash Register------")
print("=========================")
print("Cashier: %s" % cashier_name)
print("1. Chicken Strips - $3.50")
print("2. French Fries - $2.50")
pr... |
import pandas as pd
import numpy as np
from prepare import *
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import svm
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.gaussian_process.kernels import... |
from networkx import read_graphml
from rate_card import generate_rate_card
import argparse
def main(rate_card_path, graph_path) -> float:
"""
Calculates total cost of graph based on a graphml file and a rate card csv
:param rate_card_path: path to rate card csv
:type rate_card_path: str, Path
:pa... |
#!/usr/bin/env python
# coding: utf-8
import tornado.ioloop
import tornado.web
import requests
import json
__author__ = 'linyang95#aol.com'
__version__ = '0.1.0'
def net_post(uri, payload):
return requests.post(uri, data=payload)
class MainHandler(tornado.web.RequestHandler):
def prepare(self):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as tud
from torch.nn.parameter import Parameter
from collections import Counter
import numpy as np
import random
import math
import pandas as pd
import scipy
import sklearn
from sklearn.metrics.pairwise import cosine_similarity... |
# coding: utf-8
import urllib.parse
import functools
import lglass.rpsl
class Database(object):
"""Database is an abstract class which defines some constants and setter/getter
for subscripts. You have to extend from it by creating a new class and
overriding __init__, get, list, find, save and delete to conform to... |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
def f(x):
# Function
return np.cos(x) - x
def f_(x):
# Derivative of the function
return - np.sin(x) - 1
def get_next_x(x):
# Approximate a new x value using Newton's Method (Newton Raphson)
return x - f_(x)
if __name__ == '__main__':
X = ... |
import requests
import json
import time
import argparse
import datetime
import numpy as np
import pandas as pd
import os
from bs4 import BeautifulSoup
def setup():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--cookies", help="add cookies", required=True)
args = parser.parse_args()
re... |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import pandas as pd
import numpy as np
from pandas import DataFrame
from bitstring import BitArray
import os
import re
# In[4]:
Data=pd.read_csv('C:\\Users\\sarah\\Desktop\\Udemy\\Pythoncourse\\FakeData.csv')
# In[5]:
Data
# In[6]:
#the goal is to build The ... |
# Clock interrupt
enable_interrupt(0)
# Keyboard interrupt
enable_interrupt(1)
|
aHTMLLinks = ["https://tim.blog/derek-sivers-reloaded-on-the-tim-ferriss-show-transcript/",
"https://tim.blog/daymond-john-on-the-tim-ferriss-show-transcript/",
"https://tim.blog/edward-norton-on-the-tim-ferriss-show-transcript/",
"https://tim.blog/naval-ravikant-on-the-tim-ferriss-show-transcript/",
"https://tim.blog/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.