text stringlengths 38 1.54M |
|---|
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
self.func(*args, **kwargs)
print("Function Executed")
print("\n")
@MyDecorator
def function():
print("SHREYANSH KUMAR")
if __name__ == "__main__":
function() |
from PySide import QtCore, QtGui
import sys
class MyCounter(QtCore.QObject):
def __init__(self):
QtCore.QObject.__init__(self)
self.__data = 0
def setValue(self, value = 1):
try:
value = int(value)
if value < 0 or value > 50:
return
... |
#/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 19:44:26 2019
@author: Martina Cerina
Workdirectory: /Users/ludovicaflocco/Desktop/Machine_Learning
"""
# Loading Libraries
import pandas as pd
import statsmodels.formula.api as smf # regression modeling
import seaborn as sns
import matplotlib.p... |
# Explicacion de condicionales
# Funcion para recibir datos desde consola
# input()
# int()
# Operadores Logicos
# ==, <, >, <=, >= // or, and
'''
# =========================================
camisa = 1
if camisa == 1: # Expresion Logica
# Sentencia o acciona ejecutar si se cumple la expresion logica
print("... |
# Generated by Django 2.2 on 2019-04-26 10:45
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='project',
nam... |
# Volatility
# Copyright (C) 2012-13 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation. You may not use, modify or
# distribute... |
import shutil
import subprocess
import tempfile
from urllib.parse import urlparse, urlunparse
from CommonServerPython import *
''' GLOBALS '''
HOSTNAME = ''
USERNAME = ''
PORT = ''
SSH_EXTRA_PARAMS = ''
SCP_EXTRA_PARAMS = ''
DOCUMENT_ROOT = ''
CERTIFICATE_FILE = tempfile.NamedTemporaryFile(delete=False, mode='w')
IN... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import random
import time
import os
import numpy as np
from optparse import OptionParser
import torch
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.autograd import Variable
from torch.optim.lr_scheduler import La... |
# -*- coding=utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def ConvertCN(s):
return s.encode('gb18030')
print (ConvertCN("fdÄã")) |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import conv_params, linear_params, bnparams, bnstats, \
flatten_params, flatten_stats
import numpy as np
class WideResNet(nn.Module):
def __init__(self, depth, width, ninputs = 3,
num_groups = 3, num_classes = ... |
# -*- coding: utf-8 -*-
from yacc import yacc, willow_list
import lis as lis
def main():
with open('testfile.c', 'r') as content_file:
content = content_file.read()
AST = yacc.parse(content)
print AST
if AST != None:
lis.eval(AST)
main() |
from .base import *
DEBUG = False
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST =get_secret("EMAIL_HOST")
EMAIL_PORT = get_secret("EMAIL_PORT")
EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = get_secret("... |
def main(inp_str):
'''
inp_str: input data
return: vowels used in the string
'''
vowels = ['a', 'e', 'i', 'o', 'u']
result = ''
for each_vow in vowels:
if each_vow in inp_str:
result = result + each_vow
return result
if __name__ == '__main__':
text1 = "Moon fl... |
import utils
import numpy as np
import tensorflow as tf
# must match what was saved
batch_size = 128
num_hidden_units = 200
num_layers = 3
num_tweets = 50
max_tweet_len = 20
top_n = 20
X_train, Y_train, index_to_word, word_to_index, vocab_size, unknown_lookup = utils.load_dataset()
vocab_size += 1 # due to 0 bein... |
from bs4 import BeautifulSoup
filePath = r"/home/huizi/文档/test.html"
file = open(filePath,'r')
html = file.read()
bs = BeautifulSoup(html,'html.parser')
print(bs.title)
# print(bs.prettify()) # 格式化html结构
print(bs.find_all('span'))
file.close()
|
import pyglet
import robocute.sprite
from robocute.base import *
LAYER_ANY = -1
LAYER_DEFAULT = 0
class Layer(Base):
def __init__(self, parent, name = None, order = LAYER_ANY):
super().__init__()
self.parent = parent
self.name = name
self.order = order
if p... |
import ssl
import socket
from pprint import pprint
HOSTNAME = "www.google.com"
context = ssl.create_default_context()
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
#context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
conn = context.wr... |
"""Play the actual game."""
from modules.board import Board
from modules.baseboard import BeyondBoardError, OccupiedCellError, \
print_color, input_color
UI_C = (120, 255, 200)
def play_game():
"""Activate the game logic."""
board = Board()
print_color("Game starts!", fg=UI_C)
# select order
w... |
import os
from flask_sqlalchemy import SQLAlchemy
db_path = os.environ['DATABASE_URL']
# comment out the line above
# and uncomment the line below to prepare for local development and/or testing
# db_path=UNCOMMENT THIS LINE AND INSERT THE PATH TO YOUR DATABASE HERE
db = SQLAlchemy()
def setup_db(app, database_pat... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
path('gethelp', views.gethelp, name='gethelp'),
path('volunteer', views.volunteer, name='volunteer'),
path('blogs', views.blogs, name='blogs'),
path('co... |
'''
https://docs.python.org/3/library/stat.html
https://www.tutorialspoint.com/python/os_stat.htm
https://www.geeksforgeeks.org/python-os-stat-method/
https://docs.python.org/3/library/stat.html?highlight=filemode
https://kb.iu.edu/d/abdb
Permission Number
Read (r) 4
Write (w) 2
Execute (x) 1... |
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Count
from django.shortcuts import get_object_or_404, redirect, re... |
n,k,p=map(int,input().split(" "))
a=list(map(int,input().split(" ")))
s=input()
def count(a):
for i in range(len(s)):
if(s[i]=='?'):
count(a,k)
else:
c=a[n-1]
for j in range(n-1):
|
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from dashboard.forms import NewGroupForm, NewStudentForm, NewTeacherForm,\
AddHomeworkForm, NewPasswordForm
from django.core.urlresolvers import reverse
from common.models import Group, ... |
import json
from pprint import pprint
import requests
from praw import Reddit
from dotenv import load_dotenv
import os
import shutil
from config import dotenv_path, submission_download_dir
from log import get_logger
logger = get_logger(__name__)
load_dotenv(dotenv_path)
reddit = Reddit(client_id=os.environ.get('R... |
import pygame
import sys
data = [
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0... |
"""cowork URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
# Django imports
from django.conf.urls import include, url
from django.urls import include, path
from django.contrib import admin
from django.contri... |
"""
lab 3
"""
# 3.1
str_list = ['a','d','e','b','c']
print(str_list)
str_list.sort()
print(str_list)
# 3.2
str_list.append('f')
print(str_list)
# 3.3
str_list.remove('d')
print(str_list)
# 3.4
print(str_list[2])
# 3.5
my_list = ['a','123',123,'b','B','False',False,123,None,'None']
print(len(set(my_list)))
# 3.6
pr... |
#!/usr/bin/python3
# OOP
def fishing():
print('Fishing')
class GoldenFish:
def __init__(self):
weight = 0.13
def swim(self):
print('Swimming')
def eat(self):
print('Eating')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename @ spark_conf.py
# Author @ gouhao
# Create date @ 2017-07-28
"""
The LAST_TIME_PATH is the middle file used to record the last completed application finished time.
First collection should run a long time due to default last time is null
which mak... |
#!/usr/bin/env python3
# Copyright (C) 2019 The Android Open Source Project
#
# 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 requ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 18:15:45 2020
@author: IKM1YH
"""
# Imports
import sys
import numpy as np
import scipy
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.gridspec as gridspec
import seab... |
from ..types import register, PlumModule, HP, P, props
from .activation_function import ActivationFunction
import torch
from .functional import linear, dropout
@register("layers.fully_connected")
class FullyConnected(PlumModule):
in_feats = HP(type=props.POSITIVE)
out_feats = HP(type=props.POSITIVE)
has_... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
#Item A
def f(x): #defino a funcao primeiro quadrante do circulo unitario
return np.sqrt(1-x**2)
def monte_carlo(seed_x, seed_y):
cont_dentro = 0 #contador para pontos dentro do circulo
cont_total = 0 #contador para o to... |
# Copyright (c) 2014 Alcatel-Lucent Enterprise
# 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
#
# Un... |
# -*- coding:utf-8 -*-
from pykafka import KafkaClient
import codecs
import logging
logging.basicConfig(level=logging.INFO)
class kafka(object):
def __init__(self, ip, port, topic):
"""
:param ip: kafka的IP
:param port: kafka的port
:param topic: kafka的topic
"""
self.... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, response
from django.urls import reverse
from .models import Quizapplication
# Create your views here.
def home(request):
app = Quizapplication.objects.all()
if request.method == 'POST':
ans... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program: hola_test.py
# Description: Este programa prueba el modulo hola usando UnitTest
# Author: Diego Fernando Marin
# Standard Test imports
from __future__ import unicode_literals
import unittest
import sys
# Add the module location to the search path
sys.path.ins... |
#suponiendo que me acuerdo bien del ejercicio
from validadorDatos import validarDatoNumerico
def validarDatoBool(mensaje):
while True:
try:
dato = str(input(mensaje))
if dato.upper() == "S" or dato == "N":
break
else:
raise Except... |
from keras.models import Sequential
import keras
from keras.utils import to_categorical
from keras.layers import Dense, Conv1D, Conv2D, Flatten, Reshape, MaxPooling1D, MaxPooling2D, GlobalAveragePooling1D, Dropout, BatchNormalization
import pandas as pd
from sklearn.model_selection import train_test_split
from joblib i... |
"""
A collection of EOTasks for feature manipulation
"""
from .bands_extraction import EuclideanNormTask, NormalizedDifferenceIndexTask
from .blob import BlobTask, DoGBlobTask, DoHBlobTask, LoGBlobTask
from .clustering import ClusteringTask
from .doubly_logistic_approximation import DoublyLogisticApproximationTask
fro... |
str = "Manohar Singh"
#str = "Manohar Singh"
print(str)
#str[0] = "M"
print(str[0])
#str[0:5] = "Manoh"
print(str[0:5])
#str[0:] = "Manohar Singh"
print(str[0:])
#str[:5:2] = ""
print(str[::-1]) |
import tweepy
import csv
import pandas as pd
# so that emojis don't
import sys
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
def collect(csvFileName,startTime,endTime):
####input your credentials here
#For account @TeamBot123 , TRXBot
consumer_key = 'aD0VdJEhOmG27pALUanzBwvuv'
... |
from django.shortcuts import render
from django.http import HttpResponse
import mysql.connector
from datetime import datetime
# Create your views here.
def index(request):
if request.method == 'POST':
konu = request.POST['konu']
katılımcılar = request.POST['katılımcılar']
bsaat = request... |
#
# @SI_COPYRIGHT@
# @SI_COPYRIGHT@
#
import os
import stack.commands
from stack.exception import *
import struct
import socket
from itertools import groupby
from operator import itemgetter
class Command(stack.commands.Command,
stack.commands.HostArgumentProcessor):
"""
Output the PXE file for a host
<arg name=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/8/8
@Author : AnNing
"""
import numpy as np
from pyproj import Proj, transform
# 角度 -> 弧度
DEGREES_TO_RADIANS = np.pi / 180.
# 弧度 -> 角度
RADIANS_TO_DEGREES = 180. / np.pi
# 地球平均半径
EARTH_MEAN_RADIUS_KM = 6371.009
# 地球极半径
EARTH_POLAR_RADIUS_KM = 6356.752
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 20:46:50 2018
@author: shubham
"""
n = int(input())
for _ in range(n):
N = int(input())
if 360 % N == 0:
ans = 'y'
else:
ans = 'n'
if N <= 360:
ans1 = 'y'
else:
ans1 = 'n'
if (N*(N+1)/2) <=... |
#!/usr/bin/env python
# Script for localizing the Campus Rover using April Tags. For this script to work, tags
# need to be postioned on a premade map and coordiantes need to be found (these are then stored
# in sendTransform call at the end of the script, currently hardcoded for testing).
import rospy
import tf
from... |
from collections import namedtuple
from suds import WebFault
from api_exception import api_exception
from entity import entity
import util
class enum_zone(entity):
"""An ENUM Zone object in BAM
ENUM zones provide voice over IP (VoIP) functionality within a DNS server.
The system requires DNS to manage t... |
import os
from flask import Flask, render_template, redirect, url_for, escape, request
from datetime import datetime
import sqlite3 as sql
app = Flask(__name__)
@app.route('/')
def new():
return render_template('home.html')
@app.route('/enternew')
def new_entry():
return render_template('entry.html')
@app.r... |
from distutils.core import setup
from setuptools import find_packages
setup(name='hello-zmq',
version='0.1',
description='python implementation of RFC-424242',
packages=find_packages(),
requires=[
'pyzmq',
'docopt',
]
)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 17:16:11 2019
@author: sunyue
"""
"""
步骤:
1. 输入X,Y
2. 计算协方差矩阵
3. 将协方差矩阵进行特征值分解
4. 取特征值和特征向量。如取10个特征,就选择最大的10个特征值和其对应的特征向量 n_components = 10
5. 将得到的特征值和特征向量向原空间映射
"""
"""
下面代码是使用sklearn中的一个样例数据集进行PCA,将64维矩阵化为2维并展示出来
"""
import numpy as np
f... |
import numpy as np
import matplotlib.pyplot as plt
#Draw graph of pseudo-delta functions
xs=np.arange(-5,5.1,.1)
ks=[1,2,4]
for k in ks:
ys=[1/(1+np.exp(k*x)) for x in xs]
plt.plot(xs,ys,label='k='+str(k))
plt.legend()
plt.grid()
plt.show()
|
# Generated by Django 3.0.8 on 2020-09-23 02:13
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auction', '0022_auto_20200921_2249'),
]
operations = [
migrations.AddField(
model_name='bids',
name=... |
#Importations And Value Table Creation#
from random import randint
bot_field = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0,... |
import unicodedata
import ast
import file_save_load as fsl
######################################################
# adding new budgets
######################################################
fileNameDataset = 'imdb_dataset_v7_no_plots'
fileNameBudgets = '_wiki_plot_for_' + fileNameDataset
actors_amount =... |
import torch
from torch.autograd import grad
import funcsigs
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import truncnorm
import implementation.pytorch_autograd.aux_funcs_torch as fs
from scipy.io import loadmat, savemat
from implementation.pytorch_autograd.nuts import NUTS, Metropolis
### FU... |
import uuid
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models import F
from django_extensions.db.models import TimeStampedModel
from django.utils.crypto import get_random_string
def generate_api_token():
return get_random_string(64)
class Project(TimeStampedMo... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: weixin.py
@time: 16-7-13 下午6:20
"""
import json
import time
import hashlib
from config import APPID, APPSECRET, WECHAT_URL, WECHAT_TOKEN
from app.lib.sign import Sign
from flask import Blueprint, request, make_response, render_tem... |
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 2):
if l == c:
matriz[l][c] = 1
else:
matriz[l][c] = (l+1) ** 2
print('=-'* 15)
for l in range (0, 3):
for c in range(0, 2):
print(f'[{matriz[l][c]:^5}]', end='')... |
#!/usr/bin/python3
# import mysql.connector as ms
import os
from termcolor import colored,cprint
from colorama import init
import pyfiglet
from basic_op import addrec,delrec,searchrec,disprec,mailfun
from modfun import modrec
from tqdm import tqdm,trange
from time import sleep
from filereader import freader
from prett... |
bicycles=['trek','cannondale','readline','specialized']
too_expensive='readline'
bicycles.remove(too_expensive)
print('\nA '+too_expensive+' is too expensive to me.')
|
#!/usr/bin/env python3
import sys
import os
import re
filename_fa = sys.argv[1]
filename_base = re.sub(r'.fa$', '', os.path.basename(filename_fa))
# Kmer length
kmer_len = int(sys.argv[2])
kmer_tag = '%dmer' % kmer_len
seq_list = dict()
f_fa = open(filename_fa, 'r')
for line in f_fa:
if line.startswith('>'):
... |
#! /usr/bin/env python3
if(__name__ == "__main__"):
nums = input()
list1 = list(map(int, nums.split(' ')))
list2 = []
list2.append(str(list1[0] % list1[1]))
list2.append(str(list1[0] // list1[1]))
list2.reverse()
print(' '.join(list2)) |
import time
import krpc
import math
kp = 0.02
kd = 0.5
ki = 0.00001
s = (0, 0, 0)
target_port_selected = False
# 连接服务器
conn = krpc.connect(name='Docking Test')
vessel = conn.space_center.active_vessel
vessel_port = vessel.parts.docking_ports[0]
target_vessel = conn.space_center.target_vessel
#target_port... |
# steps[n] is the steps required for n, or 0 if not yet computed
steps = {1: 0}
def count(n):
if n not in steps:
if n%2==0:
steps[n] = 1 + count(n//2)
else:
steps[n] = 1 + count(3*n+1)
return steps[n]
best_n, best_count = 0, 0
for n in range(2, 1000000):
c = count(... |
from sklearn.model_selection import train_test_split, StratifiedKFold
import pandas as pd
from pytorch_tabular import TabularModel
from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig
from pytorch_tabular.models import TabNetModelConfig, TabNetModel, NodeConfig
from sklearn.metrics import confu... |
n1 = float(input("Digite a primeira nota: "))
n2 = float(input("Digite a segunda nota: "))
media = (n1 + n2)/2
if media < 5:
print("Reprovado!")
elif media >= 5 and media < 7:
print("Recuperação")
elif media >= 7:
print("Aprovado!")
|
import os
import yaml
from aiohttp import web
import aiohttp_cors
from utils.mongodb import MongoDB
from routes.animal import Animal
# loader config.yaml
configFile = os.path.abspath(os.path.expanduser('config.yaml'))
with open(configFile, 'r') as f:
config = yaml.load(f)
HTTP_SERVER = config['http-server']
MON... |
from pprint import pprint
champions = [
(2014, 'San Antonio Spurs'),
(2015, 'Golden State Warriors'),
(2016, 'The Cleveland Cavaliers'),
(2017, 'Golden State Warriors'),
(2018, 'Golden State Warriors'),
]
pprint({c[0]: c[1] for c in champions})
# Example: nonunique keys
pprint({c[1]: c[0] for c in champions... |
a,b,c=input(" ").split()
if (a>b)and(a>c):
print(a)
elif (b>a)and(b>c):
print(b)
else:
print(c)
|
import requests, re, os
from bs4 import BeautifulSoup
def stock_price(symbol: str = "ABCDEFGHIJKLMNOPQRSTUV") -> str:
url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}"
soup = BeautifulSoup(requests.get(url).text, "html.parser")
class_ = "My(6px) Pos(r) smartphone_Mt(6px)"
return soup.fi... |
#!/usr/bin/env python
#
# Poll the Bitfinex order book and print to console.
#
# Author : Scott Barr
# Date : 29 Mar 2014
#
import os, sys
from datetime import datetime
import bitfinex
# symbol to query the order book
symbol = 'btcusd'
# set the parameters to limit the number of bids or asks
parameters = {'limit_... |
#!/usr/bin/env python
'''
classify_video.py will classify a video using:
(1) singleFrame RGB model
(2) singleFrame flow model
(3) 0.5/0.5 singleFrame RGB/singleFrame flow fusion
(4) 0.33/0.67 singleFrame RGB/singleFrame flow fusion
(5) LRCN RGB model
(6) LRCN flow model
(7) 0.5/0.5 LRCN RGB... |
#2000到3200之间,可以被7整除,不是5的倍数
l = []
for i in range(2000,3201):
if (i%7 == 0) and (i%5!=0):
l.append(str(i))
print(l)
'''
学习点: 学习到如何将循环元素加到一个列表中 l.append(str(i))
''' |
import cx_Oracle
cx = cx_Oracle.connect('jiayuan/jiayuan@192.168.1.38/orcl')
sql = cx.cursor()
print()
print()
rst1 = sql.execute('select sum(cnt)/10000 from (select count(*) as cnt from get_id_1 union all select count(*) from get_id_2 union all select count(*) from get_id_3 union all select count(*) from get_id_4)')
... |
import socket
import sys
ip = sys.argv[1]
port = int(sys.argv[2])
x = int(sys.argv[3])
y = int(sys.argv[4])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
print("Connected to server!")
#Read board in
file = 'opponent_board.txt'
with open(file) as f:
board = f.readlines... |
"""
[1,2,3,4,5,6]
1. Reverse the list [6,5,4,3,2,1]
2. Print Last element from list
3. Print element third and forth element from list
"""
list = [1,2,3,4,5,6]
# Reverse the list
print(list[::-1])
# Print Last element from list
print(list[-1])
# Print element third and forth element from list
print(list[2:4])
|
import logging
import re
import pytest
import requests
from helpers.cluster import ClickHouseCluster
@pytest.fixture(scope="module")
def cluster():
try:
cluster = ClickHouseCluster(__file__)
cluster.add_instance(
"node",
main_configs=[
"configs/config.d/st... |
# forを使った辞書変数の値の取り出し
we = {'金':'Fri', '土':'Sat', '日':'Sun'}
for keys in we:
print(keys)
for value in we.values():
print(value)
for item in we.items():
print(item)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-04 12:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('social', '0019_auto_20170804_1712'),
]
operations = [
migrations.RemoveField(
... |
from numpy import*
vetor = array(eval(input()))
med = sum(vetor)/size(vetor)
print(size(vetor))
print(vetor[0])
print(vetor[-1])
print(max(vetor))
print(min(vetor))
print(sum(vetor))
print(round(med,2)) |
import os
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__name__)
ap... |
from oop.advanced_oop.class_method import Spam
class Sub(Spam):
num_instances = 0
def print_num_instances(cls):
print('Extra Stuff...', cls)
Spam.print_num_instances()
print_num_instances = classmethod(print_num_instances)
class Other(Spam):
pass
x = Sub()
y = Spam()
x.print_num_... |
import tensorflow as tf
a=tf.constant([1,2,3,4,5,6], shape=[2,3], name="a")
b=tf.constant([1,2,3,4,5,6], shape=[3,2], name="b")
c=tf.matmul(a,b)
sess=tf.Session(config=tf.ConfigProto(log_device_placement=True))
print sess.run(c)
#print sess.run(a)
#print sess.run(b)
|
import time
from api.base.base_api import BaseApi
from api.base.dto.api_output import ApiOutput
"""
所有 API 的统一入口
"""
class ApiExecutor:
@staticmethod
def execute(request) -> ApiOutput:
start_time = time.time()
# 创建 api 入参对象
api_params = ApiExecutor.build_api_params(request)
... |
import matplotlib.pyplot as plt
class MultiplePlot:
def __init__(self, size, _dimensions):
self.ax = []
self.images_num = 0
self.fig = plt.figure(figsize=size)
self.dimensions = _dimensions
def add(self, image, title, _cmap='gray'):
self.images_num += 1
self.ax... |
import matplotlib.pyplot as pl
import sys
import math
def allBinaryStrings(t):
if t == 0:
return [""]
oneLess = allBinaryStrings(t-1)
returnList = []
for i in oneLess:
returnList.append(i+"0")
returnList.append(i+"1")
return returnList
def countSwitches(s, originalChar="0"):
if len(s) == 0:
return... |
# Generated by Django 2.0.4 on 2018-04-08 13:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Codelab',
fields=[
... |
import os
import torch
import numpy as np
import pandas as pd
import torch.nn.functional as F
from dataset.data_functions import SS3_CLASSES, SS8_CLASSES, get_angle_degree, get_unnorm_asa, get_unnorm_asa_new
def classification(data_loader, model1, model2, model3, model4, model5, mean, std, device):
model1 = model... |
#!/usr/bin/env python
import tornado.ioloop
import tornado.iostream
import tornado.netutil
import hexdump
import socket
class ServerOnline(object):
def on_connected(self):
print '%s:%d OK' % (self.host, self.port)
def connect(self, host, port):
self.host = host
self.port = port
... |
8# -*- coding: utf-8 -*-
from utils import equals,sprint
from avepayoff import avePayoff_cal
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
# generate possible strategies of q with increment of 0.1
def candvector():
epsilon = 0.001
vector = []
for v in range(0,11):
... |
#110106654 Mar/16/2021 17:07UTC+5.5 Shan_XD 379A - New Year Candles PyPy 3 Accepted 93 ms 0 KB
a,b= map(int,input().split())
count=a
burn=a
while(burn>=b):
count+=burn//b
rem=burn%b
burn=burn//b+rem
print(count)
|
# Generated by Django 2.0.3 on 2019-11-14 06:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_article_is_addtimeline'),
]
operations = [
migrations.AlterField(
model_name='article',
name='is_addtim... |
N = int(input())
a = [0] * 100
a[0] = 2
a[1] = 1
for i in range(2, 100):
a[i] = a[i-1] + a[i-2]
print(a[N]) |
"""
* Copyright 2020, Departamento de sistemas y Computación
* Universidad de Los Andes
*
*
* Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
... |
#! /usr/bin/python3.6
# coding: utf-8
from bot_app import app
if __name__ == "__main__":
app.run(debug=True)
|
import requests
from bs4 import BeautifulSoup
from urllib.parse import unquote
import json
import re
base_url = "https://open.spotify.com/embed/playlist/{}"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
class SpotifyWeb... |
#!/usr/bin/env python
import os
import time
from ConfigParser import SafeConfigParser
import tarfile
#This script is based on:
#http://codepoets.co.uk/2010/python-script-to-backup-mysql-databases-on-debian/
#http://stackoverflow.com/questions/5849999/how-to-make-tar-backup-using-python
config = SafeConfigParser()
co... |
from typing import List
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
from collections import defaultdict
graph = defaultdict(list)
visited = set()
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.