text stringlengths 8 6.05M |
|---|
#!/usr/bin/python3
# python3 Othello.py
#
# COMP3270 Mini-Project
# Yan Kai
# UID: 3035141231
#
"""
This is an Othello game implemented with Python3.
The AI is based on the minimax search algorithm with alpha-beta pruning.
A history table is introduced to accelerate searching.
The GUI is implemented using Tkin... |
# -*- coding: utf-8 -*-
import scrapy
class BaiduSpider(scrapy.Spider):
name = 'baidu'
allowed_domains = ['www.baidu.com']
start_urls = ['http://www.baidu.com/']
custom_settings = {
'DEFAULT_REQUEST_HEADERS': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
... |
from ivis import Ivis
from sklearn import datasets
from sklearn.preprocessing import MinMaxScaler
from ivis_animate import IvisAnimate
digits = datasets.load_digits()
X = digits.data
X = MinMaxScaler().fit_transform(X)
model = Ivis(embedding_dims=2, k=32,
epochs=1)
animation = IvisAnimate(model, frames=500).... |
#! /usr/bin/python
from logging import getLogger, ERROR
getLogger("scapy.runtime").setLevel(ERROR)
from scapy.all import *
import sys
from datetime import datetime
from time import strftime
try:
target = raw_input("[*] Enter Target IP Address: ")
min_port = raw_input("[*] Enter Minimum Port Number: ")
max_... |
# Leitura
with open('pessoas.csv', 'r') as f:
# print(f.readlines())
headers = f.readline().split(';')
print(headers)
selecionados = []
for line in f:
data = line.split(';')
op = input(f'Deseja selecionar a pessoa {data[0]}? (s\\n) ')
if op.lower() == 's':
sele... |
intro_and_difficulty_prompt = """\nHello! This is a fill-in-the-blanks style American history trivia game.\n
Please select a difficulty by typing in easy, medium, or hard. \n\n"""
easy_test = """Originally, America had __1__ colonies. The 16th president
of United States was __2__. As of 2016, the United States con... |
from google.appengine.dist import use_library
use_library('django', '1.2')
#from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from app.api import api
def main():
applicati... |
# made
# relevance feedback if user download ittenary
import settings
import json
# input : array of downloaded place id
# Update sum of download in
def update_downloads(pid):
place = settings.places[pid]
if place.get("feedback"):
cmax = place["feedback"]["download"]
cmax += 1
setting... |
class A:
def __init__(self):
print("I am default const of A")
class B(A):
def __init__(self):
super().__init__() # calling super class const
print("I am default Const of B")
#---------------------
b1 = B()
|
def digadd(n):
num_ref = [9,1,2,3,4,5,6,7,8]
if n > 0:
results = num_ref[n % 9]
else:
results = 0
return results
print digadd(n)
|
#Title: Neural Network on prediction of cleavage sites
#Author: Changpeng Lu
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
from keras import regularizers
#Helper Libraries
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import warnings
warnings.filterwarnings('ignore')
import pan... |
import logging
from seat.models.exam import Exam
logger = logging.getLogger(__name__)
class ExamApplication(object):
"""description of class"""
def get_exam_by_id(self, exam_id):
try:
exam = Exam.objects.get(id=exam_id)
return exam
except Exception, error:
... |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from film.models import categories, actors, Director, origin, categories_film
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_... |
from collections import namedtuple, deque
from enum import Enum
import logging
import os.path
import datetime as dt
import numpy as np
import imageio
import cv2
Frame = namedtuple('Frame', ['filename', 'frame_number', 'img_data', 'timestamp'])
ExtractedChip = namedtuple('ExtractedChip', ['filename', 'frame_number', '... |
import cv2 as cv
import numpy as np
# #图像就是一个(或几个)矩阵组成的,图像有其属性:通道数目,高与宽,图像类型等
# ##读取图像的属性
def get_image_info(image):
print(type(image))
print('图像形状', image.shape)
print('图像大小', image.size)
print(image.dtype)
pixel_data = np.array(image)
print(pixel_data)
# 读取视频
def vide... |
from setuptools import setup, find_packages
from apkdl import __version__
import os
setup(
name ='apkdl',
version = __version__,
description = 'Search and download APKs from the command line',
url = 'https://github.com/sereneblue/apkdl',
author = 'sereneblue',
license = "MIT",
packages = find_packages(),
class... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
# Import BaseEventHandler
from tonga.models.handlers.event.event_handler import BaseEventHandler
# Import StoreBuilderBase
from tonga.stores.manager.kafka_store_manager import KafkaStoreManager
# Import BaseProducer
from tonga.services.producer.base imp... |
import time
import math
from flask import session
from sqlalchemy import Column, Integer, String, Text, ForeignKey, Table, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from apps.db import engine, dbsession
from common.serializer import objToDict, list... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import configparser
from multiprocess import Pool
from datetime import datetime
from device.bras import ME60, M6k
from py2neo import authenticate, Graph, Node
from funcy import lmap, partial, compose, map
basFile = 'bras.txt'
logFile = 'result/bas_log.txt'
infoFi... |
#!/usr/bin/python
"""
Demonstration of Graph and BokehGraph functionality.
"""
import random
from sys import argv
from graph import Graph
from draw import BokehGraph
def getGraph(**kwargs):
graph = Graph() # Instantiate your graph
graph.add_vertex(0)
graph.add_vertex(1)
graph.add_vertex(2)
graph... |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
nl = len(needle)
if nl == 0:
return 0
for i in range(0, len(haystack)-nl):
if haystack[i:i+nl] == nee... |
def char_mixing(a, b):
a1 = b[:2] + a[2]
b1 = a[0:2] + b[2]
return a1 + ' ' + b1
print(char_mixing("abc", "xyz"))
|
n = int(input("Digite um número: "))
print('sucessor: {}, antecessor: {}'.format(n + 1, n - 1)) |
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com
# miTorch: Medical Imaging with PyTorch
# Deep Learning Package for 3D medical imaging in PyTorch
# Implemented by Mahdi Biparva, April 2021
# Brain Imaging Lab, Sunnybrook Research Institute (SRI)
import argparse
from copy import deepcopy
import functoo... |
# -*- coding: utf-8 -*-
# Version: 1.0.0
__author__ = 'John Lampe'
__email__ = 'dmitry.chan@gmail.com'
import requests
import pdb
class tmobile:
def __init__(self, ip, port, verify=False):
self.ip = ip
self.port = port
self.base_url = "http://{}:{}".format(ip, port)
self.session ... |
"""
This provide some common utils methods for YouTube resource.
"""
import isodate
from isodate.isoerror import ISO8601Error
from pyyoutube.error import ErrorMessage, PyYouTubeException
def get_video_duration(duration: str) -> int:
"""
Parse video ISO 8601 duration to seconds.
Refer: https://develo... |
from glob import glob
import numpy as np
import cv2 as cv
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
import seaborn as sns
from sklearn.metrics import accuracy_sc... |
def copy_n_times(filepath,repetitions):
with open(filepath,"r") as getdata:
content = getdata.read()
# print(content)
for i in range(repetitions):
with open(filepath,"a+") as mytext:
mytext.write("\n")
mytext.write(content)
copy_n_times("files/data.txt"... |
"""
Longest common subsequence problem
"""
import json
from tokenizer import tokenize
def tokenize_by_lines(text: str) -> tuple:
"""
Splits a text into sentences, sentences – into tokens,
converts the tokens into lowercase, removes punctuation
:param text: the initial text
:return: a list of sente... |
# -*- coding: utf-8 -*-
import re
from pycolorname.color_system import ColorSystem
class Wikipedia(ColorSystem):
def __init__(self, *args, **kwargs):
ColorSystem.__init__(self, *args, **kwargs)
self.load()
def refresh(self):
full_data = self.request(
'GET',
... |
end = 0
ok = False
lst = []
while end < 9:
i = list(input("Enter {} line of sudoku: ".format(end+1)))
end += 1
lst.append(i)
check_list = [chr(x + ord('0')) for x in range(1, 10)]
trans_lst = [[lst[j][i] for j in range(len(lst))] for i in range(len(lst[0]))]
for rows in lst:
if sorted(rows) == check_li... |
import random
#number_per_file = 100
dir = 'data/generation-projet-test/'
def save_test_file():
with open(dir+'ask_for_recipe-newP-newV-test.bio','r') as f:
a1 = f.read()
text_a1 = a1.split('\n\n')
with open(dir+'ask_for_recipe-newP-oldV-test.bio','r') as f:
a2 = f.read()
text_a2 = a... |
# virtualenv
# 图形界面
# Python支持多種圖形界面的第三方庫
# Tk,是一個圖形庫.
# 在gui中,每個Button、label,輸入框等,都是一個widget。frame是可以容納其他widget的widget。
# pack()方法把widget放入父容器中,并實現佈局。pack是最簡單的佈局,grid可以實現複雜的佈局。
# 在createWidgets方法中,我們創建一個label和一個button。quit方法退出。
from tkinter import *
import tkinter.messagebox as messagebox
class Application(Frame):
... |
from info.info import TestData
from pages.BasePage import BasePage
from selenium.webdriver.common.by import By
from time import sleep
class LoginPage(BasePage):
"""Locators"""
EMAIL_FIELD = (By.ID, "login-email")
PASSWORD_FIELD = (By.ID, "login-password")
NEXT_BUTTON = (By.XPATH, '//*[@id="login-form"... |
"""
Microframework for composing iterator pipelines
"""
import string
from StringIO import StringIO
class Pipe(object):
"""
Pipe creator
Initializes pipeline. Other pipeline filters can be attached using pipe.
Pipeline filter is callable object having at least one argument for iterator.
>>> cat ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
# Apply unfold operation to input in order to prepare it to be processed against a sliding kernel whose shape
# is passed as argument.
def unfold_map2d(input, kernel_height, kernel_width):
# Before performing an operation between an i... |
from numpy.random import poisson
from random import randint
from math import ceil,floor
for team in range(4,7):
if team == 4:
initialTime =15
elif team == 5:
initialTime = 10
elif team == 6:
initialTime = 5
workMins = 0
wait = 0
trucks = 0
while workMins < 480 or trucks > 0:
trucks += poisson(2)
ne... |
"""Hooks which override deep learning interfaces with remote execution functionality."""
from .base import BaseHook
from .keras import KerasHook
from .tensorflow import TensorflowHook
from .torch import TorchHook
__all__ = ['BaseHook', 'TorchHook', 'KerasHook', 'TensorflowHook']
|
from WebScraper import WebScraper
import argparse
def run_scraper(extract=None,name=None):
scraper = WebScraper()
if extract=='CDS':
data = scraper.cds_scrape()
if name!=None:
print('CDS:',data[data.Name==name].Name.iloc[-1],'Price:',data[data.Name==name].Price.iloc[-1],'bps')
... |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def ex2():
s = raw_input()
tlist = s.split()
#First Solution - Using Bubble sort
for a in range(len(tlist)-1):
for b in range(1, len(tlist)-a):
if int(tlist[b-1]) > int(tlist[b]):
temp = ... |
"""Management command to create DKIM keys."""
import os
from django.core.management.base import BaseCommand
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _
from modoboa.lib import sysutils
from modoboa.parameters import tools as param_tools
from .... import models
from ... |
"""
===========================
How to use CutMix and MixUp
===========================
.. note::
Try on `collab <https://colab.research.google.com/github/pytorch/vision/blob/gh-pages/main/_generated_ipynb_notebooks/plot_cutmix_mixup.ipynb>`_
or :ref:`go to the end <sphx_glr_download_auto_examples_transforms_... |
def fatal(msg="***No error message provided***"):
print("FATAL ERROR:",msg,"EXITING...", sep="\n")
|
from scipy.io import wavfile
import math
import cmath
import numpy as np
import matplotlib.pyplot as plt
###########
#DFT function
############
def dft(data, N):
out = np.zeros(shape = N, dtype=np.complex_)
for m in range (N):
for n in range(N):
out[m] += data[n] * ( np.cos(2 * cmath.pi * n * m / N) - (np.sin(... |
from __future__ import annotations
import textwrap
from typing import (
Any,
Dict,
Final,
Sequence,
Tuple,
TypeVar,
)
from .output.types import FieldSpec, PaginatedResult
from .exceptions import BackendAPIVersionError
from .session import api_session
MAX_PAGE_SIZE: Final = 100
T = TypeVar('T... |
'''
This lets you specify an experiment to run. You must provide it with:
- an experiment name
- the number of iterations to run for
- the constants file to use
- the statistics to write out
Each one of these may be a list. If you want to use the same statistics
or number of iterations, then they will b... |
from xlutils.copy import copy # 只能修改xls后缀的文件格式,xlxs后缀格式在写入时会被破坏原文件
import os
import xlrd
def base_url(filename=None):
return os.path.join(os.path.dirname(__file__), filename)
work = xlrd.open_workbook(base_url('test1.xls')) # 实例化文件对象
print(work)
old_content = copy(work) # 复制未信息的xls
ws = old_content.get_sheet(... |
from setuptools import setup
setup(
name='Fisheye Webservice',
version='0.1',
long_description="web service for convertion of fisheye videos",
packages=['Webservice'],
include_package_data=True,
zip_safe=False,
install_requires=['Flask', 'peewee', 'Flask-WTF', 'wtforms']
) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 13:16:19 2019
histogramm and timecourse data
@author: fabio
"""
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
#from smaller_model_function_MtoU import simple_small as ss
from MtoU_model import simple as ss
import multipr... |
import unittest
from katas.kyu_7.reverse_it import reverse_it
class ReverseItTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(reverse_it('Hello'), 'olleH')
def test_equals_2(self):
self.assertEqual(reverse_it(314159), 951413)
def test_equals_3(self):
self.ass... |
from django.contrib import admin
from django.core.mail import EmailMessage
from .models import *
# Register your models here.
class OrderAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if 'status' in form.changed_data and obj.status is 1:
obj.status = 1
... |
import theano.tensor as T
import theano
import numpy as np
from braindecode.veganlasagne.objectives import tied_losses
import lasagne
from numpy.random import RandomState
def test_tied_losses():
# Regression Test, expected values never checked for correctness ....
n_classes = 3
n_sample_preds = 2
n_pai... |
import pickle, uuid, base64, hashlib, base64, os
# DEVELOPER: https://github.com/undefinedvalue0103/nullcore-1.0/
database = {}
def save_database(database):
pickle.dump(database, open('database.pickle', 'wb'))
def load_database():
try:
return pickle.load(open('database.pickle', 'rb'))
except:
... |
from __future__ import print_function
from sys import argv
def trim_broadcast( str ):
with open(str) as fp:
f = open (str+'.out', 'w')
key = ""
for line in fp:
if len(line) > 10:
temp = line.split ( )[0]
if not key == temp:
f.write(line)
key = temp
f.close()
return;
total = len(argv)
cm... |
import amath.ext._rounding as r
ROUND_TRUNC = 'ROUND_TRUNC' # Round towards 0
ROUND_CEILING = 'ROUND_CEILING' # Round towards Infinity
ROUND_FLOOR = 'ROUND_FLOOR' # Round towards -Infinity
ROUND_UP = 'ROUND_UP' # Round away from zero
ROUND_HALF_UP = 'ROUND_HALF_UP' # Round to nearest with ties going towards Infin... |
from django.contrib.admin.sites import site
from django.contrib import admin
from leds.models import Led
# Register your models here.
site.register(Led)
|
import asyncio
import aiomysql
magnet_head = 'magnet:?xt=urn:btih:'
async def test_example(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root', password='xuexi520',
db='database_test', loop=loop)
async wi... |
import json
from django.core.management import BaseCommand
from documentos.models import BaseDocument
from gerente.datatxt_helpers import Datatxt
from documentos.models import Node, Frame
class Command(BaseCommand):
help = 'Convert old style goal standard into a new one'
def handle(self, *args, **options):
... |
import logging
import sqlite3
def query_db():
"""
A function that uses a preconstructed query to retrieve data from a SQLite DB iinstance.
Parameters: None
Returns: A list of results
"""
conn = sqlite3.connect('pets.db')
cursor = conn.cursor()
sql_query = """
SELECT
per... |
import pymysql.cursors
import requests
import re
import uuid
from bs4 import BeautifulSoup
from time import sleep
connection = pymysql.connect(host=#'hostname',
user=#'username',
password=#'password',
db=#'dbname',
... |
from flask import Flask,render_template,url_for,redirect,request,json,jsonify
from flask_sqlalchemy import SQLAlchemy
import datetime
from bs4 import BeautifulSoup
import requests
import re
from urllib.request import urlopen
import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+p... |
import pandas as pd
import urllib
import requests
from bs4 import BeautifulSoup
import concurrent.futures
from time import sleep
import re
from multiprocessing import Pool
from Queue import Queue
import sys
from collections import defaultdict
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:42... |
import json
import ssl
import urllib.request
import sqlite3
# Ignore SSL certificate errors
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
connection = sqlite3.connect("db.sqlite3")
cur = connection.cursor()
cur.execute("DROP TABLE IF EXISTS Games")
cur.execu... |
import logging, json, argparse, yaml
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
from helpers import global_config, logs
import config_generator
import exporter
logger = logging.getLogger('openhab_exporter')
def main():
import helpers.cmdline_args # pylint: disable=unused-import
... |
import dash
import dash_table
import pandas as pd
from django_plotly_dash import DjangoDash
from .nutrienti import cibo_mangiato, identifica
import datetime
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from django.contrib.auth.models import User
impo... |
import socket
import sys
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('task.cstag.ca', 4547)
messages = ["HELP", "LOGIN MTECH GITRDONE", "STATUS", "START", "STOP", "LOGOUT"]
print "Connected.... Enter commands now..."
# for message in messages:
while True:
try:
... |
# STAGE CONTROL
# AUTHOR: Jamie Lake
# EMAIL: jdl62@cam.ac.uk
# All units should be in relation to mm
# i.e. x = [mm], d' = [mm/s], d'' = [mm/s^2].
# If you try to run this on another PC, it is
# likely that the stage will not be recognised
# you will need to check which COM channel the OS
# has assigned the US... |
numero = int(input("digite um numero: "))
calculo = numero%2
if calculo == 0:
print("par")
else:
print("ímpar")
|
from flask import render_template, request
from flask_login import login_required, current_user
from flask.helpers import flash
from sqlalchemy.orm import query
from models.Modelos import *
from flask_sqlalchemy import SQLAlchemy
from functools import reduce
import os.path, sys, shutil
db = SQLAlchemy() # nuestro ORM
... |
# Generated by Django 3.2.4 on 2021-06-29 14:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoFie... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import re
from pants.testutil.pants_integration_test import run_pants, setup_tmpdir
def test_counters_and_histograms() -> None:
# To get the cach... |
class Solution(object):
def titleToNumber(self, s):
total = 0
for i in range(len(s)):
multiple = len(s) - 1 - i
val = ord(s[i]) - ord('A') + 1
total += val * 26**(multiple)
return total
print(Solution().titleToNumber('A'))#1
print(Solution().titleToNumbe... |
import re
from helper import *
from collections import defaultdict
IFACE = "eth1"
ZERO = "0.00"
# Class for parsing ethstats output
#
# Gives the mean and stdev of network utilization
class EthstatsParser:
def __init__(self, filename, iface=IFACE):
self.f = filename
self.iface = iface
s... |
d = {"a": 1, "b": 2, "c": 3}
try:
print(d["d"]) # 기본적으로 실행하는 구문
except KeyError:
print("KeyError!") # KeyError가 발생했을 때 실행하는 구문 |
import re
class Assembler:
@staticmethod
def assemble(program, start_address):
program = program.split("\n")
labels = {}
curr_address = start_address
supported_instructions = [ "LW", "SW", "JMP", "BEQ", "JALR", "RET", "ADD", "SUB", "ADDI", "NAND", "MUL", "HALT" ]
new... |
from tkinter import *
before = [100, 100]
def line(x1, y1, x2, y2):
global canvas
canvas.create_line(x1, y1, x2, y2)
def on_click(event):
global canvas
global before
x = event.x
y = event.y
line(before[0], before[1], x, y)
before[0] = x
before[1] = y
tk = Tk()
canvas = Canvas(tk,... |
from flask_restful import request, reqparse
from Camel import CamelResource
from Camel.auth import is_authenticated
from Camel import config
from os import path
from pathlib import Path
from uuid import uuid4
class Attachment(CamelResource):
def __init__(self):
upload_conf = config['uploads']
self... |
class LinkedQ():
def __init__(self):
self.first = None
self.last = None
self.size = 0
def __str__(self):
"""Returnerar köns element som en sträng.
Tips: Titta på kursens FAQ (under Hjälp)"""
return "LinkedQ Class"
def put(self,x):
"""Stoppar in x sis... |
"""An example to check if BackPACK' first-order extensions are working for ResNets."""
from test.core.derivatives.utils import classification_targets
import torch
from backpack import backpack, extend, extensions
from .automated_test import check_sizes, check_values
def autograd_individual_gradients(X, y, model, ... |
import pickle
import argparse
from genotype import *
from animat import *
from single_tmaze import *
from evolutionary_search import *
if __name__ == '__main__':
parser = argparse.ArgumentParser("experiment.py")
parser.add_argument("-s", "--src", help = "src pickle for population")
parser.add_arg... |
# -*- coding: utf-8 -*-
'''
Se conecta al router wamp y hace correr el Wamp de Users
'''
if __name__ == '__main__':
import sys
import logging
import inject
inject.configure()
sys.path.insert(0, '../python')
logging.basicConfig(level=logging.DEBUG)
from autobahn.asyncio.wamp import Ap... |
# -*- coding: utf-8 -*-
import os
from django.conf import settings
class CorretorException(Exception):
def _limitar_texto_msg(self, msg, questao=None):
"""
Dado o texto de msg de erro e uma questao(de avaliacao),
remove o começo das paths para impedir que os usuarios possam se usar disso... |
"""
Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.
An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.
Example 1:
Input: nums = [23... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" NeTV2 Platform Definition
This is a non-core platform. To use it, you'll need to set your LUNA_PLATFORM variable:
> export LUNA_PLATFORM="luna.gateware.platform.netv2:... |
__author__ = "Narwhale"
import json
try:
with open('num.txt', 'r') as f_obj:
num = json.load(f_obj)
except FileNotFoundError:
num = input('请输入您喜欢的数字:')
with open('num.txt', 'w') as f_obj:
json.dump(num, f_obj)
print('I konw your favorite new number!It\'s %s'%num)
else:
print('I ... |
# First project of the Joyita
puwis_dogs = ['Joyita','Maya','Pelusa','Tofy','Popi', 'intruso','intrusa']
print ('Lindas Dogs are:')
for x in puwis_dogs:
if x=="intrusa":
print("You are not her dog")
else: print(x)
print("Intruso you got caught")
print("muajajaja")
|
from django.urls import path
from .views import *
urlpatterns = [
path('', blogPosts.as_view(), name = 'blog_posts_url'),
path('post/create/', CreatePost.as_view(), name = 'blog_create_post_url'),
path('post/<slug:slug>/', blogPost.as_view(), name = 'blog_post_url'),
path('post/<slug:slug>/edit/', Edit... |
import numpy as np
from cntk.layers import Convolution, MaxPooling, Dropout, Dense
from cntk.initializer import glorot_uniform
from cntk.ops import input_variable, relu, softmax
from common.functor import Functor
class MnistModel(Functor):
def __init__(self):
super(MnistModel, self).__init__()
#... |
#!/usr/bin/python
import sys
import ssl
import boto
import time
import operator
from collections import defaultdict
def convert_to_gb(size):
return float(size)/(1024*1024*1024)
def convert_to_mb(size):
return float(size)/(1024*1024)
def main():
start_time = time.time()
if hasattr(ssl, '_create_unve... |
#from rest_framework import serializers
from api.models import Challenge
from rest_framework_json_api import serializers
from rest_framework_json_api.relations import ResourceRelatedField
class ChallengeSerializer(serializers.ModelSerializer):
"""
Sets fields for the rest api to serialize in the Challenge m... |
from pathlib import Path
import numpy as np
import pandas as pd
from keras_preprocessing.image import img_to_array, load_img
from tensorflow.python.keras.utils.data_utils import Sequence
def idx_to_name(id_: int):
return f"{id_:06d}.jpg"
def name_to_idx(name: str):
return int(name[:-4])
def find_range_of... |
# 1st level Model Structure: Equation Block
# import sys
# sys.path.append('..')
# this module define the rules for constructing a energy block in the master block
# this is the global component set import, so that all modules uses the same set
from global_sets.component import m
from pyomo import environ as pe
# def... |
import bleach
import markdown as md
from bleach.linkifier import LinkifyFilter
from django import template
allowed_tags = [
"a",
"abbr",
"acronym",
"b",
"blockquote",
"br",
"code",
"em",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"li",
"ol",
... |
import cv2
import numpy as np
from abc import ABC, abstractmethod
class VideoReader(ABC):
def __init__(self) -> None:
self.path = None
@abstractmethod
def _read_file(self):
raise NotImplementedError('Read File Method is not implemented')
@abstractmethod
def _read_frames(self):
... |
line_stuff = list(map(lambda x: int(x), input().split()))
average = sum(line_stuff) / len(line_stuff)
more_than_average = []
for i in line_stuff:
if i > average:
more_than_average.append(i)
more_than_average.sort()
more_than_average.reverse()
for j in range(5):
if not more_than_average:
print("N... |
#!/usr/bin/env python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.autograd import Variable
from tensorboardX import SummaryWriter
import argparse, os, sys, subprocess
import setproctitle, colorama
import numpy as np
from tqdm import tqdm
from glob import glob
from os.path imp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.core.mail import send_mass_mail
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from .models import Album, AlbumImageRelation, Image
from .utils import (
search_tweets_by_ha... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('../../../python')
import inject, logging
import psycopg2
from model.config import Config
''' configuro el injector con las variables apropiadas '''
def config_injector(binder):
binder.bind(Config,Config('firmware-config.cfg'))
inject.configure(config_injector... |
# -*- coding: utf-8 -*-
val = float(input())
total = val
ced = 100
totced = 0
tipo = 'nota'
print('NOTAS:')
while True:
if(total >= ced):
total -= ced
totced += 1
else:
print(f'{totced} {tipo}(s) de R$ {ced:.2f}')
if(ced == 100):
ced = 50
elif(ced == 50):
... |
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rangeSumBST(self, root, L, R):
if root is None:
return 0
result = 0
if L <= root.val <= R:
result += ro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.