text stringlengths 38 1.54M |
|---|
import numpy as np
def generateTheSquareMatrix(size):
if size % 2 == 0:
raise Exception('size must be an odd number')
matrix = [ [None for y in range(size)] for x in range(size)]
# there are total size/2 sub squares in the matrix
square_count = 1
x, y = size//2, size//2
initialNumber = 1... |
# install pygame via pip install pygame in cmd
# use the internet for help - Keith Galli on Youtube
import pygame
import sys
import random
pygame.init()
# called when an object is created from a class and
# it allows the class to initialize the attributes
# of the class
WIDTH = 800
HEIGHT = 600
# Size of window
PL... |
#from kivy.support import install_twisted_reactor
#install_twisted_reactor()
#from twisted.web.xmlrpc import Proxy
#from twisted.internet import reactor
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.graphics import *
import xmlrpclib
class RunningRoad(Widget):
... |
from django.db import models
from django.contrib.gis.db import models as gismodels
from time import time
# Create your models here.
def get_upload_filename(instance, filename):
return "upload_business/%s_%s" % (str(time()).replace('.', '_'), filename)
class PublishQuerySet(models.QuerySet):
def published(se... |
"""
一个回合制游戏,每个角色都有hp 和power,
hp代表血量,power代表攻击力,hp的初始值为1000,
power的初始值为200。打斗多个回合
定义一个fight方法:
my_hp = hp - enemy_power
enemy_final_hp = enemy_hp - my_power
谁的hp先为0,那么谁就输了
"""
# 定义一个 fight 函数
def fight():
# 定义变量——血量
blue_hp = 1000
red_hp = 1000
# 定义变量——攻击值
blue_power = 200
red_power = 200
#... |
#! analyse.py
"""Analyse applications from CSV file."""
from os import write
from pathlib import Path
import pandas as pd
from datetime import datetime, date
import sys
import shutil
# TODO: Split the function into three different functions:
# Function 1: read CSV??
# Function 2: Assign new column names... |
#!/usr/bin/env python2
import sqlite3
import cgi,cgitb
print "Content-Type: text/html\n\n"
form =cgi.FieldStorage()
nam=form["username"].value
passw=form["password"].value
conn=sqlite3.connect('/var/crawl.db')
#print ("connected successfully\n")
print "<h1 style='color:white; text-align:center; font-size:50px'>pyCRAWLE... |
mystuff = {'apple': "I am apples!"}
print mystuff['apple']
import mystuff
mystuff.apple()
def apple():
print "Iam apples!"
import mystuff
mystuff.apple()
print mystuff.tangerine
mystuff.apple()
mystuff.tangerine
mystuff['apple']
class Mystuff(object):
def __init__(self):
self.tangerine = "And n... |
from urllib.parse import quote
class PackageVersion(object):
def __init__(self, json_data, subject, repo):
self._json_data = json_data
self.subject = subject
self.repo = repo
self.version, self.channel = self._json_data['name'].split(':')
self.name, self.username = self._... |
#! /usr/bin/python
def function(num):
print(num)
print(num*"lol ")
pom=int(input("Vnesi broj"))
function(pom)
|
from tests.customlist_tests.base.customlist_test_base import CustomListTestBase
class CustomListMoveFirstTests(CustomListTestBase):
def test_customListMove_whenListIsEmpty_shouldReturnEmptyList(self):
custom_list = self.setup_list()
result = custom_list.move(5)
self.assertEmpty(result)
... |
from rest_framework import serializers
from .models import Order
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = ('url', 'user', 'book', 'plated_end_at') |
# -*- coding: utf-8 -*-
class BaseError(Exception):
def __init__(self, value=None):
self.value = value
class UnauthorizedError(BaseError):
pass
class InternalServerError(BaseError):
def __repr__(self):
if self.value is not None:
return self.value
return '500. Inte... |
# import unittest
import numpy as np
import mlwords.DecisionTree.DecisionTree as dt
# class MyTestCase(unittest.TestCase):
# def test_something(self):
# self.assertEqual(True, False)
# if __name__ == '__main__':
# unittest.main()
data_x = np.array([[10, 200, 100, 12, 50, 40, 90, 10, 10, 80],
... |
# -*- coding: utf-8 -*-
def comp_parameters(self, output):
"""Compute the parameters dict for the equivalent electrical circuit:
resistance, inductance and back electromotive force
Parameters
----------
self : EEC_PMSM
an EEC_PMSM object
output : Output
an Output object
"""... |
# solve_itc_randomly.py: This python script extracts the dat from an ITC-2007 Course Timetabling Problem input file,
# constructs the CSP variables, domains and constraints and then generates a random "complete
# assignment" by assigning every variable to a randomly selecte... |
results = []
for num in range(20):
if num % 2 == 0:
results.append(num)
print('results', results)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 14:25:37 2018
@author: I332487
"""
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy import stats
import tensorflow as tf
import seaborn as sns
from pylab import rcParams
from sklearn.model_selection import ... |
from starter2 import *
import xtra_energy
import data_locations as dl
import loop_tools
reload(dl)
reload(looper)
reload(loop_apps)
reload(loop_tools)
if 'this_simname' not in dir():
this_simname = 'u05'
output_base = "%s_cores"%this_simname
core_list = [10]
frame_list = list(range(1,121))+[125]
fields = []# ['... |
from mnmt.inputter import ArgsFeeder
from mnmt.encoder import BasicEncoder
from mnmt.trainer.utils import create_mask
import torch.nn as nn
class Seq2MultiSeq(nn.Module):
def __init__(self, args_feeder: ArgsFeeder, encoder: BasicEncoder,
decoder_list: nn.ModuleList, teacher_forcing_rati... |
from django.conf.urls import patterns, url
from corehq.apps.preview_app.views import PreviewAppView
urlpatterns = patterns('corehq.apps.preview_app.views',
url(r'^(?P<app_id>[\w-]+)/$', PreviewAppView.as_view(), name=PreviewAppView.urlname),
)
|
import wikipedia
import webbrowser
def wiki():
wikipage=wikipedia.random(1)
wikiload=wikipedia.page(wikipage)
s=wikipedia.summary(wikipage)
url=wikiload.url
print("\n\nArticle name: {} \n".format(wikipage))
choice=input("Are you interested in this Article {}? y/n/q:").lower().strip()... |
import numpy as np
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
import re
import numpy
import seaborn as sns
sns.set_style("white")
sns.set_style("ticks")
mpl.rc('xtick', labelsize=26)
mpl.rc('ytick', l... |
from re import *
#---------------------------------#
#predefined character sets
# --------------------------------#
pattern1='[a-k]' #check for lowercase a to z
pattern2='[0-9]' #check for all digits
pattern3='[^0-9]' #except no.s
pattern4='[^a-z]' #except lowercase characters
pattern5='[a-zA-Z]' #check for both lower... |
# Load Libraries
import warnings
import model_evaluate
import model_preproecess
import tensorflow as tf
from keras import backend as K
from keras import regularizers
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.layers import Input, ELU, Embedding, BatchNormalization
... |
import os
import sys
import subprocess
import gain.utilities
def create_growth_raster(tile_age):
tile_id = tile_age[0]
age = tile_age[1]
shapefile = 'growth_rate.shp'
print tile_id
ymax, xmin, ymin, xmax = gain.utilities.coords(tile_id)
output_tif = "{0}_{1}.tif".format(tile_id, age)
... |
import pygame as pg
class Settings:
def __init__(self):
# frames per second
self.FPS = 60
# colors
self.BLACK = (0, 0, 0)
self.WHITE = (255, 255, 255)
self.ORANGE = (251, 191, 72)
self.PINK = (255, 108, 216)
self.RED = (234, 17, 17)
self.CY... |
from typing import List, Optional
from beagle.nodes import Node
class IPAddress(Node):
__name__ = "IP Address"
__color__ = "#87CEEB"
ip_address: Optional[str]
key_fields: List[str] = ["ip_address"]
def __init__(self, ip_address: str = None):
self.ip_address = ip_address
@property... |
def get_php_agent(request_target, request_method, request_redirect_method, request_data, request_params, request_cookie,
redirect_auto, redirect_cookie_use, timeout, type):
php_code = """
# 代理目标
$REQUEST_URL= "%s";
# 代理请求方法
$REQUEST_METHOD= '%s';
# 遇到跳转时的请求方法
$REQUEST_REDIRECT_METHOD = '%s';
... |
fin = open('countingsheep.in', 'r')
fout = open('countingsheep.out', 'w')
count = 0
for line in fin:
if count != 0:
x = int(line)
out = None
if x == 0:
out = 'INSOMNIA'
else:
digs = {}
y = 1
while len(digs) < 10:
for ... |
from numpy import *
def loadDataSet():
postingList = [
['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
['stop', 'posting', 'stupid', 'worthless'... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 12 21:24:19 2018
@author: SP
"""
import requests
from bs4 import BeautifulSoup
from lxml import html
import pandas as pd
import datetime
import os
import etf_vnm
import etf_ftse
import etf_vfm
import etf_ssi
import dc
import pyn
def vofprice():
page=requests.get('ht... |
from NanpyConnect import nanpyConnect
from time import sleep
from MotorClass import Motor
a = nanpyConnect()
M1EnPin = 5
M1APin = 6
M1BPin = 7
M2EnPin = 8
M2APin = 9
M2BPin = 10
# Enable and set each motor
M1 = Motor("LEFT", M1EnPin, M1APin, M1BPin)
M1.pinSet(a)
M2 = Motor("RIGHT", M2EnPin, M2APin, M2BPin)
M2.pin... |
# bot modules
import bot.utils as utils
import bot.config as config
from bot.database.sqlite import Database
from bot.parser.interface import IParser
# general python
import pandas as pd
import pickle
import hashlib
import re
import sys
from tqdm import tqdm
class Email:
"""Email object"""
def __init__(
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : collections.py
@Time : 2020/02/12 22:15:11
@Author : elegantm
@Version : 1.0
@Desc : None
'''
# here put the import lib
from collections import namedtuple,deque,defaultdict
from collections import ChainMap,Counter
import os,argparse
Poin... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import cv2
import numpy as np
# Load in image and create copy
image = cv2.imread('1.png')
original = image.copy()
# Gaussian blur and extract blue channel
blur = cv2.GaussianBlur(image, (3,3), 0)
blue = blur[:,:,0]
# Threshold image and erode to isolate gate contour
thresh = cv2.threshold(blue,135, 255, cv2.THRESH_B... |
from google.cloud import bigquery
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:\Users\100689998\Documents\python-scripts\Interview-codes\horizontal-ray-245215-61f00bf119a8.json"
client = bigquery.Client()
dataset_ref = client.dataset('hacker_news', project='bigquery-public-data')
dataset = client.g... |
from __future__ import unicode_literals
from django.db import models
from app.adopcion.models import Persona
# Create your models here.
class vacuna(models.Model):
nombre = models.CharField(max_length=50)
class mascota(models.Model):
nombre = models.CharField(max_length=50)
sexo = models.CharField(max_length=1... |
from django.db import models
class Question(models.Model):
Q = models.TextField()
A1 = models.TextField()
A2 = models.TextField()
A3 = models.TextField()
A4 = models.TextField()
A5 = models.TextField()
A6 = models.TextField()
QType = models.TextField()
RightAnswer = models.CharField(max_length = 6)
Source = ... |
from constants import less_D
import nengo_spa as spa
state_vocab = spa.Vocabulary(less_D)
state_vocab.populate("RUN;NONE")
def gen_vocab(n_dict, n_range=9, dims=32, rng=None):
vo = spa.Vocabulary(dims, rng=rng)
n_list = list(n_dict.keys())
vo.populate(";".join(n_list[:n_range]))
return n_list, vo
|
import sys
from sage.all import *
import time
'''
Implements Pollards rho for factoring
Pseducode:
Choose X_0 randomly in Z/NZ
Y_0 = X_0
Run for atmost O(B) number of times:
X_0 = f(X_0)
Y_0 = f(f(Y_0))
if(gcd(X_0-Y_0,N) > 1)
implies ... |
from django.urls import path
from . import views
urlpatterns = [
# Run data mining
path('get-driving-features', views.GetDrivingFeatures.as_view()),
path('get-driving-features-epsilon-moea', views.GetDrivingFeaturesEpsilonMOEA.as_view()),
path('get-driving-features-with-generalization', views.GetDrivi... |
##########################################################################
#
# Copyright (c) 2023, Cinesite VFX Ltd. 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 ... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import ImageGrab
def main():
while(1):
im = ImageGrab.grab((90, 90, 400, 300)) # デスクトップの始点(0,0),横400, 縦300の矩形部分をキャプチャ
im = np.asarray(im) # OpenCVで扱うためにNumpy配列に変換
im = cv2.cvtColor(im,cv2.COLOR_BGR2RGB) # BGR→RGB
... |
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
import matplotlib.pyplot as pyl
from matplotlib.contour import QuadContourSet
from matplotlib.widgets import Slider
#Define display parameters
mpl.rcParams['xtick.direction'] = 'out'
mpl.rcParams['ytick.direction'] = 'out'
delta = 0.025
#Defin... |
"""
SmartRegisterCouponInfo操作用モジュール
"""
import os
from aws.dynamodb.base import DynamoDB
class SmartRegisterCouponInfo(DynamoDB):
"""SmartRegisterCouponInfo操作用クラス"""
__slots__ = ['_table']
def __init__(self):
"""初期化メソッド"""
table_name = os.environ.get("PAY_PAY_COUPON_INFO_DB")
sup... |
import tensorflow as tf
import math
def pred_discr_BiRNN_Fc(X_id,
Seq_len,
Drop_keep,
voc_size,
embedding_size,
hidden_size,
num_stack_layer,
basic_cell,
embedding,
Candidate_id):
# Look up embedding
X_ebd = tf.nn.embedding_lookup(embe... |
import sys
sys.stdin = open('test2.txt', 'r')
def func1(k, li):
global result, f
result1 = result
if k == len(li):
for i in range(k):
result1.append(li[i])
if (li[0] == li[1] == li[2] or li[0] == li[1] +1 == li[2] + 2) and (li[3] == li[4]+1 == li[5]+2 or li[3] == li[4] == li[5])... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# stos.py
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
... |
# doc-export: DifferentBoxes
"""
Example to explain the differences between the BoxPanel and BoxLayout.
"""
T1 = """
BoxLayout (HBox, VBox) - note how in the bottom row, the natural size
of the buttons is taken into account. Also in the top row the natural
size is used as a starting point, and extra space is equally d... |
import unittest
import random
from platform.platformer import StaticPlatformer
class TestStaticPlatformer(unittest.TestCase):
def setUp(self):
random.seed(13)
def test_default_platform(self):
result = StaticPlatformer()
self.assertEqual(len(result.get_block_positions()), len(list(set... |
# loads the argv module from the system
from sys import argv
# read the WYSS section for how to run this
# This sets each variable to an argument passed in when the script was run
script, first, second, third, fourth = argv
#prints out the variables input - added my line breaks for readability
print("\nThe script is ... |
# -*- coding: utf-8 -*-
# Global imports
import os, time
import glob
import argparse as ap
import numpy as np
# Local imports
from StorePDBFilenames import *
# Script information
__author__ = "Sergi Rodà Llordés"
__version__ ="1.0"
__maintainer__="Sergi Rodà Llordés"
__email__="sergi.rodallordes@bsc.es"
def parseAr... |
# coding=utf-8
from os.path import join
from matplotlib import offsetbox
import numpy as np
from os.path import isfile
from scipy.misc.pilutil import imread, imresize
from matplotlib import pyplot as plt
import os
__author__ = 'Michał Ciołczyk'
def read_image(name):
return imread(name, True)
def greyscale_to_r... |
import clr
import sys
clr.AddReferenceByPartialName("UnityEngine")
clr.AddReferenceByPartialName("Pluton")
import UnityEngine
import Pluton
from Pluton import InvItem
from System import *
from UnityEngine import *
class Example:
def On_PlayerConnected(self, player):
for p in Server.ActivePlayers:
if(p.Name != p... |
#coding:utf-8
import json
import logging
def fixjson(data):
'''
pattern tha need to add '"""'
{ :
, :
ignore symbols
]
}
'''
symbols = ',:{'
cominbine = ['{:', ',:']
index = [0, 0]
stack = ''
newdata = ''
for i, x in enumerate(data):
if x in symbols:
... |
#!../python3.9/bin/python
from . import generadorFiveBitProblem
from . import main
from . import reca
|
import torch
from torch.utils.data import Dataset
import numpy as np
class NO2Dataset(Dataset):
def __init__(self, sequences_path, targets_path, noise_std=False):
self.inputs = torch.from_numpy(np.load(sequences_path)).float()
self.targets = torch.from_numpy(np.load(targets_path)).float()
s... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Andreas Pakulat <apaku@gmx.de>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright n... |
from django.db import models
# Create your models here.
class College(models.Model):
name = models.CharField(max_length=30)
image = models.TextField()
location = models.TextField()
rank = models.IntegerField()
review = models.TextField()
courses = models.ForeignKey('Courses', on_delete=models.... |
#Importing lib
import cv2
import numpy as np
# Importing image
image = cv2.imread("jass.jpg")
(h, w, d) = image.shape
print("width={}, height={}, depth={}".format(w, h, d))
#Accessing a pixel in an image
(B, G, R) = image[100, 50]
print("R={}, G={}, B={}".format(R, G, B))
#Slicing an image
'''roi = image[30:130, 25... |
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:
return False
for row in matrix:
if targe... |
from django.urls import path
from . import views
from django.views.generic import TemplateView
app_name='hello'
urlpatterns = [
path('', views.index),
]
|
import fileinput
import itertools
def isprime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return 2
if n % 3 == 0:
return 3
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return i
... |
import FWCore.ParameterSet.Config as cms
from JetMETCorrections.Configuration.JetCorrectionServices_cff import *
#
# SINGLE LEVEL CORRECTION SERVICES
#
# L1 (offset) Correction Services
ak7CaloL1Offset = ak5CaloL1Offset.clone()
kt4CaloL1Offset = ak5CaloL1Offset.clone()
kt6CaloL1Offset = ak5CaloL1Offset.clone()
ic5C... |
import logging
import sonrai.platform.aws.arn
def run(ctx):
ec2_client = ctx.get_client().get('ec2', 'us-east-1')
# Get role name
resource_arn = sonrai.platform.aws.arn.parse(ctx.resource_id)
ec2_instance_id = resource_arn \
.assert_service("ec2") \
.assert_type("instance") \
... |
from . import utils
from . import kernels
from . import tensorflow_kernels
from . import kernel_means_inference
from . import kernel_means_learning |
import pygame
import collections, math, re, os.path
import lib.pyg
from lib.geom import P,S,R,L
def Drawable(cls):
def draw(self, surface=None):
if None == surface:
surface = pygame.display.get_surface()
self.onDraw(surface)
def onDraw(self, surface):
raise NotImplementedError
if no... |
import wx
import globals as gbl
import lib.ui_lib as uil
class EmployeeBreakdownDialog(wx.Dialog):
def __init__(self, parent, winId, items):
self.ht = (len(items) + 1) * 25
wx.Dialog.__init__(self, parent, winId, size=(600, self.ht + 100))
panel = wx.Panel(self, wx.ID_ANY)
panel.S... |
import xml;
import requests;
import xml.etree.ElementTree as ET
base_url = 'http://127.0.0.1:4516/deployit/repository/ci/'
uri_get_ci = 'http://127.0.0.1:4516/deployit/repository/v3/query?resultsPerPage=-1';
xmlHeader = {"Content-Type":"application/xml"};
get_ci_response = requests.get(uri_get_ci, headers=xmlHeader,... |
import os
from bottle import route, run
@route('/')
def index():
return '<a href=\'/about\'>About</a> <a href=\'/bio\'>Biography</a> <a href=\'/picture\'>Pictures</a><h2>' \
'<a href=\'https://github.com/PeturSteinn/VEFTH2V-Verkefni_1\'>Github!</a></h2>'
@route('/about')
def about():
return '<h3>lo... |
from oscar.apps.dashboard.catalogue import formsets as catalogue_admin_formset
from .forms import ProductAttributesForm
ProductAttributesFormSet = catalogue_admin_formset.inlineformset_factory(catalogue_admin_formset.ProductClass,
catalogue_admin... |
from abc import ABC, abstractmethod
from typing import List
from entities.manager import Manager
from entities.reimbursement import Reimbursement
class ManagerDao(ABC):
@abstractmethod
def login(self, user_name: str, password: str) -> Manager:
pass
@abstractmethod
def view_all_requests(self)... |
from django.db.models import fields
from rest_framework import serializers
from Api import models
class LeadsSerializer(serializers.ModelSerializer):
class Meta:
model=models.Leads
fields=['id','first_name','last_name','age','email','department','hospital','product','agent']
class Agen... |
import cv2
import os
import glob
from pathlib import Path
from fsrcnn import TRAIN_DIM
def split_image(data_dir, img_name_stem, img, square_size, stride_factor):
i = 0
for r in range(0, img.shape[0], square_size // stride_factor):
j = 0
for c in range(0, img.shape[1], square_size // stride_fa... |
from django.contrib import admin
from .models import Music
from .models import Playlist
admin.site.register(Music)
admin.site.register(Playlist)
|
import gym
import deeprl_hw1.rl as rl
def run_policy(env,policy,gamma):
total_reward = 0
step_num = 0
state = env.reset()
is_terminal = False
while not is_terminal:
nextstate, reward, is_terminal, debug_info = env.step(policy[state])
total_reward += pow(gamma,step_num) * reward
... |
# coding=utf-8
from tests import unittest
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkcore.auth.signers.sts_token_signer import StsTokenSigner
from aliyunsdkcore.request import RpcRequest, RoaRequest
class TestStsTokenSigner(unittest.TestCase):
def test_sts_token_signer(self):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Action',
fields=[
('id', models.AutoField(verbo... |
import turtle
import random
import time
class Rank(object) :
def __init__(self, name, time) :
self.name=name
self.time=time
def getName(self) :
return self.name
def getTime(self) :
return self.time
def setName(self, name) :
self.name=name
def setTime(self, time) :
self.time=time
cla... |
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
base = pd.read_csv('iris.csv')
previsores = base.iloc[:, 0:4].values
classe = base.iloc[:, 4].values
labelencoder = LabelEncod... |
"""Task 3: Enter a Boolean expression to test whether the sum of 673 and 909 is divisible by 3."""
a = ((673 + 909) % 3 == 0)
print(a)
#Everything below the above print statement is optional and only used to convey "proof."
print('The remainder is ' + str(673 + 909 % 3))#Shows that the remainder is in fact not 0.
prin... |
# -*- coding: utf-8 -*-
"""
@author: Shubha Raj Kharel
"""
__all__ = ['graphDPG', 'matching', 'models', 'utils']
from DPG.graphDPG import GraphDPG, DPGfeasibilityError
from DPG.matching import Matching, smallMatchingSizeError
from DPG.models import iconfigDPG, regularDPG, linDPG
from DPG.utils import timeIt, ERGraph
|
# coding: utf-8
# In[1]:
""" Use first valid of delta or subbasin column.
-------------------------------------------------------------------------------
Update 2020/02/19 output version 8-9, input version 4-5
Author: Rutger Hofste
Date: 20180730
Kernel: python35
Docker: rutgerhofste/gisdocker:ubuntu16.04
Args:
... |
import tkinter as tk
from tkinter import ttk
import platform
from typing import List
from fludo import Liquid, Mixture
from images import icons, graphics
from common import round_digits
class BottleViewer:
def __init__(self, parent: tk.Widget = None):
if parent is None:
# assume that we nee... |
from math import log
class DecisionTree(object):
"""ID3算法决策树简单实现"""
def __init__(self, sample_data, labels):
"""初始化"""
self.sample_data = sample_data
self.labels = labels
def calcShannonEnt(self, sample_data):
"""计算给定数据集的香农熵"""
sample_num... |
#! /usr/bin/python
'''
Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remai... |
x={1,2,3,4,5}
y={3,4,5,6,7}
print(x | y) # This statement print total values in x and y
print(x & y) # This statement print common values in x and y
print(x.union(y)) # This statement print total values in x and y
print(x.intersection(y)) # ... |
import os
from flask import jsonify, make_response
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
os.environ.update({'ROOT_PATH': ROOT_PATH})
from modules import logger
from modules.app import app
ENVIRONMENT = 'development'
SECRET = 'c3c4HTQX6ETCdGrJ8dXS'
# Create a logger object to log the info and debu... |
from building import *
import rtconfig
cwd = GetCurrentDir()
src = Glob('mdns.c')
LOCAL_CCFLAGS = ''
if rtconfig.CROSS_TOOL == 'gcc':
LOCAL_CCFLAGS += ' -std=c99'
elif rtconfig.CROSS_TOOL == 'keil':
LOCAL_CCFLAGS += ' --c99'
group = DefineGroup('mdns', src, depend = [], LOCAL_CCFLAGS = LOCAL_CCFLAGS... |
# -*- coding: utf-8 -*-
import socket
import random
# 创建实例
sk = socket.socket()
# 定义绑定ip和port
ip_port = ("127.0.0.1", 8888)
# 绑定监听
sk.bind(ip_port)
# 最大连接数,可以挂起的最大连接数为5,拒绝第6个请求
sk.listen(5)
while True:
# 提示信息
print("正在进行等待接收数据.....")
# 接受数据
conn, address = sk.accept()
# 定义信息
msg = "连接成功"
#... |
import sys
import os
import shutil
import subprocess
import zipfile
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running:... |
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from spiderb... |
BYE = "Later!"
CONT = "<Let Tiny Kim continue>"
TK_GREET = "Hello, Big Kim!"
GREET_R1 = "Hello, Tiny Kim!"
GREET_R2 = "Get away from me, you little freak."
TK_INFO1_SAD = "I can see we won't be getting along. Still, you need some info."
TK_INFO1_HAPPY = "Hey, I've got a status update for you on the status of Space Ko... |
# We want to create class for an object that behaves like a triangle, that has flexible sides and angles.
# Because of approximations in python the triangle will get distorted after some of the changes so this is not a
# perfect model
# 30P
# - class constructor can receive 3 arguments for angles (with default v... |
if __name__ == '__main__':
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is',age)
print('teenager')
|
class Solution(object):
"""
refer to: https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
"""
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
length = len(nums)
if length < 3:... |
import ray
# Put the values (1, 2, 3) into Ray's object store.
a, b, c = ray.put(1), ray.put(2), ray.put(3)
@ray.remote
def print_via_capture():
"""This function prints the values of (a, b, c) to stdout."""
print(ray.get([a, b, c]))
# Passing object references via closure-capture. Inside the `print_via_cap... |
from PatientVec.Experiments.config_units import *
def get_basic_model_config(data, exp_name):
config = {
"model": {
"type": None,
"embedder": add_embedder(**data.get_embedding_params()),
"decoder": {"num_layers": 2, "hidden_dims": [128, data.output_size], "activations": ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.