text stringlengths 38 1.54M |
|---|
"""
Tests for net.ml module
"""
import numpy as np
import tensorflow as tf
import net.ml
def test_get_distance_matrix_op():
"""
Test computing a matrix of distances between all rows permutations of a matrix.
"""
inputs_matrix = np.array([
[1, 3, 5, 7],
[2, 2, 4, 4],
[1.5, -2... |
from pathlib import Path
import requests
data_path = Path('./data')
data_files = {
'summary_listings.csv': r'http://data.insideairbnb.com/united-kingdom/england/london/2021-02-09/visualisations/listings.csv',
'listings.csv.gz': r'http://data.insideairbnb.com/united-kingdom/england/london/2021-02-09/data/listin... |
# Round 1A 2018 - Waffle Choppers
# https://codejam.withgoogle.com/2018/challenges/0000000000007883/dashboard
from pprint import pprint
from typing import Union, List
def get_cuts(grid, num_chocos, num_cuts) -> Union[List[int], bool]:
num_per_row = [
sum(cell == '@' for cell in row)
for row in g... |
import pandas as pd
registro_ventas={"Producto":[],"Cantidad Ventas":[],"Precio":[],"Cliente":[]}
while (True):
respuesta = 1
respuesta_nombre=0
print("MENU PRINCIPAL")
print(" ")
print("[1] Registrar Venta")
print("[2] Consultar Venta")
print("[X] Salir.")
opcion_elegida = inp... |
"""
Plotting Time and Space: Chunk Row
Author: Robert Ross
A child implementation of the Chunk class that represents an entire row
made up of a bunch of smaller chunks.
"""
import numpy as np
import chunk
class Chunk_Row(chunk.Chunk):
"""
The chunk row contains a small ammount of image data and some other
... |
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import shapely
import networkx as nx
import pysal as ps
import random
from matplotlib.colors import ListedColormap
import geopandas as gp
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
cm_bright = Listed... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('persons', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='ngo',
name='flag',
... |
#!/usr/bin/python3
#
# Copyright 2017 Intel Corporation.
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors.
# The Material contains prop... |
import copy
import logging
from abc import ABC
from collections import namedtuple
from enum import Enum
import numpy as np
import open3d as o3d
from hydra.conf import dataclass, MISSING, ConfigStore, field
# Hydra and OmegaConf
from omegaconf import DictConfig, OmegaConf
# Project Imports
from slam.backend import Bac... |
class XhsWebCookie:
def __init__(self):
self.headers = {
'Host': 'www.xiaohongshu.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
'sec-ch-ua-mobile': '?0',
... |
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
class Empty(Instruccion):
def __init__(self, tipo, valor, strGram, linea, columna):
self.valor = None
def ejecutar(self, tabla, arbol):
return None
def getCode(self):
return 'Empty.Empty(None, None, None, 0, 0)'
|
# Generated by Django 3.2 on 2021-02-26 09:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_webpage_pagerank'),
]
operations = [
migrations.AlterField(
model_name='webpage',
name='pagerank',
... |
#--coding: utf-8--
print "How old are you ?",
age=raw_input()
#raw_input輸入框
print "How tall are you?",
height=raw_input()
print "How much do you weight?",
weight=raw_input()
print """So you're %r old , %r tall and %r heavy.""" %(
age , height ,weight
) |
# Workaround for kivy's logging issue (https://stackoverflow.com/questions/36106353/)
import logging
from kivy.logger import Logger
logging.Logger.manager.root = Logger
import os
APP_HOME = os.path.expanduser(os.environ['APP_HOME'])
APP_PATH = os.path.dirname(os.path.abspath(__file__))
def run():
logger = loggi... |
from numpy import *
from numpy.linalg import *
mat = array(eval(input("digite a matriz: ")))
c = mat.shape [1]
mz = zeros((4,4), dtype = int)
for i in range(c):
for j in range(c):
mat[:,j] = sorted(mat[:,j], reverse = True)
print(mat) |
import os
import re
import time
from PIL import Image
from PIL.ExifTags import TAGS
from lol import logger
__author__ = 'samip_000'
from PIL import Image
from PIL.ExifTags import TAGS
#import *
#from imagefuncs import ensure_dir, get_exif_data, get_dt, get_camera, get_uniqueid
def ensure_dir(f):
#print "ensuri... |
import numpy as np
import numpy as np
import plotly
import plotly.plotly as py
from helper import *
import plotly.graph_objs as go
plotly.tools.set_credentials_file(username='dengl11', api_key='STvfIKmz3XwcKtfhlAS4')
naive= [[0.00029206275939941406, 0.09076905250549316], [0.00024509429931640625, 0.04193687438964844],... |
import pickle
import re
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import GaussianNB
import json
from sklearn.pipeline import Pipeline
from sklearn import svm
from sklearn.feature_extraction import Dic... |
import copy
import os
from datetime import datetime
import pestUtil as pu
date_fmt = '%m/%d/%Y'
smp_dir = 'UMD.01\\obsref\\head\\'
smp_files = os.listdir(smp_dir)
start = datetime(1996,1,1,12)
end = datetime(2004,12,31,12)
site_names = []
f = open('misc\\bore_coords.dat','r')
for line in f:
site_names.append(... |
from itertools import chain
from typing import Dict, Iterable, Tuple
from linkedin.learner.ds.feature import Feature
from linkedin.learner.ds.record import TrainingRecord
from linkedin.learner.ds.types import NameTerm
from linkedin.learner.utils.functions import dedupe_preserve_order, flatten
INDEX_MAP_REPR_SEPARATOR... |
name = input("이름이 뭐에요? ")
age = int( input("몇 살이에요? "))
height = float( input("키가 몇이에요? ") )
print("\n이름 : " , name)
print("나이 : " , age)
print("신장 : " , height)
|
# -*- coding: utf-8 -*-
"""
Class for the ogs USER DEFINED TIME CURVES file.
.. currentmodule:: ogs5py.fileclasses.rfd
File Class
^^^^^^^^^^
.. autosummary::
RFD
----
"""
from ogs5py.fileclasses.rfd.core import RFD
__all__ = ["RFD"]
|
# Generated by Django 3.1.1 on 2020-10-13 17:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0008_productreview'),
]
operations = [
migrations.RenameField(
model_name='productre... |
from django.dispatch import Signal
__all__ = ['ipn_processed', 'state_changed']
ipn_processed = Signal(providing_args=['instance'])
state_changed = Signal(providing_args=['instance', 'previous_state'])
|
# Korzystając ze zbioru danych Iris (https://archive.ics.uci.edu/ml/datasets/iris) wygeneruj
# wykres punktowy, gdzie wektor x to wartość ‘sepal length’ a y to ‘sepal width’, dodaj
# paletę kolorów c na przykładzie listingu 6 a parametr s niech będzie wartością absolutną
# z różnicy wartości poszczególnych elementów we... |
# -*- coding:utf-8 -*-
# 算術平均
def mean(xs):
return sum(xs) / len(xs)
def mean2(xs):
return sum(map(lambda x: x/len(xs),xs))
# 幾何平均
def geometric_mean(xs):
multiplicated = 1
for x in xs:
multiplicated = multiplicated * x
return multiplicated ** (1/len(xs))
#調和平均
def harmonic_mean(xs):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 07 14:53:40 2017
@author: luoying.li
"""
import sys
sys.path.append('P:\Python Library')
import xlwings as xw
import pandas as pd
import numpy as np
from DataBaseConnection import DataBaseConnection
from JaiTrader import JaiTrader
from DoubleMA import Doubl... |
import requests
import cv2
from imutils.video.pivideostream import PiVideoStream
import imutils
import time
import numpy as np
base_url = '35.236.20.13'
class VideoCamera(object):
def __init__(self, flip = False):
self.vs = PiVideoStream().start()
self.flip = flip
def __del__(self):
... |
#Python 3.7.x
#https://projecteuler.net/problem=35
"""
There is a deliberate logical error in the code.
Do you understand Python for a long time to find her.
"""
from my_function import primes_list_bw
from my_function import isnotPrime
result_arry = set()
arry = primes_list_bw(1000000)
for k in arry:
kn = len(str(... |
# Generated by Django 3.0.4 on 2020-04-20 16:21
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('location', '0002_auto_20200414_2137'),
('post', '... |
import webbrowser
class Vedio():
def __int__(self,title,duration,director):
self.title = title
self.duration = duration
self.director = director
class Movie(Vedio):
def __init__(self,title,duration,director,imbd_link,movie_storyline,poster_image,trailer_youtube):
#Vedio.__init__... |
import libsimple
print(f"Cython Example. Importing libsimple from {libsimple.__file__}")
print("Calling libsimple.simple_function() once")
print(libsimple.simple_function())
print("Calling libsimple.simple_function() again")
print(libsimple.simple_function()) |
from peachpy import *
from peachpy.x86_64 import *
r = Argument(ptr(const_uint64_t))
bits = Argument(ptr(const_uint64_t))
bits_len = Argument(int64_t)
bits_cap = Argument(int64_t)
hashes = Argument(ptr(const_uint16_t))
hashes_len = Argument(int64_t)
hashes_cap = Argument(int64_t)
with Function("queryCore", (r, bits, ... |
from make_df import make_search_df, merge_dfs
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
PROJ_DIR = os.path.dirname(os.getcwd())
def calc_pca(df):... |
# Version format:
# Release: 1.0.0
# Beta: 1.0.0b1
# Alpha: 1.0.0a1
# Development: 1.0.0.dev0
# Release candidate: 1.0.0rc1
version = "1.0.5"
|
from dataclasses import dataclass
@dataclass
class TimingData:
def __init__(self):
self.time_parsing: float = 0
self.time_creating_secapps: float = 0
self.time_creating_streams: float = 0
self.time_creating_vars_routing: float = 0
self.time_creating_vars_pint: float = 0
... |
'''
https://leetcode.com/explore/interview/card/amazon/80/dynamic-programming/900/
'''
class Solution:
def __init__(self):
self.res = None
def climbStairs(self, n):
return self.climb_stairs_bottom_up(n)
def climb_stairs_topdown_memoize(self, n):
self.results = {}
def helper(n)... |
from django.apps import AppConfig
class GestionpeliculasConfig(AppConfig):
name = 'gestionPeliculas'
|
import yaml
# sudo pip install pyyaml
import re
import random
import smtplib
import datetime
import pytz
import time
import socket
import sys
import getopt
import os
help_message = '''
To use, fill out config.yml with your own participants. You can also specify
DONT-PAIR so that people don't get assigned their signif... |
# -*- coding: utf-8 -*-
"""
文 件 名: get_gray_images.py
文件描述: 获取二进制文件的灰度图像
备 注: 安装capstone库(pip install capstone)
作 者: HeJian
创建日期: 2022.06.14
修改日期:2022.06.14
Copyright (c) 2022 HeJian. All rights reserved.
"""
import subprocess
import os
import numpy as np
from sklearn.ensemble import RandomForestCl... |
languages= {
"en":"english",
"de":"deutsch",
"fr":"français",
"it":"italiano",
"pt":"português",
"es":"español",
"pl":"polski",
"nl":"nederlands",
"ja":"日本語",
"sl":"slovenščina",
"ru":"Русский",
"ko":"한국어",
"id":"Bahasa Indonesia",
"uk":"Українська... |
class MinStack:
def __init__(self):
self.min_stack = []
def push(self, x: int) -> None:
if self.min_stack:
self.min_stack.append((x, min(x, self.min_stack[-1][1])))
else:
self.min_stack.append((x, x))
def pop(self) -> None:
if self.... |
from starlette.requests import Request
from starlette.responses import JSONResponse
class AuthError(Exception):
def __init__(self, error: str, status_code: int):
self.error = error
self.status_code = status_code
async def auth_error_handler(
_: Request,
exc: AuthError,
) -> JSONRe... |
try:
# Try to use setuptools so as to enable support of the special
# "Microsoft Visual C++ Compiler for Python 2.7" (http://aka.ms/vcpython27)
# for building under Windows.
# Note setuptools >= 6.0 is required for this.
from setuptools import setup, Extension
except ImportError:
from distutils.... |
# Copyright 2019 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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.apac... |
#!/usr/bin/env python
#
# Copyright 2011 MERS Technologies.
#
"""Python 2.6/2.7 client library for the Subuno API.
This client library is designed to support the Subuno API. Read more
about the SUBUNO API at subuno.com. You can download this API at
http://github.com/subuno/api/
"""
import urllib, urllib2
import jso... |
"""Greek-specific forms helpers."""
import datetime
import re
from django.forms import CharField, RegexField, ValidationError
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
from stdnum import luhn
class GRPostalCodeField(RegexField):
"""
Greek Postal code f... |
import numpy as np
import pandas as pd
from pydub import AudioSegment
import os
rock_path = r"C:\Users\pravi\Desktop\music4all\Rock_names_FLOP.csv"
rock_csv = pd.read_csv(rock_path)
# print(rock_csv['id'])
mp3 = ".mp3"
mp3_list = []
for i in rock_csv['id']:
k = i + mp3
mp3_list.append(k)
... |
# Author: Denis A. Engemann <denis.engemann@gmail.com>
# License: BSD (3-clause)
from copy import deepcopy
import numpy as np
from mne.report import Report
from mne.preprocessing import ICA, create_ecg_epochs, create_eog_epochs
from mne import pick_types
from mne.utils import logger
from mne.defaults import _handle_... |
import random
# 隨機產生10個 [1:100]的數
nums = []
for i in range(10):
nums.append(int(random.random() * 99 + 1))
# 使用內建排序
nums.sort()
print(nums)
# 歷變搜尋
target = int(input('Enter the target'))
include = False
for i in range(len(nums)):
if (nums[i] == target):
print(i)
include = True
break... |
from django.forms import ModelForm
from .models import Item
class ItemForm(ModelForm):
class Meta:
model = Item
fields = [
"itemname", "itemquantity","itemstatus","date",
]
|
def step_decay_scheduler_generator(initial_lr, coef, epoch_threshold):
return lambda epoch: initial_lr * (coef ** (epoch // epoch_threshold)) |
import sys
import random
import os
import argparse
from pathlib import Path
sys.path.append('./') # to run '$ python *.py' files in subdirectories
from dataloader.utils import kface_accessories_converter, kface_expressions_converter, kface_luces_converter, kface_pose_converter
# We have already created a pair of kfa... |
# coding=utf-8
import sys
import numpy as np
import torch
from alphabet import Alphabet
import cPickle as pickle
from datautils import normalize_word, read_instance, build_pretrain_embedding
START = "</s>"
UNKNOWN = "</unk>"
PADDING = "</pad>"
class Data:
def __init__(self, args):
# Alphabet
s... |
from django.shortcuts import redirect
from django.urls import resolve
from django.utils.deprecation import MiddlewareMixin
class PasswordChangedMiddleware(MiddlewareMixin):
def process_request(self, request):
current_url = resolve(request.path_info).url_name
exempt_urls = ['logout', "change-passw... |
import os
import sys
sys.path.append('..')
sys.path.append('../..')
import argparse
import utils
import networkx as nx
from student_utils import *
"""
======================================================================
Complete the following function.
==============================================================... |
#11-3
class Employee():
def __init__(self,first,last,salary):
self.first = first
self.last = last
self.salary = salary
def give_raise(self,raise_amount=5000):
self.salary += raise_amount
|
import os
import time
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Remove old report export files'
def handle(self, *args, **options):
directory = os.path.join(settings.MEDIA_ROOT, 'export')
if os.path.exists(directory):
now = time... |
import sys
n = int(sys.argv[1])
def printDiamond(nl):
def diamondRes(nl, dir):
if nl == 1:
return [(" " * (n - nl)) + "*" + (" " * (n - nl))]
if dir == "r":
return [
(" " * (n - nl)) + ((2 * nl - 1) * "*") + (" " * (n - nl))
] + ... |
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.layers import Input, LSTM, Dense, Embedding
def make_model(batch_size=None):
maxlen = 10
source = Input(shape=(maxlen,), batch_size=batch_size,
dtype=tf.int32, name='Input')
embedding = Embedding(input_dim=128,
... |
# -*-coding:utf-8-*-
__author__ = 'howie'
import tornado.web
import tornado.escape
from handlers.base import BaseHandler
from spider import allSpider
from controller.dataController import DataController, newsSource
from spider.newsDb.insertNews import newsInsert
from system.classPredict.main import startPredict
from sy... |
from py_imessage import imessage
import bs4
import sys
import requests
import os
os.chdir('') #replace this with the path to your directory of choice.
wiki_page = 'Special:Random'
res = requests.get(f'https://en.wikipedia.org/wiki/{wiki_page}' )
res.raise_for_status()
wiki = bs4.BeautifulSoup(res.text,"html.parser")
... |
def main():
A = [5, 2, 9, 1, 3, 7]
print "UNSORTED: ",A
QuickSort(A,0,len(A)-1)
print "SORTED: ",A
def QuickSort(A, low, high):
if low < high:
pivot = Partition(A,low,high)
QuickSort(A,low,pivot-1)
QuickSort(A,pivot+1,high)
def Partition(A,low,high):
pivot = low
swap (A, pivot, high)
... |
import pandas as pd
import os
import numpy as np
#Once you have the windows data, the last part missing will just be to split the dataframe in windows (and store each dataframe in a dictionary with the right window).
#Import the fingerprinting file with the fp columns
fp_file = pd.read_csv("~/Desktop/Fingerprinting_P... |
from c12_Byte_at_a_time_ECB_decryption_Simple import *
from Crypto.Cipher import AES
from random import randint
import base64
import os
Prefix = os.urandom(randint(8, 48))
def prefix_encryption_oracle(plain):
plain = Prefix+plain
return encryption_oracle(plain)
def find_AAA(encryption_oracle, BLOCK_SI... |
"""View test example."""
from django.test import TestCase
import pytest
from unittest import TestCase
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, RequestFactory, Client
from django.urls import reverse, resolve
from mixer.backend.django import mixer
from timer import vie... |
#!/usr/bin/env python3
from multiprocessing import Queue
import time
import csv
import subprocess
import argparse
from datetime import datetime, timedelta
from dateutil import parser as dateparser
from threading import Thread
from concurrent.futures import ThreadPoolExecutor
import json
#from multiprocessing.pool impor... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View, ListView, DetailView
from django.core.mail import send_mail
from django.contrib.auth.mixins import LoginRequ... |
"""Safely insert runtime arguments into compiled GraphQL queries."""
from .common import insert_arguments_into_query, validate_argument_type |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1911)
def datos():
data = np.loadtxt("data/DR9Q.dat", usecols=(80, 81, 82, 83))
banda_i = data[:, 0] * 3.631
error_i = data[:, 1] * 3.631
banda_z = data[:, 2] * 3.631
error_z = data[:, 3] * 3.631
... |
countryFile = open('countries.txt', 'r')
for lines in countryFile.readlines():
print(lines)
countryFile.close()
countryFile = open('states.txt', 'w')
countryFile.write('\nJapan') |
'''
'''
from .file_object import Database,time_slic
from .daily_analysis import analysis_one,search_candidates,track,Sources
from .daily_analysis import get_light_curve_list
from .plot import Plot_track,Plot_serch
from .save import Save_search,Save_track
|
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import style
from os import path
style.use('ggplot')
rcParams.update({'font.size': 9})
fig, ax = plt.subplots()
df = pd.read_excel('oil_gas_misc_split_percent.xlsx')
mycolors = ['saddlebrown', 'coral', '#ffbf00']
a = df... |
import logging
from miasm2.jitter.jitload import jitter, named_arguments
from miasm2.core import asmblock
from miasm2.core.utils import pck32, upck32
from miasm2.arch.mips32.sem import ir_mips32l, ir_mips32b
from miasm2.jitter.codegen import CGen
from miasm2.ir.ir import AssignBlock, IRBlock
import miasm2.expression.e... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @File : test_hq.py
# @Author: Liaop
# @Date : 2018-08-20
# @Desc : 取行情
from pykafka import KafkaClient
client = KafkaClient('192.168.100.70:9092,192.168.100.71:9092,192.168.100.72:9092')
topic = client.topics[b'market']
consumer = topic.get_simple_consumer()
for msg in ... |
MAX = 9999999999999
import numpy as np
# Initialize a flow in the graph. Arguments are number of nodes, source node, sink node,
# list of Edges, list of variables of cost,capacity and flow for each variable and the flow required
def Compute_Flow_EdmondsKarp(N,source,sink,EdgeList,VarList,f):
Total_Flow = 0
... |
#! /usr/local/bin/python3
import math
import numpy
import sys
from statistics import mean
from tree import Tree
from loss_mle import LossTomographyMle
if len(sys.argv) != 7:
print("Usage: ", sys.argv[0], " depth expt_type mean_delay/loss_prob dist_type num_probes num_trials ")
exit(1)
else:
depth = int(sys.argv... |
import mock
from django.test import TestCase
from django.utils import timezone
from contact_book import constants
from contact_book.tests import factoryboy
class ReceiversTest(TestCase):
@mock.patch('django.utils.timezone.now')
@mock.patch('contact_book.receivers.elastic_search.create_document')
def te... |
import unittest
import os
import pandas as pd
from itertools import cycle
import filecmp
data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
from readpy import write_tsv, write_csv, write_delim
class TestReadTsv(unittest.TestCase):
def setUp(self):
self.diamonds_csv = os.path.... |
class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
mid = (len(arr) - 1) // 2
m = arr[mid]
temp = sorted(arr, key=lambda x: abs(x - m))
temp.reverse()
return temp[:k]
|
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
#similarly we can set minimum length as min_length
email =forms.EmailField(required =False)
message = forms.CharField(widget=forms.Textarea) |
import collections
s = "cdefghmnopqrstuvw"
a = list(s)
count = collections.Counter(a)
d = list(count.values())
flag = 0
stat = 1
for i in d:
if i % 2 == 1 and flag == 0:
flag = 1
elif i%2 == 1 and flag == 1:
stat = 0
break
if stat == 1:
print("YES")
else:
print("NO") |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from sklearn.ensemble import RandomForestRegressor
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.metrics import mean_absolute_error
filename = '../Datasets/maweiweather.csv'
data = pd.read_csv(filename).drop(['日期'], axis=1)
... |
"""
Peidi Xie
April 14th, 2019
Introduction to Programming, Section 03
Part 2a
"""
# function: add_letters
# input: a word to scramble (String) and a number of letters (integer)
# processing: adds a number of random letters (A-Z; a-z) after each letter
# in the supplied word. for example, if word="... |
#DetectChars.py
import os
import cv2
import numpy as np
import math
import random
import Main
import Preprocess
import PossibleChar
import Fare
#Creating a model
kNearest = cv2.ml.KNearest_create()
#Constants for checkIfPossibleChar function
MIN_PIXEL_WIDTH = 2
MIN_PIXEL_HEIGHT = 8
MIN_ASPECT_RATIO = 0.25
MAX_ASPECT... |
def nth_fibonacci(n):
result = 0
for i in range(1, n + 1):
if i == 1 or i == 2:
result = 1
if i > 2:
result = result + nth_fibonacci(i - 2)
return result
|
try:
t=int(input())
if((t%2)==0):
print("Even")
else:
print("Odd")
except:
print("invalid")
|
import random
n = int(input())
a = [0 for i in range(n)]
print(a)
m = int(input())
for i in range(m):
a[i] += 1
for i in range(m,n):
a[i] += 2
print(a)
for i in range(n):
if (len(a) == 1):
break
try:
a[m] += a[m - 1]
a.pop(m - 1)
except IndexEr... |
from collections import defaultdict
#virtual blocks are numbered from 0 to 499
#virtual disk has key as disk and returns list of virtual block
virtualdisk_block=defaultdict(list)
#size of each virtual disk mapping
virtualdisk_size={}
checkpoint_no=0;
#list contain second copy for all block
# 0 if second copy, -1 if no... |
import os
import glob
all_files=sorted(glob.glob('links/*.txt'))
for filepath in all_files:
download = 'python batchloader.py '+filepath
os.system(download)
|
'''
demo_image_filters.py
Demo for testing of a multitude of image processing filters in the image domain
'''
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from image_filters import CalculateISNR, HistEqualization, LocalHistEqualization, \
SpatiallyAdaptiveSmoothingFilt... |
import unittest
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Returns the Node which contains the lca
def findLCARecursive(root, number_1, number_2, found):
if root is None:
return None
if root.key == number_1 :
... |
import socket
import threading
import thread
import SocketServer
import time
import random
import os
import cPickle
import platform
import select
import sys
import errno
# contants
CMD_LIST_ALL = 'list'
CMD_READ = 'read'
CMD_WRITE = 'write'
CMD_BYE = 'bye'
CMD_QUIT = 'quit'
CMD_CONNECT = 'connect'
FOUND = 'FOUND'
NOT... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 11:21:38 2018
@author: zdiveki
"""
import pandas as pd
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model.logistic import LogisticRegression
from sk... |
# Generated by Django 3.1.2 on 2020-10-18 11:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('listings', '0003_auto_20201017_1339'),
]
operations = [
migrations.AlterField(
model_name='listing',
name='bedrooms'... |
import socket
class User:
'Used by the game server to keep track of its clients'
def __init__(self,**kwargs):
self.name = kwargs.get('name')
self.connection = kwargs.get('connection')
self.address = kwargs.get('address')
self.id = kwargs.get('id') #TODO: generate ids
de... |
import numpy as np
import matplotlib.pyplot as plt
N = 6040 # number of users
M = 3952 # number of movies
def read_data():
data = np.zeros((N, M))
f = open("./data/ratings.dat", "r")
lines = f.readlines()
for line in lines:
user, movie, rating, *_ = list(map(int, line.split("::")))
... |
from pyramid.config import ConfigurationError
from pyramid.security import NO_PERMISSION_REQUIRED
from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from .views import Login, Logout, OauthCallback, forbidden
def includeme(config):
"""Include U... |
import pandas as pnds
import gensim
path_train = "/content/MarketBasket/code/order_products__train.csv"
path_prior = "/content/MarketBasket/code/order_products__prior.csv"
path_products = "/content/MarketBasket/code/products.csv"
train_orders = pnds.read_csv(path_train)
prior_orders = pnds.read_csv(path_prior)
produc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.