text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
max = 0
ans = 0
for D in range(2, 1001):
n = int(D ** 0.5)
if n ** 2 == D:
continue
d = 1
m = 0
a = n
num = a
den = 1
n1 = 1
d1 = 0
while num ** 2 - D * den ** 2 != 1:
m = d * a - m
d = (D - m ** 2) // d
a = (n + m) // d
... |
#raised if parsing fails because of page scheme is changed
class PageSchemeException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
#raised if argument of the parser function is not valid
class ArgumentError(Exception):
def __init__(self, v... |
from api_handler import api_handler
import hashlib
from logger import logger
class Dataset:
def __init__(self, filepath):
self.filepath = filepath
self.sensors = []
self.checksum = None
self.file_length=None #This will be calculated by the calculate_checksum method, for performance ... |
from github import Github
from jenkins import Jenkins
git_access_token = ""
jenkins_server_url = "
jenkins_username = ""
jenkins_password = ""
git_repo_name = "docker-test_test"
docker_repo_name = git_repo_name.replace("_", "-").replace("docker-", "")
jenkins_job_name = "docker-build-{0}".format(git_repo_name.replac... |
#!/usr/bin/env python
#coding=utf-8
__author__ = "yidong.lu"
__email__ = "yidongsky@gmail.com"
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework.routers import DefaultRouter
from nginx_collector.views import (
NginxViewSet,
StatusAPIView,
)
nginx_list = NginxView... |
# coding: utf-8
# Standard Python libraries
from typing import Optional, Union
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM
# https://github.com/usnistgov/atomman
import atomman.unitconvert as uc
# Local imports
from . import CalculationSubset
from ..input import value
... |
from settings import ENABLE_SEARCH, SITE_URL, THEME_NAME, STATIC_URL, ANALYTICS_CODE
from models import Category
def categories(request):
cat = Category.objects.all()
return { 'categories':cat }
def current_site_url(request):
return { 'current_site_url' : SITE_URL }
def current_theme(request):
curre... |
from unittest import mock
import arrow
import pytest
import wrapt
from blazeutils.containers import LazyDict
import keg_storage
from keg_storage.backends.base import FileMode, ListEntry
from keg_storage.backends.sftp import SFTPRemoteFile
def sftp_mocked(**kwargs):
@wrapt.decorator(adapter=lambda self: None)
... |
import csv
data_list = [
{"id":10001, "wname":"python","year":"2001"},
{"id":10002, 'wname':'UI','year':'2002'},
{"id":10004, 'wname':'AI','year':'2003'}
]
try:
with open("ws.csv","w",newline="") as file:
heading = ['id','wname','year',]
obj = csv.DictWriter(file,fieldnames = heading)
... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from p... |
ssh = "tcp port 22" |
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
return render_to_response('index.html', RequestContext(request))
def contact(request):
return render_to_response('contact.html', RequestContext(request)) |
#多层全连接神经网络
import torch
from torch import nn,optim
from torch.autograd import Variable
import net
#超参数
learn_rate=1e-2
epoch_size=700
# 获得训练数据 - train.csv
import csv
with open('./data/train.csv') as f :
lines = csv.reader(f)
label, attr = [], []
for line in lines :
if lines.line_num == 1 :
... |
from tools import ReadConfig,ReadJson
from common import FormatConversion
class DisposeApi:
def __init__(self,casename = None):
self.readconfighandle = ReadConfig.ReadConfig()
self.version = self.readconfighandle.get_data('INTERFACE','version_num')
self.formatconversionhandle = FormatConver... |
from utils import get_formatted_time
import time
import logging
import numpy as np
import json
import uuid
import h5py
import logging.handlers
import os
from config import RecorderConfig
try:
import cv2
except:
print("OpenCV not installed! You should not use the monitor!")
class Recorder(object):
defaul... |
import sys
import unittest
import mock
from mock import patch, MagicMock
import main
class TestMainBoilerplate(unittest.TestCase):
def test_init_boilerplate(self):
with mock.patch.object(main, "main", return_value=42):
with mock.patch.object(main, "__name__", "__main__"):
wit... |
'''
!/usr/bin/env python
@author:nistha_jaiswal,archita_ganguly,ayanava_dutta,rohan_sasmal
-*-coding:utf-8-*-
'''
import streamlit as st
import numpy as np
import pandas as pd
import json
import datetime
import os
from sshtunnel import SSHTunnelForwarder
from rpscript.rpanalysis.rp_analysis_functions import putty_conn,... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import operator
import math
from sklearn.preprocessing import LabelEncoder, Imputer, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.neural_network import MLPClassifier
from sklearn.n... |
#!/usr/bin/env python3
# made for the sake of clarity - to understand these techniques, not performance
# you can learn more at https://nmap.org/book/man-port-scanning-techniques.html
from scapy.all import *
import argparse
import os
import sys
from datetime import datetime
conf.verb = 0
def check_host(ip):
ping = sr... |
from abc import ABCMeta, abstractmethod, abstractproperty
class Position():
def __init__(self, x, y):
self._position = (x, y)
self._x = x
self._y = y
def __eq__(self, other):
return self._x == other.x and self._y == other.y
@property
def position(self):... |
#!/usr/bin/env python3
import os
from functions import fuel_calculator, fuel_calculator_part_two
current_dir = os.path.dirname(__file__)
def part_one():
total_fuel = 0
with open(os.path.join(current_dir, "input.txt"), "r") as masses:
total_fuel = sum([fuel_calculator(int(mass)) for mass in masses])
... |
#!/usr/bin/env python
"""makemake V0.10
Copyright (c) 2010-2017 Michael P. Hayes, UC ECE, NZ
This program tries to make a Makefile from a template. Given a C file
(or a directory which searched to find a C file containing a main
function) the included header files are recursively searched. The for
each header file, ... |
import sys
from node import *
#input params
input_list = [-1, 1, 3, 7, 11, 9, 2, 3, 5];
partition = 5;
#make a linked-list using the input list
head = node(input_list[0]);
current_ref = head;
for index in range(1, len(input_list)):
current_ref.add_next(node(input_list[index]));
current_ref = current_ref.next;... |
from django.db import models
class User(models.Model):
phone = models.CharField(max_length = 100, null = False, blank = False)
def __str__(self):
return self.phone |
# coding: utf-8
import sys
from setuptools import setup, find_packages
def README():
with open('README.rst') as f:
return f.read()
# Backward-compatibility dependencies for Python 2
_python2_requires = [
'configparser',
'pathlib',
] if sys.version_info < (3,) else []
setup(
name='django-dev... |
'''
# 2016. 08. 19
'''
import pandas as pd
from pandas.tools.plotting import scatter_matrix
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
def main():
DnloadStockData(
"samsung.data", "005930", 2015, 1, 1, 2015, 12, 31)
df = loadStockData("samsung.data")
n,... |
def shift(letter, n):
pass
def encrypt(message, shift_amount):
pass
def decrypt(message, shift_amount):
pass
secret_message = "encryption is fun"
encrypted_message = encrypt(secret_message, 3)
print(encrypted_message)
|
# -*- coding: utf-8 -*-
class Iterator:
def __init__(self, nums):
self.nums = nums
def hasNext(self):
return bool(self.nums)
def next(self):
return self.nums.pop()
class PeekingIterator:
def __init__(self, iterator):
self.cache = None
self.iterator = iterato... |
import uuid
import os
import os.path
def get_file_path(instance,filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('images/uploads/', filename)
|
import yaml
import os
from collections import defaultdict
def get_id(myfile):
fil = myfile.strip().split("/")[-1]
return fil.strip().split(".")[0]
def get_umpires(dat):
ump = [None,None,None]
for i in range(len(dat)):
ump[i] = dat[i]
if i == 2:
break
return ump
def get_... |
#!/usr/bin/python3
"""
programmer : Amir Kouhkan
website : www.amirkouhkan.ir
E-mail : amirkouhkan1@gmail.com
This script it's so biegner, you can developed it and make it most usefull :D
"""
import sqlite3
def createDatabase():
global db
db = sqlite3.connect('save.db')
print("Database is created succe... |
# coding: utf-8
from sklearn.naive_bayes import MultinomialNB
from LSA import LSA
import numpy
class NaiveBayesClassifier:
def __init__(self, alpha):
self.classifier = MultinomialNB(alpha=alpha)
@staticmethod
def normalizer(x_abnormal):
minimum = x_abnormal.min()
maximum = x_abno... |
import myUsb
from myUsb import Queue
import json
import urllib2
from hashlib import *
import random
import unittest
import Webbrowser
import os
"""
To Do:
Function to store blockchain
Function to read blockchain
function to send manipulate JSON
main() function
"""
# stores all current data
currentData = []
# Stor... |
#!/usr/bin/python3
import numpy as np
from numpy import linalg as LA
# Centroid Decomposition, with the optional possibility of specifying truncation or usage of initial sign vectors
def centroid_decomposition(matrix, truncation = 0, SV = None):
# input processing
matrix = np.asarray(matrix, dtype=np.float64)... |
from django.db import transaction
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from tqdm import tqdm
from fetcher import tools
from fetcher.models import DataSource
from catalog.models import CatalogEntry, TLE
class Command(BaseCommand):
help = 'Import TLE f... |
# Generated by Django 3.0.3 on 2020-03-18 10:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0014_auto_20200316_1711'),
]
operations = [
migrations.AlterField(
model_name='membre',
name='mail',
... |
n = int(input())
for c in range(0, n):
p1, o1, p2, o2 = input().split(' ')
n1, n2 = map(int, input().split(' '))
if o1 == 'PAR' and (n1 + n2) % 2 == 0:
print(p1)
elif o1 == 'IMPAR' and (n1 + n2) % 2 == 0:
print(p2)
elif o1 == 'IMPAR' and (n1 + n2) % 2 != 0:
print(p1)
... |
class verbose:
def __init__(self, iterable, interval=None, fmt=None):
"""
Parameters
----------
iterable: iterable object to be wrapped
interval: int or None, verbosing interval in loop count
fmt: str or None, fstring for verbosing.
bar: st... |
# -*- coding: utf-8 -*-
"""
close the rabbit connection when the HTTP API finish
- catch the sigkill?
- deconstructor in the flask ext?
- check connection errors
"""
import json
import pika
from restapi.services.detect import detector
from utilities.logs import get_logger
log = get_logger(__name__)
QUEU... |
import subprocess
from flask import Flask
def create_app():
app = Flask(__name__)
app.config["DEBUG"] = False
app.config["SECRET_KEY"] = "pohu(jkC34&()sjhYN!mLoikdnJ??b7298YSos"
app.config["IPFS_DAEMON"] = subprocess.Popen(['ipfs', 'daemon'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
... |
import serial
port = "/dev/ttyACM0"
s1 = serial.Serial(port,9600)
s1.flushInput()
while True:
if s1.inWaiting()>0:
inputValue = s1.read(1)
print(ord(inputValue))
|
"""
Heber Cooke 10/24/2019
Chapter 5 Exercise 7
This program takes a text file and prints the unique words in alphibetical order
"""
fileName = input("Enter the file name: ")
f = open(fileName)
s = f.read().split() #Spliting the file into words
d =[] #List for already seen words
for x in s: # looping the empty list ... |
# Usage: python3 predict-test-dir-IResNetV2.py [path_to_directory_with_pictures] [correct_class]
# For instance: "python3 predict-test-dir-IResNetV2.py ./data/validation/Pitbull 1"
import os
import sys
import argparse
import numpy as np
from argparse import RawTextHelpFormatter
from keras.applications.inception_resn... |
#!/usr/bin/env python3
import argparse
import sys
from downloader import downloader
from cleanser import cleanser
from parser import parser
def main():
month, year = filter_param()
file_list, file_format = downloader(month, year)
df_struct = cleanser(file_list, file_format)
parser(month, year, file_l... |
#Setup
import praw, re, csv, random
#Validate Reddit Access
reddit = praw.Reddit(client_id='Dn_ef002ikq0dw',
client_secret='B_8gGLkYtz6aDmZ4tkP5Dj3BFIo',
password='zzzzzz',
user_agent='pix3lbot_scrape by /u/pix3lbot',
username='pix3lb... |
import sys
import os
import csv
from referenceframefunc import *
from hdf5retrieval import *
import numpy as np
from scipy import stats
import h5py
from itertools import chain
####################
# SET PRIOR TO USE
####################
CWD = '/home/selwyni/Desktop/h5/Dec 20 Data'
os.chdir(CWD)
def readHDF5(filename... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 10:41:16 2019
@author: Administrator
99: program finished
1 : adds num in two positions and store the result in third position.
2 : multiplies num in two positions and store the result in third position.
3 : takes an input to store in a specific pos
4 : outputs the va... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 15:37:49 2020
@author: Buzoni
This code can calculate de PnL, the DV01 and the Unit Price of
braziliaz Inflation-Linked Bonds
"""
from datetime import datetime, timedelta, date
from bizdays import Calendar
#Getting brazilians holidays from a txt.
HOLID... |
import mysql.connector
import dbconfig as cfg
db = mysql.connector.connect(
host=cfg.mysql['host'],
user=cfg.mysql['user'],
password=cfg.mysql['password'],
database=cfg.mysql['database']
)
cursor = db.cursor()
sql="CREATE TABLE accessories (id INT AUTO_INCREMENT PRIMARY KEY, type VARCHAR(255), brand VARCHAR(2... |
import os
# Scheme: "postgres+psycopg2://<USERNAME>:<PASSWORD>@<IP_ADDRESS>:<PORT>/<DATABASE_NAME>"
DATABASE_URI = "postgres+psycopg2://postgres:123@localhost/user_management"
providers = {
"LOCAL": "local",
"GOOGLE": "google"
}
class Config:
UPLOAD_FOLDER = 'static/'
MAX_CONTENT_LENGTH = 10 * 1024 *... |
import datetime, StringIO, re
from google.appengine.api import images
from google.appengine.api import taskqueue
from google.appengine.ext import db
import app.lib.EXIF as EXIF
from app.model.account import Account
from app.model.accounts import Accounts
from app.model.place import Place
from app.model.places impor... |
### Author: Acciente
### Version: 1.0
### Last modified date: 2017.06.29
### Usage : StrToRPN(inputStr)
### Function name is defined in funcList.
### Symbols that are not in funcList will be treated as unknown numbers.
funcList = ("sin", "cos", "tan", "asin", "acos", "atan", "sqrt")
numStr = "0123456789."
cha... |
from datetime import *
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, inch, landscape, portrait
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.styles import getSampleStyleSheet, ParagraphSty... |
number_wagons = int(input())
wagons = []
for _ in range(number_wagons):
wagons.append(0)
command_input = input()
while command_input != "End":
command_input = command_input.split(" ")
command = command_input[0]
if command == "add":
people = int(command_input[1])
last_wagon_people = w... |
# Python Standard Libraries
from datetime import datetime, timedelta
# Third-Party Libraries
from django.conf import settings
from django.contrib.auth.models import (AbstractBaseUser,
BaseUserManager,
PermissionsMixin)
from django.db import... |
class String:
def length(self,s):
print("The length of the string is",len(s))
def rev(self,s):
print("The reverse of the string is",s[::-1])
def con(self,s,s2):
print("The string after concatenation is",s," ",s2)
def cop(self,s):
self.st=s
print("The string is cop... |
import unittest
from katas.kyu_6.eighties_kids_7_shes_a_small_wonder import Robot
class RobotTestCase(unittest.TestCase):
def setUp(self):
self.vicky = Robot()
def test_equal_1(self):
self.assertEqual(self.vicky.learn_word('hello'),
'Thank you for teaching me hello')... |
from socketIO_client import SocketIO, LoggingNamespace
import cv2
import base64
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(8, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
video_capture = cv2.VideoCapture(0)
video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
video_ca... |
"""
Programmer: Keith G. Nemitz
E-mail: future@mousechief.com
Version 0.0.1 Development
"""
#The images module handles the loading of all graphics files
#conceptually, everything is a sprite.
#It also handles some graphics manipulations
#----------------------------------------------- IMPORTS
import os
import s... |
"""Functions to detect irregularities"""
import numpy as np
# --------------------------------------------------------------------------- #
# Utils
def linearize(a, index=-1):
"""Linearize vector in 2 linear segments
Assumption: a is based on regular step
Args:
a (np.ndarray)
index (in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from ?rc_node import ?RCNode
def main():
rospy.init_node("?rc_node_node")
rc_node = ?RCNode()
rospy.loginfo('%s: starting' % (rospy.get_name()))
rc_node.start()
if __name__ == "__main__":
main() |
class_names = ('Normal', 'No Lung Opacity / Not Normal', 'Lung Opacity')
|
import pygame
from pygame import Rect
from PIL import Image
import requests
from io import BytesIO
BLACK = (0,0,0)
class Piece(pygame.sprite.Sprite):
def __init__(self, color,x, y, x0=128, y0=128):
self.x0 = x0
self.y0 = y0
self.x = x
self.y = y
self.color = color
sel... |
import os;
from datetime import datetime, timedelta;
from ...utils.dateutils import next_month
from ..utils.send_email import send_email;
from ..utils.compress_netcdf_file import compress_netcdf_file;
from .ERAI_Downloader import ERAI_Downloader
ENDDATE = datetime(2019, 8, 1, 0)
class ERAI_General( ERAI_Downloader... |
import poker
#poker.run_simulation(4, "AdKd", "QdJdTd", 1)
#equity = poker.run_simulation(4, "6d3s", "", 1000000)
#print(f"My equity is {equity}")
test_array = poker.take_screenshot()
print(test_array.shape)
print(test_array.dtype)
print(test_array)
print(test_array[49][19])
print(test_array[48][18])
import mat... |
import torch
import json
from tqdm import tqdm
from collections import defaultdict, Counter
from vocab import Vocab
def get_freqs(path, fields):
"""
freqs is a dictionary, key being the field name and value
being a counter for the frequency of each token
"""
assert isinstance(fields, (list, tuple... |
import math
import random
from typing import List
from pyglet.sprite import Sprite
from version1.game.resources import *
from version2.game.PhysicalObject import PhysicalObject
def distance(point_1=(0, 0), point_2=(0, 0)):
"""Returns the distance between two points"""
return math.sqrt((point_1[0] - point_2[... |
import os, random
import numpy as np
import skimage.transform as tf
from scipy import ndarray, ndimage
from skimage import io, util
from PIL import Image
import PIL
# path variables and constant
from .. import root_dir
data_dir = root_dir.data_path()
# existing images
char_dir = "ko"
aug_crop_img_dir = os.path.join(... |
import numpy as np
import math
from operator import add
from scipy.stats import linregress
class DogGroup:
def __init__(self, height, weight, breed):
self.height = height
self.weight = weight
self.breed = breed
# implementing the factorial equation from scratch in python
def factorial(... |
import pyautogui as pag #library to run function related to mouse function
xscreen,yscreen = pag.size() #get screen size and print it
print('Xscreen: '+ str(xscreen).rjust(4)+' Yscreen:' + str(yscreen).rjust(4) )
try:
while True:
#print the posiition of the mouse coordinates
x,y = pag.position()
print('X: '+ st... |
import numpy as np
import math
class Network(object):
def __init__(self, sizes):
"""
"sizes" -> [1,2,3], where the 1st layer was 1 neuron and the other 2 have 2 and 3 respectively. Note that the 1st layer
is the input layer.
The Bias and the Weights are initialized at ... |
from Manager import Manager
def start():
exit = True
while exit:
menu()
option = get_option()
exit = execute_menu(option)
def menu():
print("____________Menu principal____________\n")
print("1. Agregar datos en una estructura\n")
print("2. Eliminar datos en una estructu... |
# how often does it beat ivv given 50 days?
# how often is 1 year up?
debug = None
import z
import queue
import buy
import sliding
import statistics
from sortedcontainers import SortedSet
import args
ETF = "VOO"
etf_wc, etf_bc, etf_ly, etf_l2y, etf_avg = 0, 0, 0, 0, 0
start = 650
istart = -1*start
req = start - 20
d... |
from __future__ import division
import numpy as np
# from numba import jit
def n_step_advantage(rewards, state_values, gamma=0.90, n=10):
"""Compute the n-step forward view advantages of a series of experiences.
This function calculates the n-step forward view temporal difference and subtracts the
estima... |
import metric_maximin
import metric_maximax
def calc(performance, maximise=True, alpha=0.5):
"""Returns the Optimism-Pessimism metric for a set of solutions
Metric obtained from:
Hurwicz, L. (1953) 'Optimality criterion for decision making under ignorance', Uncertainty and Expectations in Economics: Essay... |
hiddenimports = [
'fabio.edfimage',
'fabio.adscimage',
'fabio.tifimage',
'fabio.marccdimage',
'fabio.mar345image',
'fabio.fit2dmaskimage',
'fabio.brukerimage',
'fabio.bruker100image',
'fabio.pnmimage',
'fabio.GEimage',
'fabio.OXDimage',
'fabio.dm3image',
'fabio.HiPiCi... |
"""
CCT 建模优化代码
束线
作者:赵润晓
日期:2021年5月1日
"""
import multiprocessing # since v0.1.1 多线程计算
import time # since v0.1.1 统计计算时长
from typing import Callable, Dict, Generic, Iterable, List, NoReturn, Optional, Tuple, TypeVar, Union
import matplotlib.pyplot as plt
import math
import random # since v0.1.1 随机数
import sys
impor... |
from string import punctuation
from nltk.corpus import wordnet as wn
def preprocess_text(sentence):
sentence = sentence.lower()
for p in punctuation:
sentence = sentence.replace(p, '')
return sentence
def indicators():
return {
**dict.fromkeys(['noun', 'nn', 'thing', 'object', 'nn', ... |
from template.page import *
from template.config import *
from template.index import Index
import time
import copy
from math import floor
import threading
import concurrent.futures
import os
import json
INDIRECTION_COLUMN = 0
RID_COLUMN = 1
TIMESTAMP_COLUMN = 2
SCHEMA_ENCODING_COLUMN = 3
BASE_RID = 4
class Record:
... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = 'Man Li'
import os
import re
import sys
import time
import json
import random
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
import csv
from lxml import etree
from multiprocessing import Process
from itertoo... |
import time
import VehiclePWMModule
vehicle_servo = VehiclePWMModule.vehiclePWM("servo")
vehicle_esc = VehiclePWMModule.vehiclePWM("esc")
while(True):
#vehicle_esc.stop()
vehicle_esc.accel(1)#Forward
time.sleep(1)
vehicle_esc.accel(-10)
time.sleep(1)
|
#converted for ue4 use from
#https://github.com/tensorflow/docs/blob/master/site/en/tutorials/_index.ipynb
import tensorflow as tf
import unreal_engine as ue
from TFPluginAPI import TFPluginAPI
#additional includes
from tensorflow.python.keras import backend as K #to ensure things work well with multi-threading
impor... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver
from ckeditor.fields import RichTextField
from django.... |
b = "Hello, how are you?"
print(b[2:]) |
# Generated by Django 2.2.6 on 2019-10-16 17:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('checkout', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='shippingaddress',
name='first_name',
... |
n= int(input('Numarul de linii:'))
X=[[int(input())for a in range(n)]for b in range(n)]
print(' Matricea:')
for a in range(len(X)):
print(X[a])
s1=0
for a in range(0, len(X)):
s1+=X[a][a]
s2=0
for a in range(0, len(X)):
s2+=X[len(X)-a-1][a]
print('Suma componentelor diagonalei principale{s1}, Sum... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 5 22:35:01 2020
@author: sumant
"""
with open("mytask.txt",'w') as f:
f.write("Task Name : \n")
f.write("------------\n")
while True:
print("My To Do App")
print("============")
print("1. Add Task")
print("2. View All Tasks"... |
def result(ai, k):
rt = 0
for a in ai[::-1]:
if a <= k:
rt += k // a
k %= a
return rt
_ = list(map(int, input().split()))
N, K = _[0], _[1]
ai = list()
for n in range(N):
ai.append(int(input()))
print(result(ai, K))
|
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
"""
n = set(nums)
li = list()
for i in range(len(nums)):
if i+1 not in n:
li.append(i+1)
... |
#!/usr/bin/env python
"""
v0.1 Scipt used with PDB, to simulate what the ptf_master.py ipython tasks
do, when given a new diff-object.
- Useful for debugging source clustering, classification, ...
NOTE: 20090615: typically break around:
break ingest_tools.py:4528
NOTE: Before runni... |
# Generated by Django 3.1.1 on 2020-09-27 12:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scrapingApp', '0003_auto_20200927_1555'),
]
operations = [
migrations.AlterField(
model_name='parliament',
name='dat... |
import unittest
import numpy as np
import hpgeom as hpg
import healsparse
class FracdetTestCase(unittest.TestCase):
def test_fracdet_map_float(self):
"""
Test fracdet_map functionality for floats
"""
nside_coverage = 16
nside_fracdet = 32
nside_map = 512
non... |
"""
RainbowDash admin bot, includes code from autohelp.py and others.
Togglesmg from GreaseMonkey's whitelist script,
togglespade based off nogunall from hacktools.py
Adds /masterrefresh which will refresh the master connection every 30 min.
/togglesmg
/toggleshotty
/togglesemi
/togglespade
/noscope
/togglenade
/toggle... |
#test.py
#!/usr/bin/python
import sys
import os
import os.path
import getopt
def usage():
print("Syntax: fc [OPTIONS] [PATH]")
print("Options:")
print("-h/--help: Prints out this help section")
print("-f/--files: Prints name and number of files in the directory. Also prints total number of files")
print("-s/... |
#late fusion
import itertools
import random
import torch
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
import time
import argparse
import torch.utils.data as utils_data
from sklearn.model_selection import GridSearchCV,KFold
from sklearn.metrics import accuracy_score, f1_score,... |
# -*- coding: utf-8 -*-
"""
Application Values
"""
TEMP_CHAUDIERE_FAILURE_DEFAULT = 56 # Min Water temp before alerting of potential chaudiere failure
CHAUDIERE_DB_ROTATE_HOURS_DEFAULT = 5
CHAUDIERE_MINUTE_DB_ROTATE_DAYS_DEFAULT = 35
ALERTS_ENABLE_DEFAULT = False # Bool... |
from rich import box
from rich.layout import Layout
from rich.prompt import Prompt
from rich.table import Table
from .prettify_ldma import Header, make_sponsor_message
class MenuLayout:
def __init__(self):
self._layout = Layout()
self._table = Table(title="AUTOBOT MENU", expand=True,
... |
from django.apps import AppConfig
class WsocketConfig(AppConfig):
name = 'WSocket'
|
import copy
def testData():
otest = open('test.txt', 'r')
test = otest.readlines()
oanswer = open('answer.txt', 'r')
answer = oanswer.readline()
status = False
print("Runs test data")
result = runCode(test)
if result == int(answer): #not always int
status = True
pr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-02-23 12:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('leaderboard', '0003_auto_20180223_0848'),
]
operati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.