text stringlengths 8 6.05M |
|---|
# pi_list = list()
# pi1 = int(input("Введите делимое: "))
# pi2 = int(input("Введите делитель: "))
# for i in range(8):
# pi3 = (pi1 / pi2)
# pi_list.append(pi3)
# pi2 += 2
# pi = float(pi_list[0] - pi_list[1] + pi_list[2] - pi_list[3] + pi_list[4] - pi_list[5] + pi_list[6] - pi_l... |
#! /usr/bin/python3
import sys
import os
sys.path.insert(0, os.path.abspath('../models'))
import numpy as np
import matplotlib.pyplot as plt
from network import MutualInhibit
def f(s):
return 50 * (1 + np.tanh(s))
#1
def plot_nullclines(ls='-'):
MutualInhibit(f, np.r_[0,0]).plot_nullclines(ls=ls)
plt.... |
#!/usr/bin/env python
# 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.
"""
Verifies rules related variables are expanded.
"""
import sys
if sys.platform == 'win32':
print "This test is currently disabled: ht... |
import random
import discord
import asyncio
from discord.ext import commands
from DTbot import bot
from linklist import baddoggo_links, bkiss_links, blush_links, cage_links, cry_links, cuddle_links, glomp_links, handholding_links, highfive_links, hug_links, kiss_links, kick_links, lewd_links, lick_links, pat_links, pin... |
import time
import datetime
import traceback
from jinja2 import Template
from praw.models import Comment
import bot_logger
import config
import crypto
import lang
import re
import user_function
import utils
import dogetipper
def register_user(rpc, msg):
if not user_function.user_exist(msg.author.name):
... |
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import time
def admin_Portal():
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('http://localhost/Ghurai-Bangladesh/admin/admin_login.html')
u = driver.curren... |
from django.shortcuts import render
# from ..{{OTHER_APP}}.models import {{MODEL}}
def index( request ):
context = {
'models': {
# '{{MODEL}}': {{MODEL}}.objects.all(),
}
}
return render( request, "models_view/index.html", context )
|
import numpy as np
import logging
import os
import time
class mp_model:
id = None
logger = None
type = 'empty'
history = []
cfg = {}
# class instances
network = None
dataset = None
machine = None
def __init__(self, config = None, network = None, datas... |
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import MyUser
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
class Meta:
... |
import sys
import os
import warnings
import torch
import webdataset as wds
import typer
import braceexpand
from collections import Counter
from itertools import islice
from torchvision import transforms
# We're not using actual torch.distributed, since we just want to simulate
# how data is split between different no... |
# -*- coding: utf-8 -*-
import threading
from socket import *
from QueueTeam import PackQueueClass
class SendPackData:
def __init__(self,hostIp,hostPort):
self.hostIp=hostIp
self.hostPort=hostPort
self.tcpCliSock=""
self.packThread=None
self.sendPack=PackQueueCl... |
from functools import total_ordering
import json
import pickle
import re
import sys
from os import name
import numpy as np
from numpy.core.fromnumeric import size
from numpy.lib.utils import byte_bounds
import pandas as pd
# Convert from path reutrns a list of PIL images making it very easy to use
from pdf2image impor... |
"""animals URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
import numpy
import re
import pytest
import builtins
from unittest import mock
def swap_case():
line = input('')
return line.swapcase()
def test_swap_case_1():
with mock.patch.object(builtins, 'input', side_effect=['HackerRank.com presents "Pythonist 2".']):
assert swap_case()=='hACKERrANK.COM PRE... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.python.framework.stevedore.python_target_dependencies import (
InferStevedoreNamespac... |
import numpy as np
import random as rnd
import math
freq = 44100
ecart_fenetre = 1./441.
temps_fenetre = 0.030
def hamming_window (signal):
k =0
l =len(signal)
j =0
while (k <l/(ecart_fenetre*freq) and j<((2*l)-(ecart_fenetre*freq))):
for i in range(int(temps_fenetre*freq)):
signal[k*int(ecart_fenetre*freq)+i... |
if __name__ == '__main__':
# case1 -> only positives
from andrew_packages.programming_problems.greedy.\
expression_maximization.__init__ import first_positives, second
print("First set:")
print(first_positives)
print("Second set:")
print(second)
from andrew_packag... |
import re
import os
from pathlib import Path
lineRegex = re.compile(r'\s*(.*)\s*(".+")')
rubyRegex = re.compile(r'{rb}(.+?){/rb}\s*?{rt}(.+?){/rt}')
rubyRtRegex = re.compile(r'(.){rt}(.+?){/rt}')
def cleanFile(infile, outfile):
if not os.path.exists(os.path.dirname(outfile)):
os.makedirs(os.path.dirname(o... |
# 위의 그림과 같이 육각형으로 이루어진 벌집이 있다.
# 그림에서 보는 바와 같이 중앙의 방 1부터 시작해서
# 이웃하는 방에 돌아가면서 1씩 증가하는 번호를 주소로 매길 수 있다.
# 숫자 N이 주어졌을 때, 벌집의 중앙 1에서 N번 방까지
# 최수 개수의 방을 지나서 갈 때 몇 개의 방을 지나가는지
# (시작과 끝을 포함하여)를 계산하는 프로그램을 작성하시오.
N = int(input())
rng = 6
dist = 1
if N == 1:
print(1)
else:
while N-1>rng:
dist+=1
rng... |
from universal import process, clean_csv, add_trans_chunk
import sys
import re
# The infile is the system trancript.
infile = sys.argv[1]
# Using the system output name, the relevant universal format and full transcripts are gathered.
filename_prep = re.search(r"(?<=system-output\/)(.*?)(?=\.txt)", infile).group(0)
o... |
from __future__ import division
import sys
import subprocess
import glob, os
import shutil
## Author: Spencer Caplan, University of Pennsylvania
## Contact: spcaplan@sas.upenn.edu
outputFileNamesWithWordID = False
printDebugStatements = True
def accessDictEntry(dictToCheck, entryToCheck):
if entryToCheck in dictTo... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import asyncio
import aiohttp
import time
ev = asyncio.get_event_loop()
async def make_request():
async with aiohttp.ClientSession() as session:
async with session.get('http://localhost:8000/') as resp:
print(time.strftime("%H:%M:%S"), await resp.text())
async def request_producer():
whil... |
from .cyclic_lr import CyclicLR
from .learningratefinder import LearningRateFinder |
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
if maxChoosableInteger >= desiredTotal: return True
if (1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal: return False
def dfs(state, desiredTotal, dp):
if dp[state] != None:... |
# Generated by Django 2.0.2 on 2018-03-19 08:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import turtle, random, math
def main():
limit = 1
scale = 150
iterations = 5000
sidelength = scale * 2
count = 0
radius = limit * scale
# print(area)
turtle.tracer(0)
turtle.setworldcoordinates(-(scale), -(scale), (scale), (scale))
turtle.hideturtle()
turtle.penup()
tur... |
import string
import pandas as pd
import numpy as np
from babel.numbers import format_currency
# Function to convert currency into Rupee format
def in_rupees(curr):
curr_str = format_currency(curr, 'INR', locale='en_IN').replace(u'\xa0', u' ')
return(remove_decimal(curr_str))
def remove_decimal(S):
S = st... |
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
import os, urllib
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
import matplotlib.pyplot as plt
from data_cleaner import data_cleaner_funtion
from regression import regression_function
fro... |
# -*- coding:utf-8 -*-
'''
Created on 2016��4��1��
@author: huke
'''
def fib(max):
n,a,b = 0 ,0 ,1
while n < max:
print(b)
a , b = b , a+b
n += 1
return "done"
if __name__ == '__main__':
fib(8) |
l = input().split(' ')
s, a, n, c = 0, 0, 0, 0
while a == 0 or n == 0:
if int(l[c]) > 0:
if a == 0:
a = int(l[c])
elif n == 0:
n = int(l[c])
c += 1
for c in range(0, n):
s += a + c
print(s) |
# -*- coding: utf-8 -*-
"""
Build a modified DBpedia Spotlight model by manipulating the raw data.
"""
import os, json, urllib2, sys, re
import unicodecsv as csv
from collections import defaultdict
from vocabulary import get_target_db
csv.field_size_limit(sys.maxint)
target_db = get_target_db()
def uri_to_id(uri, spl... |
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <lucas@theis.io>'
__docformat__ = 'epytext'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.admin.views.decorators import staff_member_required
from ... |
#/usr/bin/env python3
# -*- encoding: utf8 -*-
server_version = "0.2.3"
server_log = """
0.0.3 2018-06-11 使用model提供的类方法而不是对象属性重构了项目,使用API解耦合。
添加了Pickle存储对象,方便进行调试。
对于从源HTML中获取Chapter的信息,提供了一个类方法,现在只需要一句话就可以完全自动构建Course对象,
其中自动化Course的信息、包含章节的信息以及每个章节相关笔记的信息。
0.0.4 2018-0... |
import numpy as np
def print_policy(q_table, SIZE):
# left, down, right, up
actions = [ ' ⬅ ', ' ⬇ ', ' ➡ ', ' ⬆ ' ]
for i, r in enumerate(q_table):
if 0 == (i % SIZE):
print()
max_action = np.argmax(r)
print(actions[max_action], end='')
|
from datetime import datetime, timedelta
from itertools import zip_longest
from decimal import Decimal, ROUND_HALF_UP
import copy
import json
from django.db.models import Q
from .cumulative_helper import _get_datewise_aa_data
from quicklook.calculations import garmin_calculation
from quicklook.models import UserQuick... |
# -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def maxNumberOfBalloons(self, text):
counts = Counter(text)
return min(
counts["b"], counts["a"], counts["l"] // 2, counts["o"] // 2, counts["n"]
)
if __name__ == "__main__":
solution = Solution()
... |
import socket
import time
import urllib.request
obj = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
time_per_signal = 5
addr = ("127.0.0.1",5883)
class handlers:
def nothing():
return "nothing"
def activate(link):
#Download and install
return "nothing"
def connect_to(obj,addr):
... |
def function(question_list):
ans_list=[2,1,4]
i=0
while i<len(question_list):
print(question_list[i])
j=0
while j<len(option_list[i]):
print(option_list[i][j])
j=j+1
def function2(ans):
if ans!=ans_list[i]:
print("correct",a... |
import os
import sys
import io
import urllib.request as req
import requests,json
import urllib.parse as rep
from bs4 import BeautifulSoup
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
input_x = [1,2,3,4,... |
"""
Example program for receiving gesture events and accelerometer readings from Kai
"""
import os
import time
import configparser
from KaiSDK.WebSocketModule import WebSocketModule
from KaiSDK.DataTypes import KaiCapabilities
import KaiSDK.Events as Events
from pythonosc.dispatcher import Dispatcher
from pythonosc.... |
from decimal import Decimal
from django.conf import settings
from books.models import Book
from operator import itemgetter
class Cart(object):
def __init__(self, request):
"""
Initialize the cart.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSI... |
#!/usr/bin/env python
# This script will get the highest UID available under 500
import subprocess
uid_list = []
unique_uid = []
cmd = ["dscacheutil", "-q", "user"]
output = subprocess.Popen(cmd, stdout=subprocess.PIPE)\
.stdout.readlines()
for _ in output:
if "uid" in _:
uid_list.append(_.strip().... |
#!/usr/bin/python3
#
# Send a String message from command line to an AMQP queue or topic
#
# Useful for testing messaging applications
#
# To install the dependencies:
#
# Debian / Ubuntu:
# apt install python3-qpid-proton
#
# RPM:
# dnf install qpid-python
#
# See README_AMQP_Apache_Qpid_Proton.txt
#
# C... |
from flask import Flask, render_template, request, redirect
from pymongo import MongoClient
from bson import ObjectId
client = MongoClient('mongodb://user:As1234@ds245971.mlab.com:45971/catpedia')
db = client['catpedia']
cat_collection = db['cats']
app = Flask(__name__)
@app.route('/')
def index():
cats = list(... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-10 12:15
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('k8sproject', '0005_auto_20180610_1954'),
]
operati... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 10:23:54 2020
@author: Alex
"""
import numpy as np
import matplotlib.pyplot as plt
from Analysis_Methods import NLL_1
from Univariate import univariate
#Import univariate method and apply it to mininise mass first
#Extract the function minima, the curvature, and the ... |
import random
def play():
user = input ("rock press 'r', paper press'p' scissors press 's'\n")
user = user.lower()
computer = random.choice(["r", "p","s"])
if user == computer:
return "its a tie, you have both choosen{}"
if win(user, computer):
return" you have won, you have choosen{}the computer has ch... |
# -*- coding: utf-8 -*-
#Operadores Relacionais
x = 2
y = 3
#Igual == usamos o igual para comparar se dois valores são iguais
print(x == y) #x vale 2 e y vale 3, logo o resultado é False (Falso), pois o numero 2 é diferente de 3
#Diferente != usamos o diferente para comparar se dois valores são diferentes
print(x !=... |
'''program to input a multidigit no. and
1)print sum
2)print the reverse number
3)check whether the given no. is a palindrome '''
n=input("Enter A Multidigit Number:")
i=1
s=0
while n>i:
f=i*10
x=(n%f)
x=x/i
s=s+x
i*=10
print 'Sum Of The Digits Is', s
m=n
r=0
while n!=0:
d=n%10
... |
## Script (Python) "getPastasRaiz"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
path={ "query": "/automator", 'depth': 1 }
pastas = context.portal_catalog.searchResults(Type=['Folder'], sort_on="getObjPositionInParent"... |
import itertools
import torch
from sklearn.neural_network import MLPRegressor
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# data = [line.strip() for line in open('/Users/ksnmurthy/research-work/data-kern/pitch-plots/data_schweiz.txt', 'r')]
data = [line.strip() for line... |
from random import randrange
# method 1 O(n**2)
def twoNearestNum1(seq):
dd = float("Inf")
for i in seq:
for j in seq:
if i == j:
continue
d = abs(i - j)
if d < dd:
ii, jj, dd = i, j, d
return ii, jj, dd
# method 2 O(n*log(n))
def... |
import asyncio
from asyncio.exceptions import CancelledError
async def producer(q):
for i in range(10):
await q.put(i)
await asyncio.sleep(0.1)
async def watcher(q, name):
while True:
task = await q.get()
print(f"{name} got {task}")
await asyncio.sleep(1)
q.task... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import Iterable, Mapping
from pants.core.goals.test import TestResult
from pants.engine.internals.native_engine import Address
from pants.jv... |
import os
os.chdir(os.path.dirname(__file__))
print(str(os.getcwd()))
os.system('cmd /k "python automation.py"') |
#!/usr/bin/env python
# coding=utf-8
import numpy as np
def calc_entropy(x):
"""
calculate shanno ent of x
"""
x_value_list = set([x[i] for i in range(x.shape[0])])
ent = 0.0
for x_value in x_value_list:
p = float(x[x == x_value].shape[0]) / x.shape[0]
logp = np.log2(p)
... |
from brain_games.games import progression
from brain_games import engine
def main():
engine.run(game=progression)
|
import socket
import sys
# Create a UDP socket
messages = ["HELP", "LOGIN MTECH GITRDONE", "STATUS", "START", "STOP", "LOGOUT"]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (sys.argv[1], 4547)
commands = []
commands.append(sys.argv[2])
if len(sys.argv) > 3:
commands.append(sys.argv[... |
import time
import json
import paho.mqtt.client as mqtt
def pluie(client, boule,dt):
cmds=[]
cmds1=[]
rings = [2,1,0]
for i in rings :
cmd = {
'command': 'set_ring',
'ring': i,
'rgb': [0, 0, 255]
}
cmd1 = {
'command': 'set_ring',
'ring': (... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\InputKey.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, Q... |
n1 = int(input('Digite a Nota 1: '))
n2 = int(input('Digite a Nota 2: '))
mediaNotas = (n1+n2)/2
print('A NF foi: {}!'.format(mediaNotas))
if mediaNotas < 5.0:
print('REPROVADO!')
elif mediaNotas >= 5.0 and mediaNotas < 6.9:
print('RECUPERAÇÃO')
else:
print('APROVADO!') |
#-*- coding: utf-8 -*-
"""
forms/activity.py
~~~~~~~~~~~~~~~~~~
定义活动相关的表单
"""
from flask.ext import wtf
from scriptfan.forms import RedirectForm
class ActivityForm(RedirectForm):
title = wtf.TextField(u'活动标题', validators=[ \
wtf.Required(message=u'请为活动填写一个标题')])
content = wtf.TextAreaF... |
# Code for CS229 Final
import numpy as np
import sklearn as skl
import skimage as ski
import pandas as pd
import matplotlib.pyplot as plt
import xlrd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn import linear_model
from sklearn import preprocessing
from sklearn.pre... |
#square each ele and store in other lst
nums = [1,2,3,4,5,6,7,8,9]
lst=[]
for num in nums:
lst.append(num*num)
print(lst) |
import gensim
import numpy as np
import pandas as pd
from ..util import defines
from ..util import file_handling as fh
def main():
input_filename = fh.make_filename(defines.data_token_dir, 'ngrams_1_rnn_all', 'json')
response_tokens = fh.read_json(input_filename)
print "Building token set"
token_set... |
#Szum.py
import numpy as nm
import matplotlib.pyplot as plt
def error_calc(lengthdata, noise_amp):
b = nm.random.uniform(-1, 1, lengthdata)
signal = nm.zeros(lengthdata,float)
for i in range(len(b)):
if b[i] < 0:
signal[i] = -1
else:
signal[i]=1
n... |
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import gettempdir
import os
from helpers import *
# configure application
app = Flask(__name__)
# ensure... |
class Collection(object):
def __init__(self, update_func):
self._update_func = update_func
self._elements = None
def __dir__(self):
if self._elements is not None:
return self.__dict__
else:
self.refresh()
return self.__dict__
def __getite... |
def finite_iteration():
companies = [
'google',
'ibm',
'adobe',
'nike',
'target',
]
def infinite_iteration():
if __name__ =="__main__":
finite_iteration()
infinite_iteration()
|
import os
import sys
from torch import nn
import time
import pdb
sys.path.append('../..')
from fastreid.config import get_cfg
from fastreid.engine import DefaultTrainer, default_argument_parser, default_setup
from fastreid.utils.checkpoint import Checkpointer
from fastreid.evaluation import ReidEvaluator
from build im... |
class GlaesError(Exception): pass |
from rest_framework import routers
from .views import CategoryModelViewSet
router = routers.SimpleRouter()
router.register(r'categories', CategoryModelViewSet)
urlpatterns = router.urls
|
from accounts.models import Address
from django.shortcuts import render_to_response
from dajax.core.Dajax import Dajax
def addresses_by_user(request,user_id):
addresses=Address.objects.filter(user__id=user_id)
dajax = Dajax()
dajax.alert('123')
return dajax.json()
|
def count(L, S):
diff = len(L) - len(S)
if diff < 0:
return 0
cnt = 0
for i in range(diff+1):
if S == L[i:i+len(S)]:
cnt += 1
return cnt
while True:
try:
S, L = input().split()
s1 = count(L, S)
s2 = sum([count(L, s) for s in set([S[:i] + S[i... |
#coding:utf-8
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
def show_data(y, y_pred, title):
plt.f... |
# -*- python -*-
# Assignment: Stars
# Write the following functions.
# Part I
# Create a function called draw_stars() that takes a list of numbers and prints out *.
#
# For example:
# x = [4, 6, 1, 3, 5, 7, 25]
# draw_stars(x)
# Should print the following:
# ****
# ******
# *
# ***
# *****
# *******
... |
#!/usr/bin/env python
# Copyright (c) 2009 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.
"""
Verifies simple build of a "Hello, world!" program with static libraries,
including verifying that libraries are rebuilt correctly when ... |
from enum import Enum
class PullRequestState(Enum):
OPEN = 'OPEN'
CLOSED = 'CLOSED'
MERGED = 'MERGED'
class ReviewDecision(Enum):
NACK = 'NACK'
CONCEPT_ACK = 'CONCEPT_ACK'
UNTESTED_ACK = 'UNTESTED_ACK'
TESTED_ACK = 'TESTED_ACK'
NONE = None
|
'''
建议每级缩进都使用四个空格,这既可提高可读性,又留下了足够的多级缩进空间
建议每行不超过 80 字符
建议注释的行长都不超过 72 字符
要将程序的不同部分分开,可使用空行
''' |
# This file is part of beets.
# Copyright 2021, Edgars Supe.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... |
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
def input():
return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
return random.randint(ran1,... |
# -*- coding: utf-8 -*-
def com(n):
return float(n*(n-1)/2)
if __name__ == "__main__":
fid = open('main.txt','r')
#fout = open('out.txt','w')
k,m,n = [int(x) for x in fid.readline().split()]
print 1-(com(n)+com(m)/4+m*n/2)/com(k+m+n)
|
from datetime import date
from . import db
class Company(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), unique = True)
transaction_date = db.Column(db.DateTime)
per_share_deal_price = db.Column(db.Float)
executives = db.relationship('Executive', backref='c... |
__author__ = 'Aravinth Panchadcharam'
__email__ = "me@aravinth.info"
__date__ = '22/04/15'
import cv2
if __name__ == '__main__':
img = cv2.imread('test.jpg', 0)
image_small = cv2.resize(img, (800, 600))
cv2.imshow('image', image_small)
cv2.waitKey(0)
cv2.destroyAllWindows() |
# classification backend
# Load libraries
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pickle # allows to save differnt trained models of the same classifier object
import time
import streamlit as st
@st.cache
def query_lightcurve_XD(SourceID):
"""
Download ... |
import pygame
import math
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 736
class Player:
# Direction: 0 = right, 1 = down, 2 = left, 3 = up
def __init__(self):
self.image = pygame.image.load('./pics/player.png')
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
s... |
# This file is part of beets.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribu... |
# simple-crack.py - simple cracking method for linksys routers using JNAP library
# May 4th 2019
# info@tpidg.us
from jnap.router import Linksys
from time import sleep
import json
import sys
import getpass
addr = sys.argv[1]
dict = sys.argv[2]
router = Linksys(addr)
passwords = [line.rstrip('\n') for line in open(d... |
import unittest
import time
from utils import get_config
from utils import get_driver
class TestBase(unittest.TestCase):
def setUp(self):
self.config = get_config()
self.driver = get_driver()
time.sleep(0.5)
self.driver.maximize_window()
def tearDown(self):
... |
class Measures(object):
def __init__(self, measures_list=[]):
self.measures_list = measures_list[:]
def get_measures(self):
"""Return a list of Measure"""
#print dir(self.measures_list)
#print self.measures_list[0] is self.measures_list[3]
#raw_input('pigia2')
... |
from distutils.version import StrictVersion
VERSION = StrictVersion('0.3.5')
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-07-26 14:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('features', '0009_auto_20190724_1025'),
]
operations = [
migrations.RemoveFiel... |
import requests
#######
#This code works for getting a list of the courses
######
def sendRequest(url, headers):
r = requests.get(url, headers=headers)
return r
def getCourses(authToken):
headers = {}
headers["Authorization"] = authToken
r = sendRequest("https://classroom.googleapis.com/v1/courses", headers=head... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import hashlib
import os
import pkgutil
import shutil
import socket
import ssl
import tarfile
import time
from dataclasses import dataclass
from http.se... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
# NB: Mark this as an explicit namespace package, so that `pants.testutil`
# can be loaded, if installed.
# (We can't rely on an implicit namespace package as pytest chooses package names ... |
# Generated by Django 2.2 on 2019-04-26 10:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
#!/usr/bin/env python
import argparse
# define interface
def cml_interface():
parser = argparse.ArgumentParser(description='compare two strings representing versions')
parser.add_argument(dest='strings', type=str, nargs='+')
return parser.parse_args()
def compare_versions(s1, s2):
l1 = s1.split('.')
... |
from random import *
x = randint(1,50)
print("Random first value :",x)
y = randint(2,5)
print("Random second value :",y)
print("x power y :",x**y) |
def gcd_test_two(a, b):
if a>b:
a, b=b, a
if b%a==0:
return a
else:
return gcd_test_two(a,b%a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.