text stringlengths 38 1.54M |
|---|
import torch
import random
class E_Greedy_Policy():
def __init__(self, epsilon, decay, min_epsilon):
#initialise parameters
self.epsilon = epsilon
self.epsilon_start = epsilon
self.decay = decay
self.epsilon_min = min_epsilon
def __call__(self, state, n_act... |
from __future__ import absolute_import
from __future__ import with_statement
import re
import sys
import warnings
try:
import unittest # noqa
unittest.skip
from unittest.util import safe_repr, unorderable_list_difference
except AttributeError:
import unittest2 as unittest # noqa
from unittest2.u... |
import argparse
import cPickle as pickle
import sys
import numpy as np
import os.path
from sklearn.metrics import average_precision_score
## my own library
from my_utils import printParams, myloadData, mypretrainLSTM, glove_init_LSTM
from my_utils import get_dict, vectorize_label, mymap, count_MAP_total
from build_... |
# -*- coding:utf-8 -*-
# import time
#
# # 获得当前时间时间戳
# now = int(time.time())
# # 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
# timeStruct = time.localtime(now)
# strTime = time.strftime("%Y-%m-%d-%H:%M", timeStruct)
#
# print(strTime)
# sheet_name_xls = (u'测试专用表格 %s' % strTime)
# print(sheet_name_xls)
# 格式化字符串
# 槽号绑定信号的函数
def... |
from datetime import datetime, timedelta
from sqlalchemy.orm import relationship
from app import db
class Token(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE', name='token_user_id_fk'))
user = relationship('User')
... |
'''
File : eddieSpread.py
Start Date : 20070111
Description : Spread messaging interface
$Id: eddieSpread.py 900 2007-12-09 09:27:47Z chris $
'''
__version__ = '$Revision: 900 $'
__copyright__ = 'Copyright (c) Chris Miles 2007'
__author__ = 'Chris Miles'
__license__ = '''
This program i... |
# Generated by Django 3.0.5 on 2020-04-07 23:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('urlshortener', '0003_auto_20200407_2253'),
]
operations = [
migrations.AlterField(
model_name='urlshortener',
name='... |
from pyforest import *
def clean():
FG_df=pd.read_csv('../data/fgplayerdf.csv')
EV_df=pd.read_csv('../data/EVdf.csv')
SS_df=pd.read_csv('../data/SSdf.csv')
shift_df = pd.read_csv('../data/Shiftdf.csv')
#trim to columns with correlation to Babip
FG_df = FG_df[['Year','Player','Babip','Team','PA','SB','CS','ISO',... |
from django.db import models
from ecommerce.utils import CustomModelManager, CustomModelQuerySet
from items.models import Item
from settings.models import FiscalYear
from users.models import GuestEmail, User
# Create your models here.
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.... |
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Extract drives_right column as Series: dr
dr = cars['drives_right']
# Use dr to subset cars: sel
sel = cars[dr]
# Print sel
print(sel)
|
import sqlite3
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
cursor2 = conn.cursor()
cursor.execute("Update phones set name = 'Police' where name = 'Hello'")
cursor2.execute("Select * from phones")
cursor2.close()
for record in cursor2.fetchall():
print("Name: {}, Phone Number: {}".format(record[... |
# ======================================================
# @Author : Daniel
# @Time : 2020.6.20
# @Desc : 用户视图
# ======================================================
from flask import Blueprint, request, render_template, session, redirect, url_for
from flask_login import login_required... |
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
class DomainRedirectMiddleware(object):
"""
In Apache's httpd.conf, you may have ServerName set to mysite.com.au along
with a number of aliases: mysite.com, mysite.net, my-site.com etc.
This middleware redirects any re... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-26 08:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prodsys', '0023_auto_20170626_0824'),
]
operations = [
migrations.RenameField... |
"""add join table for ann tasks and term sampling groups
Revision ID: 700869c6a3d1
Revises: 59f532bb2197
Create Date: 2017-06-08 19:44:54.766976
"""
# revision identifiers, used by Alembic.
revision = '700869c6a3d1'
down_revision = '59f532bb2197'
branch_labels = None
depends_on = None
from alembic import op
import ... |
from django.db import models
import bcrypt,datetime
class UserManager(models.Manager):
def validate_registration(self, postData):
response = {
'status' : False,
'errors' : []
}
if len(postData['name']) < 2:
response['errors'].append("Name too short")
... |
# -*- coding: utf-8 -*-
# @Author: yulidong
# @Date: 2018-04-25 19:03:52
# @Last Modified by: yulidong
# @Last Modified time: 2018-08-06 13:13:55
import scipy.io
import numpy as np
import os
data=scipy.io.loadmat('/home/lidong/Documents/datasets/nyu/nyu2_test_index.mat')
test1=data['testNdxs']-1
data=scipy.io.loadm... |
import unittest2 as unittest
import sys
sys.path.insert(0, '..')
from driver import Driver
from trip import Trip
from passenger import Passenger
from artist import Artist
from song import Song
from genre import Genre
class TestOneToManyRelationships(unittest.TestCase):
global driver_1
driver_1 = Driver("Danie... |
from lib.DataReader import DataReader
class ReadDoodad:
def __init__(self, filename):
self.read = DataReader(filename)
self.info = self.ReadDoodad()
def ReadDoodad(self):
doodHeader = self.ReadHeader()
doodInfo = {}
doodInfo["fileID"] = doodHeader[0]
... |
def column_metrics(column):
print("Średnia: \t", column.mean())
print("Wariancja: \t", column.var())
print("Skośność: \t", column.skew())
print("Kurtoza: \t", column.kurtosis())
print("Mediana: \t", column.median())
print("Mediana: \t", column.median())
print("Moda: \t \t", float(column.mode... |
"""
Løsningsforslag
Øving 2 - Oppgave 2
@author: Thomas Nyborg
"""
def leg(alder):
return(alder>=18)
alder = int(input("Hvor gammel er du?"))
if leg(alder):
print("Du er gammel nok til å kjøre bil.")
else:
print("Du er ikke gammel nok til å kjøre bil.")
|
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, ge... |
"""
Difficulty: *
Code: *
Ref: https://www.hackerrank.com/challenges/camelcase
"""
import unittest
def camel_case(words):
words_found = 1
for letter in words:
if letter.isupper():
words_found += 1
return words_found
class MyTestCases(unittest.TestCase):
def tes... |
from greedy import greedy_celf
import numpy as np
import copy
class LUCBLearner:
def __init__(self, Graph, budget, n_features, c):
self.graph = copy.deepcopy(Graph)
self.n_features = n_features
self.M = np.identity(self.n_features)
self.b = np.zeros(self.n_features)
self.b ... |
# Copyright 2020 LMNT, Inc. 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 applicable law or ag... |
import wechatsogou
from collections import Iterable
import json
def show_info(item):
if isinstance(item, Iterable):
for i in item:
print(i)
elif item is None:
print("没有相关信息,抱歉")
else:
print(item)
print("请确定验证码图片后,关闭图片,准确填写验证码!")
print("请确定验证码图片后,关闭图片,准确填写验证码!")
print... |
"""Indy error handling."""
from typing import Type
from indy.error import IndyError
from ...core.error import BaseError
class IndyErrorHandler:
"""Trap IndyError and raise an appropriate LedgerError instead."""
def __init__(self, message: str = None, error_cls: Type[BaseError] = BaseError):
"""Ini... |
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return
n=int(input("enter n "))
r=int(input("enter r "))
if n<1 or r<1:
print("check numbers ")
else:
ans=fact(n)/fact(n-r)
print(ans) |
targets = [int(x) for x in input().split()]
def shout(idx, power, data):
if idx in range(len(data)):
data[idx] -= power
if data[idx] <= 0:
data.pop(idx)
return data
def add(idx, power, data):
if idx in range(len(data)):
data.insert(idx, power)
else:
... |
import matplotlib.pyplot as plt
# 创建画布
plt.figure(figsize=(3, 2), facecolor='lightgrey')
# 绘制空白图形
plt.plot()
# 划分子图
plt.subplot(2, 2, 1)
plt.subplot(2, 2, 2)
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4)
# 设置中文字体
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.suptitle('我是Hello')
plt.tight_layout(rect=[0, 0, 1, 0.9])
p... |
# -*- coding: utf-8 -*-
from django.conf import settings
import re
import operator
OBJECTS_LIST_SEPARATOR = getattr( settings, "OBJECTS_LIST_SEPARATOR","\n")
OBJECTS_TYPE_RE = getattr( settings, "OBJECTS_TYPE_RE", re.compile("^(([^{]+)\.)?([^{]+)") )
MISSION_NOTIFICATION_TOKEN = getattr( settings, "MISSION_NOTIFICA... |
#!/usr/bin/env python3
"""
exercise 2 napalm
"""
from pprint import pprint
from napalm_devices import d_devices, network_devices
from napalm_functions import get_connection, get_backup
suffix = ".txt"
if __name__ == "__main__":
for my_device in network_devices:
print("")
print("Open device conn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class UnfreezeExtendParams(object):
def __init__(self):
self._quit_type = None
self._total_discount_amount = None
self._total_real_pay_amount = None
self._total_task_cou... |
from typing import List
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
lr = [
max(row)
for row in grid
]
tb = [
max(
grid[i][j]
... |
# -*- coding: utf-8 -*-
from collective.transmogrifier.transmogrifier import configuration_registry
from collective.transmogrifier.transmogrifier import Transmogrifier
from optparse import OptionGroup
from optparse import OptionParser
import logging
import mr.migrator
import Products.GenericSetup
import sys
logging.... |
import pika
import time
from config import rabbit_mq_data
credentials = pika.PlainCredentials(rabbit_mq_data['login'], rabbit_mq_data['password'])
connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_mq_data['host'],
rabbit_mq_data['port'... |
import math
import scipy.optimize
import codecad
from codecad.shapes import *
from codecad.util import Vector
import util
import tools
import vitamins
import parameters
from parameters import wheel_clearance
bogie_count = 6 # Count of bogies on both sides of the vehicle
suspension_spacing = 120
arm_clearance = 1... |
# -*- coding: utf-8 -*-
import scrapy
import copy
from selenium import webdriver
class WangyiSpider(scrapy.Spider):
name = 'wangyi'
# allowed_domains = ['www.wangyi.com']
start_urls = ['https://news.163.com/']
def __init__(self):
self.bro = webdriver.Chrome(r'F:\chromedriver_win32\chromedrive... |
# Created By: Jeenal Suthar
# Created Date:
# Last Modified: 22/01/2020
# Description: This module provide Common Configuration Details.
import os.path, time, socket, calendar
from Common.Utils import str_to_bool
from configparser import ConfigParser
class ConfigManagerBase(object):
_instance = Non... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'IQAUTOCLICK.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, ... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Helpers for using libcloud.
"""
from zope.interface import (
Attribute as InterfaceAttribute, Interface, implementer)
from characteristic import attributes, Attribute
from flocker.provision._ssh import run_remotely, run_from_args
def _fixed_OpenS... |
import numpy as np
import glob, os, re, sys, json
import matplotlib.pyplot as plt
from PIL import Image
#get_ipython().magic('matplotlib inline')
def plotBars (f1_scores, elapsed_times):
fig = plt.figure(figsize=(6,6),dpi=720)
subplot = fig.add_subplot(1, 1, 1)
width = 0.05
colors = ['b', 'r', 'g', 'b... |
"""Flanker task
At each trial, a set of arrows is presented at the center of the
screen and the participant must look at the middle arrow, then press the left arrow key if the middle arrow points the left, and the right arrow key if the middle arrow points the right.
"""
import random
from expyriment imp... |
#导包
from rest_framework import serializers
from .models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields = "__all__"
class PicsSerializer(serializers.ModelSerializer):
class Meta:
model=Pics
fields = "__all__"
class GoodsSerializer(seri... |
#!/usr/bin/env python3
import os
import sys
import getopt
import subprocess
import shlex
def usage():
usage = """
servers.py -s SERVER -a start|stop|restart
Usage:
-h --help Prints this help
-a --action Action to perform (stop|start|restart)
-s --server a... |
#!/usr/bin/env python
# Blast putative target query genes against nucleotide biosynthetic clusters databases
import os
import subprocess
import glob
import sys
import math
# BGC0000185 tartrolon Polyketide None
id_to_name = {}
target_to_cluster = {}
f = open("mibig_clusters.txt", 'r')
for line in f.readli... |
# -*- coding: utf-8 -*-
'''
@Author: Lingyu
@Date: 2021-10-19
@Description:
'''
from .db import db, dbse
from .users import *
def init_app(app):
db.init_app(app) |
# voom_mode_python.py
# Last Modified: 2014-04-13
# VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x
# Website: http://www.vim.org/scripts/script.php?script_id=2657
# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)
# License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/
"""
VOoM mark... |
from django.db import models
# Create your models here.
class ProductCategory(models.Model):
name = models.CharField(
verbose_name='наименование',
unique=True,
max_length=128,
)
short_desc = models.CharField(
max_length=256,
blank=True,
verbose_name='краткое ... |
#!/usr/bin/env python
import os, sys, time
import esgf
submission_config = {
'metadata': [
{
'name': 'name',
'value': 'Test publication'
},
{
'name': 'organization',
'value': 'University of Chicago',
},
{
'name': ... |
rate = {224: 1152, 256: 1088, 384: 832, 512: 576}
rot_vals = [
[153, 231, 3, 10, 171],
[55, 276, 36, 300, 6],
[28, 91, 0, 1, 190],
[120, 78, 210, 66, 253],
[21, 136, 105, 45, 15]
]
RC = [
0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
0x00000000... |
from gi.repository import Gtk, Gdk
import threading
import logging
import collections
import os
import datetime
class Ui(object):
(SYM_LIST_NAME,
SYM_LIST_TYPE,
SYM_LIST_SIZE,
THUMB_LIST_NUM_COLS) = range(4)
UI_FILE = 'ui.glade'
def __init__(self, cfg):
self.cfg = cfg
self... |
#coding:utf-8
from simple import (ExtDateField,
ExtStringField,
ExtNumberField,
ExtComboBox,
ExtTextArea,
ExtCheckBox,
ExtTimeField,
ExtHiddenField,
ExtDisp... |
"""
Multimedia Web Databases - Fall 2019: Project Group 17
Authors:
1. Sumukh Ashwin Kamath
2. Rakesh Ramesh
3. Baani Khurana
4. Karishma Joseph
5. Shantanu Gupta
6. Kanishk Bashyam
This is the CLI for task 8 of Phase 2 of the project
"""
from classes.dimensionreduction import DimensionReduction
from classes.globalco... |
# Ch2 Exercise 2.15
# Macky Ruiz
# CIS 007
#
# This program prompts the user to enter the side of a hexagon and displays its area.
#
# /////////////////////////////////////////////////////
# ex: Enter the side: 5.5
# Output: The area of the hexagon is 78.59180539343781
# ////////////////////////////////////////////////... |
data = input('Enter the sentence: ').split()
result = []
i = 0
while i < len(data):
if not data[i] in result:
result.append(data[i])
i += 1
print(' '.join(result))
|
import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag.annotation import Type
from ztag.annotation import Manufacturer
from ztag import protocols
import ztag.test
class FtpSpeedPort(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
por... |
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import L... |
# coding: utf-8
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import math
import random
from sklearn.utils import shuffle
from sklearn.svm import SVC
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
answer = input("Решите пример: 4 * 100 - 54 = ")
print("Правильный ответ: 346")
print(("Ваш ответ: ") + answer)
|
from DOTA_configs._base_.datasets.DIOR_full_ms_test import num_classes, max_bbox_per_img
dataset_config = '../_base_/datasets/DIOR_full_ms_test.py'
|
import boto3, json, os
from sshClient import get_ssh_client, ssh_install_docker_apt, ssh_install_docker_yum, ssh_install_docker_images, load_config_file
def get_key_pair(ec2, private_key_filename):
if private_key_filename not in os.listdir("."):
key_pair_name = private_key_filename.rstrip(".pem")
... |
# 请你来实现一个 atoi 函数,使其能将字符串转换成整数。
#
# 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:
#
#
# 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
# 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
# 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。
#
#
# 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数... |
"""
ID: rk91091
LANG: PYTHON3
TASK: beads
"""
fin = open('beads.in', 'r')
fout = open('beads.out', 'w')
num = int(fin.readline().strip())
beads = fin.readline().strip()
count = [['x', 0]] # placeholder
for bead in beads:
if count[-1][0] == bead:
count[-1][1] += 1
else: count.append([bead, 1])
count.remove(['x'... |
def is_armstrong_number(number):
order = len(str(number))
sum = 0
temp = number
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if number == sum:
return True
else:
return False
|
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
import random
from anapy.datamanip... |
#
# 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 or agreed to in writing, software
# ... |
class Solution(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# node1->node2-> node3
def reverse(head):
node = head
pre = None
while node:
tmp = node.next
node.next = ... |
from rest_framework import generics
from base import mixins
from . import serializers
from .models import Assignment
from .models import Channel
class Assignments(mixins.AdminPermission, generics.ListAPIView):
queryset = Assignment.objects.all()
serializer_class = serializers.AssignmentSerializer
def get... |
from random import randint
#Hangman Game
#all the words available are stored in this list
word_list = []
#this list is used to store above words but without newline characters (rstrip method)
new_word_list = []
#opens file with the list of words in it
with open('hangman_words.txt') as file_obj:
word_list = file_... |
names = ['Ram', 'Raj', 'Amir', 'Shyam']
def filter_names_using_map(name):
if (name.startswith('R')):
return name
def filter_names_using_filter(name):
if(name.startswith('R')):
return True
# else:
# return False
#
filteredNames= list(filter(filter_names_using_filter, names))
# fil... |
from _collections import deque
n = int(input())
r1,c1,r2,c2 = map(int,input().split())
dx = [-2,-2,0,0,2,2]
dy = [-1,1,-2,2,-1,1]
visit = [[False]*(n+1) for _ in range(n+1)]
q = deque()
q.append((r1,c1,0))
visit[r1][c1] = True
def dfs():
while q:
x,y,cnt = q.popleft()
if x == r2 and ... |
import pygame
from pygame.locals import * # 调包
import time
import math
from sys import exit
import random
pygame.init() # 初始化
screen = pygame.display.set_mode((551, 401), 0, 32) # 创建图形化窗口
pygame.display.set_caption("Start Coding Now! 黄金矿工") # 窗口标题
background_start = 'all_start.png' # 加载背景
backGroun... |
"""
Created on 14/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a Python program to count the number of strings where the string length is 2
or more and the first and last character are same from a given list of strings
"""
# initializing a sample list given in problem
sample_List = ['abc', 'xyz', 'aba',... |
from flask import make_response, jsonify
def render(view_func, status=200, *data_dicts):
"""
Wrap the result of a view function as a Flask response object,
given the view function, status code, and data dict that will passed to the function
Argument:
view_func - a function, the function for gen... |
#
# trafficLightDemo.py
#
# Example of a simple state machine modeling the state of a traffic light
#
import statemachine
import trafficlightstate
class TrafficLight(trafficlightstate.TrafficLightStateMixin):
def __init__(self):
self.initialize_state(trafficlightstate.Red)
def change(self):
... |
#Import modules
import os
import csv
#Read through the resource csv file titled "election_data.csv"
election_data = os.path.join("election_data.csv")
election_analysis = os.path.join("election_analysis.txt")
#Open the CSV File & make sure new line is an empty space
with open(election_data, 'r') as csvfile:
#read ... |
import dm3
import time
import struct
import unittest
from Fixture.fixture import *
from Util.decorator import method_tracer
from Util.mixin import *
class TestNandRules(unittest.TestCase):
def setUp(self):
print
print '*********************************************************'
print 'Set up... |
import time
import libtorrent as lt
from werkzeug.urls import url_decode, url_unquote
from flask import Flask, Response, request, render_template
from flaskext.cache import Cache
DEBUG = True
CACHE_TYPE = 'simple'
CACHE_THRESHOLD = 1000
app = Flask(__name__)
app.config.from_object(__name__)
cache = Cache(app)
ses = ... |
#---------------------------------------------------#
#Estructuras de Control de flujo(Condicional If-else)
#---------------------------------------------------#
print("Verificacion de Acceso");
#Pido y almaceno edad usuario
edadUsuario = int(input("Intruduce tu edad: "));
# Valido usuario con if--elif(else if)--else
i... |
from util import readDatabase, AccuracyHistory, showPerformance, showConfusionMatrix
from keras.models import Sequential
from keras.layers.core import Dense, Flatten
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.optimizers import Adam
from keras import backend as K
# Neural network structure fo... |
#!/usr/bin/env python3
from socket import *
import os.path
def checkFile(file):
return os.path.isfile(file)
if __name__ == '__main__':
serverPort = 6969
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(("127.0.0.1",serverP... |
## ========================================================================= ##
## Copyright (c) 2019 Agustin Durand Diaz. ##
## This code is licensed under the MIT license. ##
## utils.py ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/5 16:04
# @Author : SuenDanny
# @Site :
# @File : nn_linear.py
# @Software: PyCharm
import torch
import torchvision
from torch import nn
from torch.nn import Conv2d, Linear
from torch.utils.data import DataLoader
from torch.utils.tensorboa... |
import numpy as np
from sklearn.utils.extmath import randomized_svd
def ols_regression(X, Y):
"""
Performs standard linear regression
:param X: Feature matrix (n, p)
:param Y: Dependent data (n, m)
:return: Linear regression coefficients (p, m)
"""
return np.linalg.solve(np.matmul(X.T, X),... |
import random
numero = random.randint(0,99)
respuesta = int (input ('introduce un numero entre 0 y 99'))
intentos= 0
while respuesta != numero:
if respuesta < numero:
print ("Muy Pequeño")
intentos = intentos + 1
respuesta = int (input ('introduce un numero entre o y 99'))
i... |
import sys
import os
f = open("C:/Users/user/Documents/python/other/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
cand = [1,2,3,4]
def dfs (i):
if i <= 0:
return [["1"],["2"],["3"],["4"]]
temp = []
for j in range(4**i):
for k in range(4):
tmp = dfs(i-1)... |
combustivel = 1.4
desconto = 0.1
litros = float(input("Litros abastecidos: "))
preco = 1.4 * litros
if litros > 40:
preco *= (1-desconto)
print("Custo: {} euros".format(round(preco, 2)))
|
import matplotlib.pyplot as plt
from pandas import date_range, Series, DataFrame, read_csv, qcut
from pandas.tools import plotting
from numpy.random import rand, randn
from pylab import *
import brewer2mpl
from matplotlib import rcParams
#colorbrewer2 Dark2 qualitative color table
dark2_colors = brewer2mpl.get_map('Da... |
def dynamicArray(n, queries):
# Write your code here
last_answer = 0
result = []
seq_list=[]
for a in range(n):
seq_list.append([])
for i in range(len(queries)):
query = queries[i]
if query[0] == 1:
seq = ((query[1] ^ last_answer)%n)
seq_l... |
'''
Delete contents of s3 bucket (so that delete-stack call will work)
'''
import boto3, sys
if len(sys.argv) == 1:
print ("must pass the bucketname you want to delete contents from")
sys.exit()
else:
bucketname = sys.argv[1]
client = boto3.client('s3')
s3 = boto3.resource('s3')
paginator = client.get_pag... |
n=int(input())
for i in range(n):
a,b=input().split()
a,b=[int(a),int(b)]
if a==b:
if a%2==0:
print(a*2)
else:
print(a*2-1)
elif a-b==2:
if a%2==0:
print(a+b)
else:
print(a+(b-1))
else:
print("No Number")
... |
ipt = []
a, b, c = map(int, input().split(' '))
ipt.append(a)
ipt.append(b)
ipt.append(c)
ipt.sort()
print(ipt[1])
|
#!/usr/bin/env python
from pylab import *
import PylabUtils as plu
if __name__ == '__main__':
xPrime = array ([[-1, 1, 1],
[1, 1, 1],
[1, -1, 1],
[-1, -1, 1]]).T
x = array ([[0, 0, 1],
[640, 0, 1],
[640, 480, 1],
... |
import json
dic=json.load(open("cal.json"))
dic_se=json.load(open("se.json"))
def Count_cal(text_food, text_exe):
val = 1785
count = 0
cal_val = 0
burn_val = 0
list_food = text_food.split(",")
list_exe = str(text_exe)
print(list_food)
for data in dic:
for item in list_food:
... |
import cv2
import numpy as np
import flycapture2 as fc2
import time
import datetime
import sys
def getXY(img, colorMin, colorMax, threshVal, size_rank_of_target):
# imgt = cv2.inRange(img, colorMin, colorMax) # restricts to a color range
rv, imgt = cv2.threshold(imgr, threshVal, 255, cv2.THRESH_BINARY_INV) #t... |
import hyperneat
import numpy
import os
import sys
from art_basics import *
from render_help import *
nm=novelty_mapper()
import glob
from PIL import Image
def render_nov(direc,gen,out):
arcsize=len(glob.glob("%s/generation%d/archive*" %(direc,gen)))
for k in range(arcsize):
to_render = "%s/generation%d/archive... |
"""Testing for days between challenge."""
from days_between import days_diff
def test_same_day():
"""The difference between the same day is 0."""
assert days_diff((1982, 4, 19), (1982, 4, 19)) == 0
def test_it_can_return_a_few_days_apart():
"""Return the difference in two close together days."""
ass... |
import json
from flask_login import login_user, login_required, logout_user
from itsdangerous import TimestampSigner, BadSignature, URLSafeSerializer, SignatureExpired
from SampleApp.DataManagement.db import User
from SampleApp import db, login_manager
from flask import (
Blueprint, request, Response, session
)
... |
try:
a = 5/0
except Exception as e:
print(e)
try:
a = 5/0
except Exception as e:
print(e)
finally:
print("Final block")
#If use return in try block ,except block wont execute but final block get execute
def exam():
try:
a = 5/0
return 0
except Exception as e:
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.