text stringlengths 38 1.54M |
|---|
import matplotlib.pyplot as plt
import numpy as np
# 本节主要给 点做标识, 加上注解
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure(num=1, figsize=(8, 5))
# 设置取值范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel("i am x")
plt.ylabel("i am y")
# 这里要加 逗号,否则 plt.legend(handles=[l1, l2], loc='best') 中会报错
# plot 是画线... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
class MLP_G(nn.Module):
def __init__(self, isize, nz, nc, ngf, ngpu):
super(MLP_G, self).__init__()
self.ngpu = ngp... |
#! /bin/env python
import time
start = time.clock()
print("Starting at time " + str(start))
from mpi4py import MPI
import models
import sys
from pypdevs.simulator import Simulator, loadCheckpoint
model = models.AutoDistChain(3, totalAtomics=500, iterations=1)
sim = Simulator(model)
sim.setAllowLocalReinit(True)
sim.... |
import ahocorasick
def build_auto(F):
auto = ahocorasick.Automaton()
for f in F:
auto.add_word(f, f)
auto.make_automaton()
return auto
def is_substring(auto, w):
for _, _ in auto.iter(w):
return True
return False
def find_occurrences(auto, w):
occurrences = []
for end_idx, found in auto.iter(w):
occurr... |
import threading
import server
import argparse
import json
import time
import globs
import neighbor
import miner
from node import Node
from wallet import Wallet
# set flags
parser = argparse.ArgumentParser()
# parser.add_argument("host", type=str, help="host")
# parser.add_argument("port", type=int, help="port")
par... |
# Software Name: MOON
# Version: 5.4
# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors
# SPDX-License-Identifier: Apache-2.0
# This software is distributed under the 'Apache License 2.0',
# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'
# or see the "LI... |
'''
Created on Oct 31, 2014
@author: huunguye
paper: k-Nearest Neighbors in Uncertain Graphs (VLDB'10)
'''
import time
from random import *
import math
import networkx as nx
import scipy.io
from numpy import *
import numpy as np
from itertools import chain, combinations
from distance_constraint_reachab... |
import configparser
import os as _os
import json
class Configuration:
def __init__(self):
self.__config_file_name = 'config.ini'
self.__config_ini = configparser.ConfigParser()
self.__log_filter_hash_id_list = []
self.__node_data = {}
pass
def __do_init(self):
... |
from dataclasses import dataclass
from app.utilities.data import Data, Prefab
from app.data.weapons import WexpGain
@dataclass
class Klass(Prefab):
nid: str = None
name: str = None
desc: str = ""
tier: int = 1
movement_group: str = None
promotes_from: str = None
turns_into: list = None
... |
from django.db import models
# Create your models here.
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.timezone import datetime
from datetime import timedelta
class QuestionManager(models.Manager):
def mnew(self):
return self.order_by('-added_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-05-16 06:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comercial', '0012_auto_20180427_2305'),
]
operations = [
migrations.AlterFi... |
# Uses python3
import sys
import collections
def fast_count_segments(starts, ends, points):
count = [0] * len(points)
#write your code here
left, point_label, right = (1,2,3)
point_map = collections.defaultdict(set)
pairs = []
for i in starts:
pairs.append((i, left))
... |
# -*- coding: utf-8 -*-
__author__ = 'Sergio Sanchez Castell '
__version__ = 'v_2.0'
__email__ = "sergio.tendi[at]gmail[dot]com"
__status__ = "Production"
import tweepy
import ConfigParser
import sys
import argparse
import datetime
from time import sleep, strftime, time
from neo4j.v1 import GraphDatabase, basic_auth
... |
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import numpy as np
import argparse
import cv2
import imutils
import json
import requests
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
... |
import sys
import csv
filename = 'examples/csv/monty_python.csv'
if len(sys.argv) == 2:
filename = sys.argv[1]
people = []
with open(filename) as fh:
reader = csv.DictReader(fh)
for line in reader:
people.append(line)
print(people[1]['fname'])
|
import builtins
from .curry import curry
@curry
def filter(f, itr):
try:
_ = iter(itr)
except TypeError:
itr = []
return builtins.filter(f, itr) |
from typing import Dict, Tuple
from raiden.transfer.state import NettingChannelState, NetworkState, RouteState
from raiden.utils.typing import Address, ChannelID, List, NodeNetworkStateMap, TokenNetworkAddress
def filter_reachable_routes(
route_states: List[RouteState], nodeaddresses_to_networkstates: NodeNetwor... |
__author__ = 'Шелест Леонид Викторович'
"""
Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив,
заданный случайными числами на промежутке [-100; 100).
Вывести на экран исходный и отсортированный массивы.
"""
import hw_07 as lib
def bubble_sort(nsl: list) -> list:
"""
classic sortin... |
class Solution:
def reverseString(self, s):
l, r = 0, len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return s
if __name__ == '__main__':
a = ["h", "e", "l", "l", "o"]
s = Solution()
res = s.reverseString(a)
print(res)
|
import matplotlib.pyplot as plt
import numpy as np
import sys
tiles_fn = sys.argv[1]
data = np.fromfile(open(tiles_fn), dtype=np.uint8, sep=' ').reshape((256, 16))
btt_fn = sys.argv[2]
btt = np.fromfile(open(btt_fn), dtype=np.uint8, sep=' ').reshape((32, 32))
tiles = [
np.unpackbits(datum).reshape((16, 8))
... |
from selenium import webdriver as WD
from selenium.webdriver.common.action_chains import ActionChains as AC
# setting up driver
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = WD.Chrome(PATH)
driver.get('https://orteil.dashnet.org/cookieclicker/')
driver.implicitly_wait(10) # for initial loading
click... |
# coding=utf-8
# Modifications Copyright 2021 The PlenOctree Authors.
# Original Copyright 2021 The Google Research Authors.
#
# 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... |
import yaml
import os
from six.moves import urllib
download_cfg = yaml.safe_load(open('semantic_config.yaml'))
url = download_cfg["DATASET"]["DOWNLOAD_URL"]
model_path = download_cfg['DATASET']['DOWNLOAD_DIR']
tar_name = download_cfg["DATASET"]["TARBALL_NAME"]
if not os.path.exists(model_path):
os.makedirs(model... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Complain(models.Model):
name = models.CharField(max_length=50)
phone_no = models.IntegerField()
complain = models.TextField()
date_posted = models.DateTimeField(default=t... |
# reverse an array
def reverse_array(arr: list) -> list:
start = 0
end = len(arr) - 1
while start < end:
# arr[start] = arr[end]
# arr[end] = arr[start]
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
print(reverse_array([1,2... |
#https://github.com/niklasf/python-chess
import chess
import chess.uci
import chess.pgn
import chess.polyglot
import csv
import random
import hashlib
import math
import base64
from eval_moves import fen_plus_move, move_history_to_fen
#TODO: lots of unused code here, try to remove it
#Read in a pgn list of games and ... |
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from .data_source import get_yiyan
yiyan = on_command("一言", rule=to_me(), priority=5)
@yiyan.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
m... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 13:18:04 2019
@author: christophermasferrer
"""
#Christopher Masferrer
#EE 381
#Lab 5
import numpy as np
import matplotlib.pyplot as plt
import random as r
import math as m
N = 1200000
mu = 45
sig = 3
B = np.random.normal(mu,sig,N)
def sSiz... |
def climb(n):
operations = []
resultados = [1]
while n != 1:
if n%2 == 0:
operations.append("a")
n = n/2
else:
operations.append("b")
n = (n-1)/2
operations.reverse()
for option in operations:
if option == "a":
... |
# -*- coding: utf-8 -*-
#
# Copyright 2020-2023 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
# -*- coding: utf-8 -*-
from lxml import html
import urllib
class Movie:
title = ''
org_title = ''
director = ''
writer = ''
genres = ''
producer = ''
release_year = ''
description = ''
rate = ''
def print_all(self):
print "title: ", self.title
print "org_title:... |
import copy
from lxml import etree, objectify
from .mixins import Node
from .utils import classproperty
# class PsBase(MixinRepr):
# def append(self, _name, _value=None, **kwargs):
# node = PsNode(_name, _value, **kwargs)
# self._xml.append(node._xml)
# return self
# def delete(self... |
'''
Title: Implementation of 'Pong' playing agent using Deep Q-Networks
File: video_animation.py
Description: Implementation of video player and slider using cv2
Company: Artificial Intelligence Research Institute (AIRI)
Author: Channy Hong
'''
import Tkinter as tk
import cv2
import numpy as np
from PIL import Image, ... |
import os
from django.config.urls import HpptResponse
import string
def translate_text_to_urls(text):
resps = text
return text
|
# import the necessary packages
from mrcnn.config import Config
from mrcnn import model as modellib
import numpy as np
import cv2
def remove_transparan(inputan_gambar,gambar_transparan,lokasi):
class myMaskRCNNConfig(Config):
# give the configuration a recognizable name
NAME = "MaskRCNN_inference"... |
import argparse
import codecs
import os
import re
import sys
from collections import namedtuple
from logging import getLogger
from merger.lrc_wirter import lrc_writer
from merger.time_utils import parse_ms, parse_time
logger = getLogger()
__author__ = 'wistful'
__version__ = '0.6'
__release_date__ = "04/06/2013"
SU... |
import graphene
from ...wishlist import models
from ..core.connection import CountableDjangoObjectType
class Wishlist(CountableDjangoObjectType):
class Meta:
only_fields = ["id", "created_at", "items"]
description = "Wishlist item."
interfaces = [graphene.relay.Node]
model = model... |
from botocore.client import BaseClient
from ..key_store import KeyStore
from ..raw import CryptoBytes
class CryptoClient(object):
def __init__(
self,
client: BaseClient,
key_store: KeyStore,
) -> None:
self._client = client
self._crypto_bytes = CryptoBytes(
... |
from django.db import models
from django.utils import timezone
class ProductModel(models.Model):
segment = models.CharField(max_length=255)
country = models.CharField(max_length=255)
product = models.CharField(max_length=255)
units = models.IntegerField()
sales = models.IntegerField()
date_sol... |
## This file is part of Scapy
## Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
## 2015, 2016 Maxence Tury
## This program is published under a GPLv2 license
"""
This is a register for DH groups from RFC 3526 and RFC 4306.
XXX These groups (and the ones from RFC 7919) should be registered to
the cry... |
from torchtext import data
from torchtext import datasets
from transformers import BertTokenizerFast
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import Dataset, DataLoader
import torch
TEXT = data.Field()
LABEL = data.Field()
train, test = datasets.IMDB.splits(TEXT, LABEL)
train, va... |
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 7766
# connect to the server on local computer
s.connect(('192.168.137.241', port))
# receive data from the server
stri="Python send this laskjdflaksdf fasldfjsadlfkas dfasldfkjas... |
# -*- coding: cp1250 -*-
"""
/***************************************************************************
pogoda
A QGIS plugin
pogoda
-------------------
begin : 2015-01-21
git sha : $Format:%H$
copyrig... |
from operationscore.Behavior import *
import util.Geo as Geo
class PedTrack(Behavior):
def processResponse(self, sensor, recurs):
ret = []
if self['MaxIntensity'] != None:
maxIntensity = self['MaxIntensity']
else:
maxIntensity = 10
if recurs:
outp... |
from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# if len(nums) != len(set(nums)):
# return True
# return False
"""
Improve by using less checking
"""
# numsDic = {}
# for item in nums:
# ... |
#! /usr/bin/python3.6
import logging
import sys
import random
import string
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/srv/')
from app import app as application
secret = ''
for i in range(2048):
secret+=random.choice(string.ascii_letters+string.digits+string.punctuation)
application.secret_key = s... |
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.shortcuts import render_to_response
#from django.contrib.auth import login, logout, authenticate
from django.contrib.auth import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
url = 'http://httpbin.org/post'
params = {
"name": "fcjiang",
"age": 12
}
headers = {
'User-agent': 'none/ofyourbusiness',
'Spam': 'Eggs'
}
resp = requests.post(url, data=params, headers=headers);
print(resp.text)
print("=================... |
# -*- coding: utf-8 -*-
from EXOSIMS.SurveySimulation.linearJScheduler_sotoSS import linearJScheduler_sotoSS
import logging
import numpy as np
import astropy.units as u
import time
import copy
Logger = logging.getLogger(__name__)
class linearJScheduler_DDPC_sotoSS(linearJScheduler_sotoSS):
"""linearJScheduler_DD... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 02:55:48 2019
@author: VIVEK VISHAN
"""
# 2D lists & Nasted Loops
number_grid = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[3][0])
number_grid = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
... |
# Utilities to acquire files
from . import fsUtils as fs
from . import msgUtils as msg
from . import exeUtils as exe
from ..config import settings
import os
from collections import namedtuple
import hashlib
import ftplib
## Tdo
###############################################################################
acquire... |
import re, sys, csv, pprint
from icecream import ic
from beartype import beartype
from typing import Tuple
from collections import OrderedDict, defaultdict
from dateutil import parser
type_hierarchy = {None: -1, 'text': 0, 'bool': 1, 'int': 2, 'float': 3, 'datetime': 4, 'date': 4} # Ranked by test stringency
def te... |
from consumer import PikaClient
from homalogger import logger
import json
class PikaPublisher(PikaClient):
"""
Class used for publishing messages to message bus
Attributes
----------
dl_queue: str
name of the deadletter queue
exchange: str
name of the exchange that we want to ... |
import pika
import json
from pymongo import MongoClient
from urllib.request import urlopen
from bson import ObjectId
import dateutil.parser
import schedule
import time
import datetime
import requests
import pytz
tz = pytz.timezone("Europe/Amsterdam")
last_executed_datetime = datetime.datetime.now(tz=tz)
print("it is ... |
from http.server import *
from http.client import *
import sys
import requests
# get port and name of board file from arguments
port = int(sys.argv[1])
board = sys.argv[2]
w, h = 10, 10;
board = [[0 for x in range(w)] for y in range(h)]
cCount = 0
bCount = 0
rCount = 0
sCount = 0
dCount = 0
#reads the txt file into an... |
# Generated by Django 3.0.5 on 2020-04-17 09:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('login', '0005_auto_20200417_1723'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={'ordering': ['-c_ti... |
import cookielib,mechanize
b=mechanize.Browser()
b.set_handle_robots(False)
c=cookielib.LWPCookieJar()
b.set_cookiejar(c)
url=raw_input('Enter url (In form of http:// or https://) :http')
url='http'+url
op=b.open(url)
print '\n',c
|
import threading
import time
import pyaudio
from Queue import Queue
from math import ceil
from pydub import AudioSegment
def lookup_device_index(audio_manager, device_name):
info = audio_manager.get_host_api_info_by_index(0)
num_devices = info.get('deviceCount')
for device_id in range(0, num_devices):
... |
with open('moby_clean.txt') as file:
obj = file.readlines()
ans = []
for i in obj:
for j in i.split():
ans.append(j)
print(sorted(set(ans), key=ans.count)[::-1][:5])
print(sorted(set(ans), key=ans.count)[:5])
|
## 프랙탈 도형을 그리는 문제이다.
import sys
def stars(star):
matrix = []
for i in range(3 * len(star)):
if i // len(star) == 1:
matrix.append(star[i % len(star)] + ' ' * len(star) + star[i % len(star)])
else:
matrix.append(star[i % len(star)] * 3)
return list(matrix)
star = [... |
# Write a Python program to count the number of even and odd numbers from a series of
# numbers.
number=[9,8,97,4,3,535,35,35,33,4]
odd=0
even=0
for i in range(len(number)):
k=number[i]
if k%2 == 0:even=even+1
if k%2 != 0:odd=odd+1
print('Number of odd numbers is',odd)
print('Number of even numbers is',even... |
import mxnet as mx
import numpy as np
from rcnn.config import config
class LogLossMetric(mx.metric.EvalMetric):
def __init__(self):
super(LogLossMetric, self).__init__('LogLoss')
def update(self, labels, preds):
pred_cls = preds[0].asnumpy()
label = labels[0].asnumpy().astype('int32'... |
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
ans = []
for intv in intervals:
if intv[0] < toBeRemoved[0]:
if toBeRemoved[0] >= intv[1]:
ans.append(intv)
else:
... |
from cards import Deck
import random
def min_trump_suit(trump_suit, a_deck): # арг-ы функции: метод choose_trump_suit и a_deck,карты игрока
all_trump_suit_cards = []
for i in a_deck.deck: # a_deck is not a list, is not iterable, a_deck._deck IS a list, it's iterable
if i.suit == trump_s... |
import numpy as np
import seaborn as sns
import typer
from analysis.mixed.generate_table import get_df
from analysis.plot import plot
cli = typer.Typer()
MODEL = {"autoencoder": "Autoenkoder", "wavenet": "WaveNet", "segan": "SEGAN"}
@cli.command()
def plot_mixed(
pattern: str = "models/**/mix*/metadata.json",
... |
from django.test import TestCase
from .models import Event
class EventTestCase(TestCase):
def setUp(self):
evnt1 = Event.objects.create(event_type="evnttest", is_cached=True)
self.id1 = evnt1.id
def test_event_property(self):
evnt1 = Event.objects.get(id=self.id1)
self.assert... |
# Generated by Django 3.1 on 2020-08-06 18:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0004_city_country'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='image',
... |
# Generated by Django 2.2.2 on 2019-07-18 08:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CrawlerApp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='BaseUrlImages',
fields=[
... |
import cv2
# Gary level
img=cv2.imread("galaxy.jpg",0)
# color level
# img=cv2.imread("galaxy.jpg",1)
print(type(img))
print(img)
print(img.shape) #resolution
print(img.ndim) #dimension
resized_image=cv2.resize(img,(int(img.shape[1]/2),int(img.shape[0]/2)))
# cv2.imwrite("Galaxy_resized.jpg", resized_image)
cv2.imsh... |
import csv
from typing import List, Tuple, Dict
from arg.perspectives.basic_analysis import predict_by_elastic_search
from arg.perspectives.classification_header import get_file_path
from arg.perspectives.load import get_claim_perspective_id_dict, load_dev_claim_ids, get_claims_from_ids, \
load_test_claim_ids
from... |
# Generated by Django 2.2.8 on 2020-01-30 08:36
import autoslug.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blogs', '0003_auto_20200130_1127'),
]
operations = [
migrations.AlterField(
model_name='post',
name='... |
from libs.effects.effect import Effect # pylint: disable=E0611, E0401
from scipy.ndimage.filters import gaussian_filter1d
import numpy as np
class EffectAdvancedScroll(Effect):
def __init__(self, device):
# Call the constructor of the base class.
super(EffectAdvancedScroll, self).__init__(device... |
#!/usr/bin/python
import sys,re
# Quick way to see if an acronym is in the acrobase.txt file
# ----------------------------------------------------------
# ./check.py MHZ
# ./check.py NAFTA CEO CPU
# ./check.py NOTINHERE 73
# Once a term is tested, you can enter one or more new terms.
# Each time you do, the acrobas... |
from flask import Flask
from flask import request
from flask import jsonify
app = Flask(__name__)
list_of_dict = []
@app.route("/")
def hello():
return "Hello World!"
@app.route('/users', methods=['POST']) # curl -i -X POST http://127.0.0.1:5000/users -d "name=foo"
def add_users():
""" Add a user and ret... |
import os
import sys
sys.path.append("../")
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_
from torch.utils.tensorboard import SummaryWriter
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
from utils imp... |
from django.contrib import admin
# Register your models here.
from check_phone.models import User, Price, Request
admin.site.register(User)
admin.site.register(Price)
admin.site.register(Request) |
# coding: utf-8
from flask_migrate import MigrateCommand
from wanhe import create_app
from flask_script import Manager
app = create_app()
manager = Manager(app=app)
manager.add_command('db',MigrateCommand) # 新增脚本命令,用于迁移数据
if __name__ == "__main__":
manager.run() |
# Check if Palindrome - Checks if the string entered by the user is a palindrome.
def palindrome():
i = input("Give an input: ")
if i.isdigit():
print("NOT A STRING")
else:
print(check(i))
def check(string):
if string==string[::-1]:
return "input is a palindrome"
els... |
from enum import Enum
class Command(Enum):
CREATE_PARKING_LOT = ('create_parking_lot', 1)
PARK = ('park', 2)
LEAVE = ('leave', 1)
STATUS = ('status', 0)
REGISTRATION_NUMBERS_FOR_CARS_WITH_COLOUR = ('registration_numbers_for_cars_with_colour', 1)
SLOT_NUMBERS_FOR_CARS_WITH_COLOUR = ('slot_numbe... |
def famous():
print("this is a function") # defining a function
#calling the function
famous()
def reed():
print("you are underaged")
guy=int(input("enter your age"))
if guy <= 10:
reed()
else:
print("welcome on board")
#assigning numbers to variables in a function
def boy(x,y):
l=[x+y, x*y]
re... |
"""
Datastore model for authors.
And methods for standardizing author names from disparate sources.
User entry and isbndb crowd-sourced data often has
"""
import logging
from google.appengine.ext import db
def format_author_names(author_name):
""" Parse string for first and last names. """
first_name = ''
las... |
import pandas as pd
path = r'C:\Users\omgit\PycharmProjects\185cMidterm\Business_case_dataset.csv'
features = ['id', 'BLoverall', 'BLavg', 'price_overall', 'price_avg', 'review', 'review score', 'minutes listened',
'completion', 'Support Request', 'Last visited minus purchase date', 'targets']
dataset = pd.... |
import sys
import re
import numpy as np
import tensorflow as tf
from preprocess import Corpus
from sklearn.cluster import KMeans
from sklearn import preprocessing
from collections import OrderedDict
import draw_cluster
def minibatch(X, batch_size = 50, Shuffle = True):
all_batch = np.arange(X.shape[0])
all_siz... |
from django.urls import path
from rest_framework.routers import DefaultRouter
from games.views import GameModelViewSet
app_name = "games"
router = DefaultRouter()
router.register("games", GameModelViewSet)
urlpatterns = router.urls
|
import socket, ssl, re
import Value
from setting import *
from Message import *
from Log import *
from snuMenu import *
from daumDic import *
from naverWeather import *
from db import *
import arith
def send_msg(channel, txt):
irc.send(bytes('PRIVMSG ' + channel + ' :' + txt + '\n', UTF8))
def pong():
irc.se... |
from rest_framework import serializers
from .models import Restaurant
from .models import Menu
from .models import Day
class RestaurantSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Restaurant
fields = ('id', 'url', 'name')
class MenuSerializer(serializers.HyperlinkedMod... |
"""
Abstrai os blocos, permintindo sua instaciação como objeto da blockchain
e permite operações básicas do seu funcionamento, como a criação de
assinaturas (hashs) e
"""
from erros import erroGenericoGenesis, vatoNaoPodeConterNumero, tipoDeBlocoInvalido, modoDeInclusaoInvalido
from hashlib import sha256
import os,... |
import requests
import re
import xlsxwriter
from bs4 import BeautifulSoup
playerlist=[]
rankplayer=[]
LPList=[]
LVLList=[]
vitoriaList=[]
derrotaList=[]
pctList=[]
z=101
o='#'
cont=0
for a in range(1,1001):
print("P", a)
url ="http://br.op.gg/ranking/ladder/page="+str(a)
req = requests.get(url)
soup = B... |
# Creating a greetings function
# Syntax def name_of_function():
# Each function has a block of code to execute to ideally run one task
# Note: We can assign variables to functions e.g. a = add(5, 7) and a = 12 forever more
def greeting(name):
print(f"Welcome on board {name}, hope you'll enjoy the ride")
# If we ... |
from django import forms
class ContactForms(forms.Form):
name=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter Your Name'}),label=False,max_length=100,required=True)
email=forms.EmailField(widget=forms.EmailInput(attrs={'placeholder':'Enter Your Email'}),label=False,required=True)
selectO... |
from django.test import TestCase
from model_mommy import mommy
from model_mommy.recipe import Recipe,foreign_key
from .models import Blogger
class KidTestModel(TestCase):
"""
Class to test the model
Kid
"""
def setUp(self):
"""
Set up all the tests
"""
self.kid = m... |
from jinja2.environment import Environment
from jinja2.loaders import PackageLoader
from keyword import kwlist
from hwt.hdlObjects.operator import Operator
from hwt.hdlObjects.operatorDefs import AllOps, sensitivityByOp
from hwt.hdlObjects.constants import SENSITIVITY
from hwt.hdlObjects.statements import IfContainer
... |
import copy
import time
import random
import matplotlib.pyplot as plt
import numpy as np
from msgame import MSGame
class baseGeneticAlgorithm(object):
def __init__(self, boardWidth = 16, boardHeight = 30, bombs = 99, populationSize = 100, generationCount = 100, crossoverRate = .75, mutationRate = .05):
se... |
"""
Script permettant de charger un rdf dans une base sqlite
qui pourra ensuite en théorie être utiliser comme
triple store
"""
from rdflib import plugin, Graph, Literal, URIRef
from rdflib.store import Store
from rdflib_sqlalchemy import registerplugins
registerplugins()
ident = URIRef("pt_ecoute")
dbu... |
from PIL import Image
from pathlib import Path
def im_read_save(path):
try:
im = Image.open(path)
except:
return 0
save_dir = str(images_dir / im_name)
im.save(save_dir)
print("{} is copied in {}".format(im_name, save_dir))
def main():
data_dir = ".... |
from pymongo import *
class DB_Manager:
client = MongoClient()
db = client.Indexer
Words_in_url = []
Urls_contain_word = []
word_positions_in_doc = []
Error = "Ops! Error happened w da barra 3nny, please don't try again msh na2sa :v"
def insert_word(self, collection_name, s, w, r, url, pos... |
##################################################
INPUT CODE:
##################################################
/* Copyright 2018 The TensorFlow 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 ob... |
from django.contrib import admin
from food.models import *
# Register your models here.
admin.site.register(Food)
admin.site.register(Consume)
|
import model
from typing import Callable
def get_simple_linear(initial_rrsp: float, final_rrsp: float, initial_year: int, career_length_yrs: int):
"""
Sets the split between RRSP and TFSA as a linear function of time.
s[y] = a + b*(y - y_0), where s = RRSP allotment (normalized), a = initial_rrsp (normali... |
import numpy as np
import file_loader as fl
import preprocess as pp
import tensorflow as tf
import keras
import random
import time
import copy
import numpy
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers import LSTM, Embedding
from keras.layers import Merge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.