text stringlengths 8 6.05M |
|---|
from PIL import Image
from tqdm import tqdm
import os
def CropImageSeries(image):
IMAGERESOLUTIONS = image.height #Assumes square images
totalImages = image.width // IMAGERESOLUTIONS
indImages = []
for i in range(totalImages):
tmpImage = image.copy()
cropped_img = tmpImage.cro... |
from .base import StochasticProcess, StochasticProcessOverError
from collections import namedtuple
import numpy as np
SIRParameters = namedtuple('SIRParameters',
'population_size infection_rate recovery_rate T delta_t')
class SIR(StochasticProcess):
"""
The Susceptible-Infected-Reco... |
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
#在出现 nums[i] < nums[i - 1] 时,需要考虑的是应该修改数组的哪个数,使得本次修改能使 i 之前的数组成为非递减数组,
#并且 不影响后续的操作 。优先考虑令 nums[i - 1] = nums[i],因为如果修改 nums[i] = nums[i - 1] 的话,那么 nums[i] 这个数会变大,就有可能比 nums[i + 1] 大,从而影响了后续操作。
#还有一个比较特别的情况就是 nums[i] < nums... |
import torch
import torch.nn as nn
import torch.nn.functional as f
import numpy as np
import gym
from flare.kindling.neuralnets import MLP, GaussianPolicy, CategoricalPolicy, Actor
from flare.kindling.utils import _discount_cumsum
from flare.kindling import PGBuffer
from flare.polgrad import BasePolicyGradient
# pylint... |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if not s:
return True
n = len(s)
DP = [False] * (n+1)
DP[0] = True
for i in range(1, n+1):
for word in wordDict:
if DP[i-1] and i-1+len(word) <= n and s[i-1 : i-1... |
import os
import warnings
def test_rubicon_with_misc_folders_at_project_level(rubicon_local_filesystem_client_with_project):
rubicon, project = rubicon_local_filesystem_client_with_project
os.makedirs(os.path.join(rubicon.config.root_dir, ".ipynb_checkpoints"))
with warnings.catch_warnings(record=True) ... |
import json
import logging
import os
from typing import Tuple
import backoff
import requests
from bitcoin_acks.logging import log
logging.basicConfig(level=logging.ERROR)
logging.getLogger('backoff').setLevel(logging.INFO)
def fatal_code(e):
# We only retry if the error was "Bad Gateway"
log.error('GitHub ... |
s = input()
sub_s = input()
k = 0
for i in range(len(s) - (len(sub_s)-1)):
if s[i: i + len(sub_s)] == sub_s:
k += 1
print(k) |
# Copyright 2020 Pulser Development Team
#
# 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 i... |
__author__ = 'AlecGriffin'
class Book:
def __init__(self, bookTitle):
self.bookTitle = bookTitle
# Container for Chapter Objects
self.chapterList = []
self.numChapters = 0
def addChapter(self, chapter):
self.numChapters += 1
self.chapterList.append(chapter)
... |
CG Lab Sample Questions
CS 1507 Computer Graphics Lab
Sample Questions for Lab Examination
* Use Bresenham’s algorithm to draw circle & line for the following questions.
* Use non-recursive fill algorithms to fill colours
Write a program to draw sierpensky triangle (recursive and non recursive)
Write a program to ... |
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import transforms
from models import *
import numpy as np
import os
import time
model = semantic_ResNet18().cuda()
ckpt = torch.load('./Res18_model/net_150.pth... |
# Generated by Django 3.0.3 on 2021-05-27 10:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ticketingsystem', '0008_auto_20210527_1120'),
]
operations = [
migrations.AlterField(
model_name='inventoryitem',
na... |
####################################################################################################
# constants_and_vowels.py #
# ------------------------------------------------------------------------------------------------ #
# Takes the user'... |
def feuer_frei(concentration, barrels):
fuel_hours = barrels * concentration
if fuel_hours < 100:
return '{} Stunden mehr Benzin ben\xf6tigt.'.format(100 - fuel_hours)
elif fuel_hours == 100:
return 'Perfekt!'
return fuel_hours - 100
|
from flask import Flask,request
from celery import Celery
import json
import redis
from celery.result import AsyncResult
import task
app=Flask(__name__)
redis_host = "localhost"
redis_port = 6379
redis_password = ""
r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)... |
import tensorflow as tf
class PointNet(object):
def __init__(self, batch, keep_rate, is_training):
"""
Args:
batch: B*P*C (BATCH_SIZE * NUM_POINTS * NUM_INPUT_COORDS)
"""
# batch_size = batch.get_shape()[0].value
num_points = batch.get_shape()[1].value
n... |
import unittest
from tempfile import mkdtemp
import shutil
import hylite
from hylite import HyScene, HyCloud, HyImage
from hylite.project import Camera, Pushbroom
import numpy as np
class MyTestCase(unittest.TestCase):
def build_dummy_data(self):
# build an example cloud
x, y = np.meshgrid(np.li... |
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'nest_el',
'type': 'static_library',
'sources': [ '../file_g.c', ],
'postbuilds': [
{
... |
# Generated by Django 2.1.3 on 2018-11-06 10:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181106_2343'),
]
operations = [
migrations.AddField(
model_name='staff',
name='nfc_dev_id',
... |
import os
from setuptools import find_packages, setup
import dc_signup_form
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
def get_version():
return dc_signup_form.__version__
setup(
name="dc_signup_form",
version=get_version(),... |
# Generated by Django 2.1.4 on 2018-12-13 01:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('UserProfile', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='profile',
table='UserProfiles',
),... |
module("gxx.std",
include_paths = ["."]
) |
from google.appengine.api import users
from google.appengine.ext import db
from app.model.account import Account, AccountEmail
_REQUIRE_INVITE = True
# DB Model - Account
# ------------------
class Accounts():
@staticmethod
def loadAll():
# Check cache first, if not load from DB
accounts ... |
df_train = pd.read_csv('../input/labeledTrainData.tsv', delimiter="\t")
xxx
xxx
|
# The location of the script
path = "/home/pi/Tiny-Stereo/"
# GPIO setup (BCM) on the Raspberry Pi. Set "warnings" to True if you wish to render GPIO warnings.
pins = {
"warnings": False,
"led": 14,
"buttons": {
"power": 3,
"next": 17,
"volume_up": 22,
"volume_down": 27
... |
# Copyright 2021 DAI Foundation
#
# 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,... |
import numpy as np
import matplotlib.pyplot as plt
r = 0.5
n = 10
K = 0.3
a = 1.2
def f(x, y):
return x + y
def RK4(xs, xd, ys, h):
n = (int)((xd - xs)/h)
x = np.zeros(n + 1)
y = np.zeros(n + 1)
x[0] = xs
y[0] = ys
for i in range(1, n + 1):
k1 = h * f(x[i-1], y[i... |
##encoding=utf-8
"""
Imoprt Command
--------------
from archives.spider import spider
"""
import requests
class ArchivesSpider():
def __init__(self, timeout=30, sleeptime=0):
self.session = requests.Session()
self.default_timeout = timeout
self.default_sleeptime = sleeptime
se... |
# Created by Luis A. Sanchez-Perez (alejand@umich.edu).
# Copyright © Do not distribute or use without authorization from author
import os
import re
import random
import numpy as np
import tensorflow as tf
# Dictionary containing features description for parsing purposes
feature_description = {
'spec': tf.io.Fixe... |
import os
import numpy as np
from . import __file__ as filepath
__all__ = ["Inoue14"]
class Inoue14(object):
def __init__(self, scale_tau=1.):
"""
IGM absorption from Inoue et al. (2014)
"""
self._load_data()
self.scale_tau = scale_tau
def _load_data(self):
... |
from django.urls import path, re_path, include
from rest_framework.routers import DefaultRouter
from jiaju.cases.views import CategoryView, CaseView, CaseDetailedView, FeaturedCaseView
router = DefaultRouter()
router.register(r'category', CategoryView)
router.register(r'(?P<category>[0-9]+)', CaseView)
router.registe... |
import matplotlib.pyplot as plt
import numpy as np
labels=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
data=np.random.rand(7)*100
plt.pie(data,labels=labels,autopct='%1.1f%%')
plt.axis('equal')
plt.legend()
plt.show() |
from mod_base import*
class NewPass(Command):
"""Change your password.
Usage: newpass oldpassword newpassword newpassword
"""
def run(self, win, user, data, caller=None):
args = Args(data)
if len(args) < 3:
win.Send("Usage: newpass oldpassword newpassword newpassword")
... |
print(sum1(2,3))
print(sum2(10,11,20))
p()
aa() |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import xavier_init
from mmdet.core import auto_fp16
from ..builder import NECKS
@NECKS.register_module
class LiteFpn(nn.Module):
def __init__(self,
in_channels,
out_channels,
):
super(... |
import numpy as np
def alpha_from_c_beta(c, beta):
sb = np.sqrt(beta)
return c/(1.0 + sb) + (1.0 + 2.0*sb)/6.0
def c_from_beta_k(beta, k):
return (1.0 - beta - 9.0*k/4.0)/30.0
def k_from_xi(xi):
if xi is None:
return 0.0
else:
return 2.0/xi - 2.0
def alpha_from_beta_xi(beta, x... |
import requests
import base64
import json
import urllib.request as urllib
localUrl = 'http://localhost:7071/api/'
cloudUrl = 'https://ft45mlfuncapp.azurewebsites.net/api/'
code = "DYAwYUdU2CuRHfKYQ3zUwWoChIIDbhSIterIPZxvO9EHFcQKtir4JQ=="
image_url = 'https://uniqlo.scene7.com/is/image/UNIQLO/goods_67_400711?$p... |
"""
Created by Alex Wang
On 2018-08-26
"""
import struct
import base64
import math
import traceback
import numpy as np
TAG_NUM = 1746
AUDIO_FEAT_LEN = 400
AUDIO_FEAT_DIM = 128
FRAME_FEAT_LEN = 200
FRAME_FEAT_DIM = 1024
def tags_process(tags_org):
"""
:param tags_org:
| 782028346 | 1076,1676,1373,0,0,0... |
import mqtt
import json
import random
class GameSession:
def __init__(self, callback = None, context = None):
mqtt.connect(GameSession.onMsg, self)
self.id = random.randint(1, 1000000000)
# self.id = random.randint(1, 10)
print("I am:", self.id)
self.wants = False
se... |
# This code helps to find out feature multipliers for KNN.
# This is shown using some features derived by me but this method can be extended for other features as well.
# One needs to derive his own features and then apply similar approach to get the correct weights.
import numpy as np # linear algebra
import pandas... |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse , resolve
from ..forms import NewWorkerForm
from ..models import Work, Worker, Assignment
from ..views import new_worker
# test_view_new_worker
#from datetime import datetime
class NewWorkerTests(TestCase)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
delete_nvl_linestring_element_query = """
UPDATE public.nvl_linestring AS nls SET deleted = TRUE,
active = FALSE WHERE ($1::BIGINT is NULL OR nls.user_id = $1::BIGINT) AND nls.id = $2::BIGINT RETURNING *;
"""
delete_nvl_linestring_element_by_... |
# Copyright 2018 Intel Corporation
#
# 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 wri... |
import chainer
import cv2
import numpy as np
from chainer import serializers, Variable
from colorize import unet
from colorize.img2imgDataset import ImageAndRefDataset
class Painter:
def __init__(self, gpu=-1):
self.line_image_dir = 'images/line/'
self.ref_image_dir = 'images/ref/'
self.c... |
import sys
import re
import shlex
import subprocess as sp
exe_pat = re.compile(r'(\s*)\(!>(.*)<\)\s*')
inc_pat = re.compile(r'(\s*)\(>(.*)<\)\s*')
if __name__ == "__main__":
for line in sys.stdin:
match_exe = re.match(exe_pat, line)
match_inc = re.match(inc_pat, line)
if match_exe:
space = match_e... |
from django.views.generic.base import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
class IndexView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/home.html'
|
test_case = int(input())
for _ in range(test_case):
sentence = input()
if sentence.endswith('po'):
print('FILIPINO')
elif sentence.endswith('masu') or sentence.endswith('desu'):
print('JAPANESE')
else:
print('KOREAN') |
from util import *
from get_word_embeddings import *
import random
import tensorflow as tf
import numpy as np
import sys
import pandas as pd
import pandas as pd
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics... |
import requests
import json
import sys
import time
import datetime
try:
from utils import get_console_size
except:
# not needed in a testing environment
pass
from Transactions import *
class BitcoinTransaction:
def __init__(self):
self.ts = time.time()
self.symbol = "BITCOIN"
... |
import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage as nd
#from skimage import color
import math
#read the files
#path = '.\positives\ '
p_path = 'path\\positives\\'
n_path = 'path\\negatives\\'
def read_files(dir, extension):
files = [f for f in glob.glob(dir + "**/... |
import matplotlib.pyplot as plt
import numpy as np
import uncertainties.unumpy as unp
from scipy.optimize import curve_fit
from scipy import stats
import scipy.constants as con
from uncertainties import ufloat
# t, p_a, p_b, t_1, t_2, n = np.genfromtxt('plots/test.txt', unpack=True)
t, t_1, p_a, t_2, p_b, N = np.genfr... |
n=int(input("enter any number:"))
factorial=1
if n<0:
print("number can not be negative")
elif n==0:
print("the factorial of 0 is 1")
else:
for i in range(1,n+1):
factorial*=i
print("the factorial of" , n ,"is" ,factorial, "." )
|
from datetime import *
class BaseModel:
# fields
__date = None
__open = 0
__high = 0
__low = 0
__close = 0
__diff = 0
__diff_per = 0
def __init__(self, raw):
parts = raw.split('\t')
if len(parts) < 7:
print(raw, " error format base")
return
... |
import cv2
import numpy as np
class ReferenceLine:
def __init__(self, triangles):
points = np.reshape(map(lambda t: t.centroid, triangles), (-1, 2))
points = np.hstack([points, np.ones((points.shape[0], 1))])
_, _, vt = np.linalg.svd(points)
self.vector_form = vt[-1:, :].reshape(3,... |
def hello(msg):
return "Hiya"
|
import array
import socket
import sys
def checksum(data):
if len(data) % 2:
data += b'\x00'
check_sum = 0
for i in range(0, len(data))[::2]:
check_sum += int.from_bytes(data[i:i + 2], byteorder=sys.byteorder, signed=False)
while (check_sum >> 16) > 0:
check_sum = (check_sum & 0... |
#! /usr/bin/env python
# Copyright (c) 2018 - 2019 Jolle Jolles <j.w.jolles@gmail.com>
#
# 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
#
# Unle... |
'''
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 <= k <= number of unique elements.
Your algorithm's time complexity must be better than ... |
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
def get_title(url):
"""
Getting the title of a webpage
:param url:
:return:
"""
try:
html = urlopen(url)
print(html.read())
except HTTPError as e:
return No... |
from abc import ABC, abstractmethod
class Command(ABC):
"""抽象命令基类
Usage(demo):
main = SomeCommand()
main.config = config
main.run()
Design:
构造 PITL,配置 property,控制
Attributes:
config: [description]
"""
def set_config(self, config):
self.__dict... |
import numpy as np
import cv2
import time
import boto3
import os
#import the cascade for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
max = 3
filenum = max
i = 1
x = 1
def TakeSnapshotAndSave():
# access the webcam (every webcam has a number, the default is 0)
c... |
import requests
token = 'aKcaFuAVEJre7L9UkxAG'
# Consultar projetos
# projetos = requests.get(f'http://localhost:81/api/v4/projects?private_token={token}')
# print(projetos.json())
# projeto = {
# 'name': 'batata-frita'
# }
# Adicionar projetos
# projetos = requests.post(f'http://localhost:81/api/v4/projects?pr... |
LOGIN_REQUIRED = 'Login required.'
USER_CREATED = 'User created successfully.'
LOGOUT = 'Log out successfully.'
ERROR_USER_PASSWORD = 'Incorrect user or password.'
LOGIN = 'Successfully authenticated user.'
TASK_CREATED = 'Article created successfully.'
TASK_UPDATE = 'Article Updated Successfully.'
TASK_DELETE =... |
import turtle
ans = True
turtle.write("""
1. INSTRUCTIONS
2. PLAY!!
PRESS ENTER TO QUIT
""",True, align="center", ("Times", 24, "bold italic"))
while ans:
print("""
1. INSTRUCTIONS
2. PLAY!!
PRESS ENTER TO QUIT
""")
turtle.mainloop()
|
import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.sparse
import scipy.signal
from tqdm import tqdm
from numba import stencil, jit, prange
class Namespace(dict):
def __mul__(self, other):
if isinstance(other, Namespace):
return Namespace({key: other[key] * val for key,... |
import sys
import numpy as np
import h5py
import json
from scipy.stats import gamma,lognorm,norm
from numpy.random import negative_binomial as nb
import matplotlib.pyplot as plt
from dateutil import parser
import datetime
from prime_utils import prediction_filename
# sys.path.append('../../scripts')
from prime_model... |
#!/usr/bin/python3
import os.path
def reduce():
if not os.path.isfile("german.dic"):
print("Please download the german dictionary \"german.dic\" from")
print("https://sourceforge.net/projects/germandict/" +
"files/german.7z/download")
print("and place it inside this director... |
import concurrent.futures
import config
import time
import pandas as pd
import requests
import numpy as np
from ast import literal_eval
import os
def worker_process(d):
data = requests.get("https://api.spotify.com/v1/artists",
{"ids":",".join(d.tolist())},
headers=config.spotify_... |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import resolve, reverse
from ..models import Work, Assignment, Worker
from ..views import worker_assignments
class WorkerAssignmentsTests(TestCase):
def setUp(self):
work = Work.objects.create(name='Tailor', desc... |
from django.http.response import HttpResponse
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def test(request):
return HttpResponse('OK')
# HTML 문자열로 작성
# JSON로 작성
# Template로 작성
def main(request):
# return HttpResponse('<b><i>안녕하세요</i></b>')
... |
# Generated by Django 2.2.3 on 2019-08-01 07:42
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Questions... |
a = []
s = 1
a.append(1)
for i in range(1,21):
s *= i
a.append(s)
try:
while True:
n, m = map(int, input().split(' '))
print(a[n]+a[m])
except EOFError:
pass |
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
import socket
import unittest
try:
from http_parser.parser import HttpParser
except ImportError:
from http_parser.pyparser import HttpParser
from ammo.phantom import HttpCompiler
TEST_SERV_ADDR = ('httpbin.org', 80)
class HTTPCompilerCase(unittest.... |
import discord
from discord.ext import commands
import requests
import json
import shlex
API_URL = "https://api.coinmarketcap.com/v1/ticker/grimcoin/?convert=JPY"
client = discord.Client()
def current_price():
headers = {"content-type": "application/json"}
data = requests.get(API_URL, headers=headers).json()
... |
todaysCustomer = {"name":"Mark", "email":"mark@zuckerberg.com", "city":"San Francisco", "telephone": 92321321321}
print(todaysCustomer['telephone'])
rankings = {5: "Finland", 2: "Norway", 3: "Sweden", 7: "Iceland"}
print(rankings[3])
things_to_remember = {
0: "the lowest number",
"a dozen": 12,
"snake eyes"... |
from rest_framework import serializers
from rest_auth.serializers import UserDetailsSerializer
from django.conf import settings
from accounts.models import CustomUser as User
from rest_auth.registration.serializers import RegisterSerializer
from allauth.account import app_settings as allauth_settings
from allauth.utils... |
# Copyright 2017 Google Inc.
#
# 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 writin... |
# Recursive function to calculate the factorial of a number
def factorial(n):
if(n<0):
return -1
if(n==0):
return 1
return n*factorial(n-1)
result1=factorial(0)
result2=factorial(5)
result3=factorial(12)
result4=factorial(-2)
print ("Results = ",result1,result2,result3) |
import sys
import os
from os.path import isfile, join
import csv
import pandas as pd
import numpy as np
from collections import defaultdict
class MinMaxDenormalise:
def __init__(self):
self.local_values = defaultdict()
self.global_values = defaultdict()
def get_local_norms(self, csvs):
try:
local_nor... |
from direct.distributed.DistributedObjectGlobalUD import DistributedObjectGlobalUD
from direct.directnotify import DirectNotifyGlobal
import SettingsMgrBase
class SettingsMgrUD(DistributedObjectGlobalUD):
notify = DirectNotifyGlobal.directNotify.newCategory('SettingsMgrUD')
def __init__(self, air):
Di... |
import time, pytest
import sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))
from clsCommon import Common
import clsTestService
from localSettings import *
import localSettings
from utilityTestFunc import *
import enums
class Test:
#=============================... |
import tensorflow as tf
from tf2_models.attention import layers
from tf2_models.attention.transformer import point_wise_feed_forward
from tf2_models.attention.transformer import positional_encoding
class DecoderLayer(tf.keras.layers.Layer):
"""Decoder layer as described in the paper.
"""
def __init__(sel... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ing.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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, QtGui, Q... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# disk_space_run_dusk.py: run dusk in each directory to get disk size #
# ... |
#!/usr/bin/env python
import pathlib
from tilda import VERSION
from setuptools import find_packages, setup
PROJECT_ROOT = pathlib.Path(__file__).parent
README = (PROJECT_ROOT / 'README.md').read_text()
ldap = ['freenit[ldap]']
mongo = ['freenit[mongoengine]']
sql = ['freenit[sql]']
dev = ['freenit[dev]']
setup(
... |
import os
import collections
from six.moves import cPickle
import numpy as np
from json import loads
import logging
from string import printable
class TextLoader():
def __init__(self, data_dir, batch_size, seq_length):
self.data_dir = data_dir
self.batch_size = batch_size
self.seq_length = s... |
num1, num2, num3 = input().split()
plus = int(num1) + int(num2) + int(num3)
print(plus, format(plus / 3, "0.2f"))
|
# -*- coding: utf-8 -*-
print(''.join(['パタトクカシーー'[i] for i in range(len('パタトクカシーー')) if(i%2==0)]))
|
from app import app, db
from flask import render_template, request, flash, get_flashed_messages, redirect, url_for
from datetime import datetime
from app.forms import AddTaskForm, DeleteTaskForm
from app.models import Task
@app.route("/", methods=["GET", "POST"])
def home():
form = AddTaskForm()
tasks = None
... |
import abc
import os.path as osp
from smqtk.representation import SmqtkRepresentation, DescriptorElement
from smqtk.utils import plugin
class DescriptorIndex (SmqtkRepresentation, plugin.Pluggable):
"""
Index of descriptors, keyed and query-able by descriptor UUID.
Note that these indexes do not use the... |
from flask import Flask, url_for, render_template
# import smhutson.github.io
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run()
|
import requests
url = "699991.txt"
while url[:2] != 'We':
r = requests.get("https://stepic.org/media/attachments/course67/3.6.3/" + url)
url = r.text
with open('out.txt', 'w') as file_writer:
file_writer.write(url) |
import random
import math
import time
def insertion_sort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i+1] = A[i]
i -= 1
A[i+1] = key
a = []
for i in range(1, 101):
a.append(int(random.random()*10001))
begin = time.time()
insertion_sort(a)
end = time... |
# Read TextGrid in Python
# 2017-04-02 jkang
# Python3.5
#
# **Prerequisite**
# - Install 'textgrid' package
# from https://github.com/kylebgorman/textgrid
import textgrid
import numpy as np
T = textgrid.TextGrid()
T.read('stops.TextGrid')
w_tier = T.getFirst('phone').intervals # 'phone' tier
words_raw = []
for iv... |
# Isikukoodi valideerimise jaoks tehtud skript. skript võtab kasutajalt isikukoodi,
# ja väljastab kasutajale andmed selle kohta. (sünnikuupäev, sugu) jne.
# Kõigepealt importime mooduli datetime, sellest funktsiooni date
from datetime import date
# ID-kaardi kordajad
kordajad1 = [1, 2, 3, 4, 5, 6, 7, 8, 9,1]
... |
"""Views"""
#from django.shortcuts import render ppylint: disable=unused-import
from django.views import generic
class IndexView(generic.ListView): #pylint: disable=too-many-ancestors
"""Index view"""
template_name = 'andrew/index.html'
queryset = None
class DetailView(generic.DetailView): #pylint: dis... |
# I declare that my work contains no examples of misconduct, such as plagiarism, or collusion.
# Any code taken from other sources is referenced within my code solution.
# Student ID: 2019757
# Date: 02/04/2020
# Part 1 - Student Version
def pro_intro(): ... |
from .arcface import ArcFaceLoss
from .bce import BCEWithLogitsLossAndIgnoreIndex
from .combo_loss import SegmentationWithClassificationHeadLoss
from .dice_loss import DiceLoss
from .focal_loss import (
BinaryDualFocalLoss,
BinaryFocalLoss,
BinaryReducedFocalLoss,
FocalLoss,
LabelSmoothBinaryFocalLo... |
import tkinter as tk
from FuncaoBeckEnd import *
from ProgramaPrincipal import *
passagem = False
# Aqui, ao receber os dados do cliente,
# e conseguir fazer um menu principal
# dinâmico que depende do cliente logado
dadosCliente = []
def mainMenu():
# Criando o menu inicial
menuInicial = tk.Tk()
menuInic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.