text stringlengths 38 1.54M |
|---|
a=input("Enter number 1") # input number 1 ex. 5
b=input("Enter number 2") # input number 2 ex. 7
print (a+b) # output will be 57 because data type of input function is string by default so when we add strings they get concatenated
|
'''
面向对象思想
'''
'''
软件编程实质:
软件编程就是将我们的思想转变成计算机能够识别语言的一个过程
什么是面向过程?
自上而下顺序执行,逐步求精
其程序结构是按功能划分为若干个基本模块,这是树状结构
各模块之间的关系尽可能简单,子啊功能上相对独立
每一模块内部均是由顺序,选择和循环三种基本机构
其模块化死心啊的具体方法是使用子程序
程序流程在写程序时就已决定
什么是面向对象?
把数据及对数据的操作方法放在一起,作为一个实体--对象
对同类对象抽象出其共性,形成类。
类中的大多数数据,只能用本类的方法进行处理
类通过一个简单的外部结构与外界发送关系,对象通过消息进行通信。
程序流程由用户在使用中决定
理解面向对... |
# coding=utf-8
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
class CourseViewTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = reverse('app:course:manage')
#def tearDown(self):
# pass
def test_course_ok(self):
response = self.client.get(self.ur... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
import xlrd
class Dingdan(object):
def chaxun_shuju(self):
chaxun = []
f = xlrd.open_workbook(r'C:\Users\kong\Desktop\python学习\接口框架练习\data\dingdan_chaxundingdan.xlsx')
sheet = f.sheets()[0]
aa = sheet.nrows
for i in range(aa):
... |
import time, json, requests, os, sys
from ConfigParser import ConfigParser
from lxml import etree
from datetime import datetime
import pystache
from lib import (
get_bbox, getstate, getosc, point_in_box, point_in_poly,
hasbuildingtag, getaddresstags, hasaddresschange, loadChangeset,
addchangeset, html_tmpl... |
import threading
import socket
import base64
from typing import TYPE_CHECKING
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
from electrum.i18n import _
from electrum.plugin import hook
from electrum.bip32 import xpub_type, BIP32Node
from electrum.util import UserFacingException
from electrum im... |
from skimage.io import imread, imsave
import matplotlib.pyplot as plt
import numpy as np
import os
import warnings
def read_rich_labels(path):
"""
Checks the structure of your rich_labels.txt file.
Returns a dictionary:
key: file name
value: a tuple of floats (<latitude>, <longitude>)
"""
location_dict = {}
... |
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import tree
import warnings
import sys
import cv2
from skimage import io, color, img_as_ubyte
from skimage.feature import greycomatrix, greycoprops
from sklearn.metrics.cluster import entropy
from scipy.stats import skew
... |
from __future__ import unicode_literals, print_function, absolute_import
from marshmallow import MarshalResult
from marshmallow import Schema, ValidationError
from restie.exceptions import InvalidArgumentsError
from werkzeug.datastructures import CombinedMultiDict, MultiDict
from .base import MethodsDecoratorEntrypoi... |
#Problem ID: ENTEXAM
#Problem Name: Entrance Exam
for _ in range(int(input())):
n, k, e, m = map(int, input().split())
l = []
for i in range(n-1):
l.append(sum(list(map(int, input().split()))))
ser = sum(list(map(int, input().split())))
l.sort(reverse = True)
min_score = l[k-1]+1 -ser
... |
'''
定制类
看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的。
'''
'''
__str__
'''
class Student(object):
def __init__(self, name):
self.name = name
print(Student('Mic'))
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name:%s)' % self.name
... |
import sys
import configparser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from time import sleep
inifile = configparser.SafeConfigParser()
inifile.read('/Users/TK/project/a... |
from gen3.tools.metadata.ingest_manifest import async_ingest_metadata_manifest
from gen3.tools.metadata.ingest_manifest import async_query_urls_from_indexd
from gen3.tools.metadata.verify_manifest import async_verify_metadata_manifest
|
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
clean away the 10% of points that have the largest
residual errors (different between the prediction
and the actual net worth)
return a list of tuples named cleaned_data where
each tuple is... |
"""
Дан список чисел. Определите, сколько в этом списке элементов, которые больше двух своих соседей (слева и справа),
и выведите количество таких элементов. Крайние элементы списка никогда не учитываются,
поскольку у них недостаточно соседей.
"""
# # Вариант 1
# from random import randint
#
# lst = [randint(1, 20) fo... |
#################################################################### MODULE COMMENTS ############################################################################
#The following class is a python object that takes in the libraries: Nunmpy, Pandas, Sys and Random. ... |
import pytest
from TestData.Configuration import Config
from Tests.BaseTestSuite import BaseTestSuite
from PagesFactory import PagesFactory
pytestmark = [pytest.mark.skipif((Config.LOGIN is None or Config.PASSWORD is None), reason='LOGIN and Password required'),
pytest.mark.login]
class TestLoginSui... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Xie Yanbo <xieyanbo@gmail.com>
# This software is licensed under the New BSD License. See the LICENSE
# file in the top distribution directory for the full license text.
"""A debug library and REPL for RobotFramework.
"""
from __future__ import print_function
i... |
"""
chapter 6
Lists
pg 123 - 146
"""
# 124
# cmd python
# ctrl + z to exit
"""
# Strings Literals
# Double Quotes
spam = "that is Alice's cat."
# Escape Characters
spam = 'Say hi to Bob\'s mother.'
works!!
"""
# 125
# cmd python
# ctrl + z to exit
"""
print("Hello there!\nHow are you?\nI\'m doing fine. "... |
# --- Find the Median
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
# --- My solution
def median(a,b,c):
if a == biggest(a,b,c):
a = 0
return biggest(a,b,c)
if b == biggest(a,b,c):
b = 0
return big... |
import requests
import urlparse
import os
from bs4 import BeautifulSoup
def get_pdf_urls():
"""Scrape the Supreme Court oral argument transcript sites
to return a list of urls to all of the oral argument transcript pdfs.
The site urls look like this:
http://www.supremecourt.gov/oral_arguments/argumen... |
from django.contrib import admin
from .models.category import Category
from .models.page import Page
class teste_Category(TestCase):
def teste_comment_nulo(self):
Category.objects.get_or_create(name = "Teste")
self.assertEquals(Category.objects.find(name = "Teste"),True)
|
import numpy as np
'''动态规划
'''
def minPathSum_M_N(m):
if (len(m) == 0) or (len(m[0]) == 0):
return 0
rows = len(m)
cols = len(m[0])
matdp = np.zeros((4,4))
# print(matdp)
matdp[0][0] = m[0][0]
for i in range(1, rows):
matdp[i][0] = matdp[i-1][0] + m[i][0]
for j in rang... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from watchdog import Watchdog
if __name__ == "__main__":
Watchdog(["osascript", "-e", """tell application "Safari"
do JavaScript "window.location.reload()" in front document
end tell"""]).run()
|
import sys
import configparser as cp
try:
from pyspark import SparkContext, SparkConf
props = cp.RawConfigParser()
props.read("src/main/Resources/application.ini")
# env = sys.argv[1]
conf = SparkConf().setMaster(props.get(sys.argv[5], 'executionMode')).setAppName("Revenue Per Month")
... |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class DblpItem(scrapy.Item):
# define the fields for your item here like:
ConOrJou = scrapy.Field()
ConOrJouName = scrapy.Field()
authors = scrapy.Field()
... |
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if not nums or len(nums) < 4: return []
nums.sort()
res = []
for i in xrange(len(nums)-3):
if i != 0 an... |
def main():
maxi = 0
n, m = map(int, input().split())
lst = list(map(int, input().split()))
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
if maxi < lst[i]+lst[j]+lst[k] <= m:
maxi = lst[i]+lst[j]+lst[k]
print(maxi)
main()... |
# Python 3.4 program to recursively scan from current folder
# or folder dropped onto file or specificed in command line
# for every file with an extension in the exts list:
# check if file's album tag is "recompressed", if not recompress it, and add that tag
# then rename/overwrite of OVERWRITE = True
#
#
#
# Copy ffm... |
from tools.test_case_generators.raw_file_reader.raw_file_reader \
import RawFileReader
import abc
import sys
class KuugaPseudoInstruction(object):
"""
An abstract class that represents a Pseudo-Assembly language instruction.
Crucially it contains a method that allows the instruction to be expanded.
... |
import inquisition as inq
from pathlib import Path
from tqdm import tqdm
import whoosh.index
import argparse
import sys
def parse_args(args):
"""
Returns arguments passed at the command line as a dict
:param args: Command line arguments
:return: args as a dict
"""
parser = argparse.ArgumentPar... |
'''
기본 자료 구조 array
배열의 필요성 : 동일한 자료형을 한번에 관리하기 위함, index 번호로 관리
배열의 장점은 인덱스 번호로 빠르게 찾아 갈 수 있다는 것.
배열의 단점은 배열 생성시에 메모리 할당 범위를 정해 놓고 하기 때문에
새로운 데이터를 추가해서 넣기가 어렵고 (메모리가 고정적) 삭제 시에 중간의 메모리가 비기때문에
앞으로 당겨와야 하는 단점이 있음
Python 은 array 의 향상된 형태이기 때문에, c 와는 다르게 작성해야 되서
배열의 장단점이 와닿지 않는 경우가 많음 (메모리... |
"""
Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com
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, m... |
from mytools import get_time
@get_time
def main():
(v1, v2) = (1, 2)
max = 4 * (10**6)
s = 0
while v2<=max:
if not v2 % 2: s += v2
(v1, v2) = (v2, v1+v2)
print s
@get_time
def main2():
(v1, v2) = (1, 2)
max = 4 * (10**6)
s = 0
while v2 <= max:
s += v2
(v1, v2) = (v1+2*v2, 2*v1+3*v2)
... |
{
"targets": [{
"target_name": "dm-codec",
"sources": [
"src/dm-codec.cc",
"src/datamatrix.cc"
],
"include_dirs" : [
"<!@(node -p \"require('node-addon-api').include\")"
],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '... |
from django.contrib import admin
from .models import *
# Register your models here.
# 注册模型Article
class ArticleAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'text', 'get_read_num')
admin.site.register(Article, ArticleAdmin)
admin.site.register(Diary, ArticleAdmin)
|
# -*- coding: utf-8 -*-
"""
Node discovery and network formation are implemented via a kademlia-like protocol.
The major differences are that packets are signed, node ids are the public keys, and
DHT-related features are excluded. The FIND_VALUE and STORE packets are not implemented.
The parameters necessary to impleme... |
#mini.py
def foo():
print("这是模块mini的函数foo")
if __name__ =="__main__":
print("这是一个模块文件mini")
|
import pygame
import sys
import colors
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
month_length = 28
current_date = 1
def get_day_of_week(date, month_length):
return days_of_week[(date - 1) % len(days_of_week)]
def inc_date():
global current_date
current_... |
#----------------------------------#
#-------- MailCleaner v0.1 --------#
#----------------------------------#
# #
# by: Alessandro Carrara(alkz) #
# email: alkz.0x80@gmail.com #
# build date: 2011-03-22 #
# for: PoliGrafica SRL #
# ... |
#!/usr/bin/python
import os, sys, shlex
from glob import glob
from subprocess import call
from optparse import OptionParser
dirsNotFound = []
options = []
args = []
def dcm2nii(file):
niis = glob("nii/*.nii.gz")
if len(niis) > 0:
for f in niis:
os.remove(f)
niiCmd = 'dcm2nii -a ... |
# Generated by Django 2.2.9 on 2020-07-18 12:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0023_auto_20200704_1346'),
]
operations = [
migrations.CreateModel(
name='StockAnalysisD... |
import threading
import logging
from common.Common import Locking
from Logger import Logger
class Cache:
'''LRU strategy'''
class Node:
__slots__ = ['key', 'val', 'succ', 'prev']
def __init__(self, key, val):
self.key = key
self.val = val
self.succ = None
... |
import numpy as np
import os
def read_list(list_file_path):
with open(list_file_path) as f:
lines = f.readlines()
frame_list = []
for i, line in enumerate(lines):
if line.startswith('#'):
continue
tokens = line.split(' ')
frame_list.append(tokens[0].strip())
... |
#!/usr/bin/python
__author__ = "Donghoon Lee"
__copyright__ = "Copyright 2016"
__credits__ = ["Donghoon Lee"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Donghoon Lee"
__email__ = "donghoon.lee@yale.edu"
###
### Predict Y and save results as NPY
###
### Usage: python postproc_modelPred.py -m splicing_... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import time
import urllib.request
try: #python3
from urllib.request import urlopen
except: #python2
from urllib2 import urlopen
from PyQt5.QtWidgets import QApplication, QDesktopWidget
from PyQt5.QtCore import QObject, pyqtSlot, QUrl, Qt, QPoin... |
'''
The primes 3, 7, 109, and 673, are quite remarkable. By taking
any two primes and concatenating them in any order the result
will always be prime. For example, taking 7 and 109, both 7109
and 1097 are prime. The sum of these four primes, 792, represents
the lowest sum for a set of four primes with this property.
F... |
__author__ = 'Mies'
'''
Inleveropdracht Week 5, Pyramide/diamant:
Schrijf een programma dat aan de gebruiker een getal vraagt. Hij toont dan een pyramide patroon op basis van dit getal, waarbij het ingevoerde getal boven staat en elke opvolgende regel dit getal met 1 eenheid minder. Als de gebruiker geen getal invoert... |
# FTP port
PORT = 21
# Maximum duration from an initial probe to a successful login
SCAN_TIMEOUT = 20
# Maximum simultaneous scan tasks
MAX_SCAN_TASKS = 1000
# Interval between scans
SCAN_INTERVAL = 10 * 60
# Offline time after which a server is forgotten
OFFLINE_DELAY = 24 * 3600
# Timeout for the connection to a... |
import re
import socket
from twisted.mail.smtp import ESMTPSenderFactory, sendmail
from twisted.internet.defer import Deferred
from twisted.internet import reactor
from twisted.internet import threads
from cStringIO import StringIO
from email.generator import Generator
import mailer
EMAIL_RE = re.compile(r"(?P<loca... |
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> data = b'Hello World'
>>> data[0:5]
b'Hello'
>>> data.startswith(b'Hello')
True
>>> data.split()
[b'Hello', b'World']
>>> data.replace(b'Hello', b'... |
import copy
from datetime import datetime
import json
version = 1.0
class MetaBase():
"""MetaBase class"""
def __init__(self, name='', value='', description=''):
self.name = name
self.value = value
self.description = description
def get_dict(self):
return copy.deepcopy(se... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
from firstimage_extractor import *
HUDONG_DUMP='/home/xlore/disk2/data/hudong/hudong-dump-20120823.dat'
OUTPUT = 'hudong.firstimage.dat'
TTL = '/home/xlore/Xlore/etc/ttl/xlore.instance.icon.hudong.ttl'
INSTANCE_LIST='/home/xlore/Xlore/etc/ttl/xlore.instance.list.ttl'
class Hud... |
"""
Originally ported from code at:
http://code.google.com/apis/chart/docs/data_formats.html#encoding_data
retrieved 2010/03/13, but then was cleaned up, enhanced, fixed, etc.
"""
import string
import math
def is_number(s):
try:
float(s)
return True
except ValueError:
retu... |
# Вывести последнюю букву в слове
word = 'Архангельск'
print(word[-1])
# Вывести количество букв а в слове
word = 'Архангельск'
count_a = 0
for l in word:
if l.lower() == 'а':
count_a += 1
print(f"The amount of a is: {count_a}")
# Вывести количество гласных букв в слове
word = 'Archangelstk'
vowels = 'a... |
import cv2
__belgium_file = "CoreFlags/Flag_of_Belgium.png"
__france_file = "CoreFlags/Flag_of_France.png"
__germany_file = "CoreFlags/Flag_of_Germany.png"
__trans_pride_file = "CoreFlags/Transgender_Pride_flag.png"
__indian_file = "CoreFlags/Flag_of_India.png"
__serbian_file = "CoreFlags/Flag_of_Serbia.png"
__panama_... |
#from tensorflow import keras
#from tensorflow.keras.layers import Dense
#from tensorflow.keras import layers
import os
from os import listdir
from os.path import isfile, join, isdir
import nltk
from keras_preprocessing.text import Tokenizer
from nltk.corpus import stopwords
import pymorphy2
from sklearn.feat... |
import sys
import numpy as np
import matplotlib.pyplot as plot
import simulate
import learn
import random
threshold = 0.8
outcomes = [True, False]
rcaps = []
qcaps = []
r = {'mu': 50, 'sigma': 10}
p = {'mu': 60, 'sigma': 10}
length = 100
size = 500
workers = simulate.createHyperbolicWorker(size, r, p, None, 1)
... |
import pandas as pd
import json
xls = pd.read_csv('datos.csv',na_values=['no info','.']#,index_col='Month'
)
# xls.head(#)
# meses= xls['Month']
print(xls)
# with open('datos.json') as json_file:
# data = json.load(json_file)
# for i in data:
# print (i) |
from apistar import App as BaseApp, Route, TestClient, http
from apistar_sentry import SentryMixin
class App(SentryMixin, BaseApp):
pass
class SomeHook:
def on_response(self, response: http.Response) -> None:
response.headers["x-example"] = "example"
def index():
return {}
app = App(
rou... |
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import random
import time
plt.style.use('ggplot')
def binarySearch(arr, l, r, x, c):
c+=1
while l <= r:
c+=1
mid = l + (r - l)//2;
if arr[mid] == x:
c+=1
return c
elif ar... |
import numpy as np
array = np.random.rand(100)
array[5] = np.nan
# Returns inccorrect result
print(np.max(array))
# nan
# Returns correct result
print(np.nanmax(array))
# 0.992949280963
|
startStr = raw_input("Where to start? > ")
endStr = raw_input("Where to end? > ")
byStr = raw_input("Count by > ")
start = int(startStr)
end = int (endStr)
by = int(byStr)
# awesome solution
print range(start, end, by)
# actual solution
curr = start
while curr < end:
print curr
curr += by |
import pandas as pd
import numpy as np
return_dataset = pd.read_csv('processed_data/returns.csv')
np.random.seed(42)
# get the index from the df for 2018-01-01
i_2018 = return_dataset[return_dataset['Date']=='2018-01-01'].index[0]
return_all = return_dataset[['btc', 'eth', 'xrp']].to_numpy()
# total number of time poi... |
# -*- coding: utf-8 -*-
"""
// Copyright 2020 PDF Association, Inc. https://www.pdfa.org
//
// This material is based upon work supported by the Defense Advanced
// Research Projects Agency (DARPA) under Contract No. HR001119C0079.
// Any opinions, findings and conclusions or recommendations expressed
// in this materi... |
from datetime import datetime
class LogUtil:
def __init__(self, log_prefix):
self.prefix = log_prefix
def log(self, message):
print("{} {}: {}".format(datetime.now(), self.prefix, message)) |
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
N = int(input())
primes = prime_factorize(N)... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(columns=('Type', 'Ratio', 'Times', 'gid', 'k', 'Number of CPU Cores', 'Memory Constraints', 'Isolation Level', 'Lower Bound', 'Upper Bound'))
cores = [2, 3, 4, 5, 6]
mem = [1, 0.95, 0.9, 0.85, 0... |
# Variable
exampleString = "Hello World"
print(exampleString)
print(type(exampleString))
myName = "Chris Ritter"
myAge = 23
myBirthDay = "05/11/1997"
myIntro = f"Hello my name is {myName} and I am {myAge}. I was born on {myBirthDay}." #String Interpolation
print(myIntro)
#Lists
listOfDifferentTypes = [0,1.0, "Some ... |
import yaml
import random
import string
def GetZonesList(context):
zones = []
if context.properties['usEast1b']:
zones.append('us-east1-b')
if context.properties['usEast1c']:
zones.append('us-east1-c')
if context.properties['usEast1d']:
zones.append('us-east1-d')
if context.... |
#!C:\Users\Lee\AppData\Local\Programs\Python\Python38-32\python.exe
### Python AI Script
### Author: Lee Hughs
### Date: 2020/02/01
import sys
##initiate global variables/weights
p_weight = 1;
ep_weight = -1;
k_weight = 2;
ek_weight = -2;
class MoveTree:
def __init__(self, src):
self.moves = {
... |
"""Main product initializer
"""
from zope.i18nmessageid import MessageFactory
from ecreall.trashcan.events import ObjectTrashedEvent, ObjectRestoredEvent
from zope.event import notify
trashcanMessageFactory = MessageFactory('ecreall.trashcan')
from Products.PythonScripts.Utility import allow_module
allow_module('ecre... |
from shared.codejam_plumbing import GCJParsedInput, GCJOutputs
import re
_CodeJamRound = "2016.1B"
_Question = "A"
_AttemptNo = 1
_SmallLargeSample = 'large' # pick between 'sample', 'small' (requires attemptNo), 'large', 'practice'
assert _SmallLargeSample in ('sample', 'small', 'large', 'practice'), ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 02:12:27 2020
@author: dmin
"""
from urllib.request import urlretrieve
from ols_reg_function import *
# Import pandas
import pandas as pd
# Assign url of file: url
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv'
... |
"""
From the US Constitution
Amendment IX: The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others
retained by the people.
Algorithm: Checks if agent's actions hinder the process of a speedy public trial,
If this amendment is violated by the agent's actions:
ret... |
f =float(input('请输入华氏温度:'))
c =(f-32)/1.8
print (f'{f:.2f}华氏度= {c:.2f}摄氏度') |
"""
******************************************************************************
* Purpose: Write a program Calendar that takes the read month and year from user and prints the Calendar of the month.
*
* @author: Manjunath Mugali
* @version: 3.7
* @since: 21-01-2019
*
********************************************... |
import sys
num = int(sys.stdin.readline())
solutes = sorted(list(map(int, sys.stdin.readline().split()))[:num])
min_diff = (abs(solutes[0] + solutes[1]), solutes[0], solutes[1])
print(solutes)
def binary_search(idx, val):
start = idx + 1
end = len(solutes) - 1
while start < end:
mid = (start + e... |
import math
n=[int(i) for i in input().split()]
a=n[0]
b=n[1]
v=n[2]
print(math.ceil((v-a)/(a-b))+1)
|
import argparse
from typing import Any, List, Optional, Tuple, Union
# pyre-ignore
from data_generator.cli_parser import convert_args, parse_inputs, verify
from data_generator.generator import assemble_data_generators
from data_generator.output import to_csv, to_excel, to_json
from data_generator.toml import get_input... |
NUM_WRONG_GUESSES = 3
NUM_GOOD_GUESSES = 3
POINTS_PER_GOOD_GUESS = 2
POINTS_PER_WRONG_GUESS = -1
LETTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
NUMBERS = set("1234567890")
HOST = None
DB = "WikiTrivi_DB"
PAGE_COL... |
from django.shortcuts import render,redirect, get_object_or_404
from genre.models import UsersGenre
from .models import Explore, Playlist
from .forms import PlaylistForm
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def explore_view(request):
user= request.us... |
# -*- coding: utf-8 -*-
"""
file: gromacs_setup.py
Function for preparing input definitions for a GROMACS
Linear Interaction Energy MD calculation
"""
import os
import logging
import re
def correct_itp(topfile, topOutFn, posre=True, outitp={}, removeMols=[], replaceMols=[], excludePosre=[], excludeHH=[],
... |
"""
The lower_convex_hull module handles geometric calculations associated with
equilibrium calculation.
"""
from __future__ import print_function
from pycalphad.log import logger
from pycalphad.core.cartesian import cartesian
import numpy as np
# The energetic difference, in J/mol-atom, below which is considered 'zer... |
# coding=utf-8
__author__ = 'stefano'
import logging
from pprint import pprint
from optparse import make_option
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from openpyxl import load_workbook, Workbook
from django.core.management.base import BaseCommand
fr... |
from django.contrib import admin
from .models import Template, Webpage, Comment, Like
# Register your models here.
admin.site.register(Template)
admin.site.register(Webpage)
admin.site.register(Comment)
admin.site.register(Like)
|
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
pio.renderers.default = "browser"
from asset_research.utils import get_orderbook_df
def realtime_orderbook_heatmap(orderbook_df, code=None, ):
if code is not None:
orderbook_df = orderbook_df[orderbook_df['c... |
from django import forms
from account.models import AccountGroup
class EditForm(forms.Form):
name = forms.CharField(
max_length=16, required=True,
widget=forms.TextInput(attrs={'size': 16}))
info = forms.CharField(
max_length=64, required=False,
widget=forms.TextInput(attrs={'size'... |
#
# -*- coding: <utf-8> -*-
#
import urllib2
from lib.sonos.soco import SoCo
from lib.sonos.soco import SonosDiscovery
import lib.feedparser as feedparser
from core.Logger import log
sonos_devices = SonosDiscovery()
class Sonos:
def GetDeviceList(self):
info = {}
for ip in sonos_devices.get_speaker_ips():
... |
# -*- coding: utf-8 -*-
# cuadrics
from sage.all import matrix,var,vector,solve,det
"""Returns whether matrix m is symmetric (assuming it is square)"""
def symmetric(m):
for i in range(m.nrows()):
for j in range(i, m.ncols()):
if m[i][j] != m[j][i]:
return False
return True
... |
from django.contrib.auth.models import User
from django.test import TestCase
class TestListTweets(TestCase):
def setUp(self) -> None:
user = User.objects.create_user(username='user_test', email='test@gmail.com', password='2DF1SD2d2D2@D')
self.client.login(username='user_test', password='2DF1SD2d2D... |
#============================================
# Title: Assignment 9.2
# Author: Don Cousar
# Date: 29 June 2019
# Description: Querying and Creating Documents
#===========================================
# Imports
from pymongo import MongoClient
import pprint
import datetime
# Connect to local MongoDB
client = Mon... |
# utf-8
# PA
termo1 = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
termos = int(input('Digite quantos termos deseja ver: '))
res1 = 0
x = 0
while True:
while x < termos:
print(termo1, end='')
print(end=' → ' if x < termos -1 else print(end=' → PAUSA'))
ter... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
def doc_upload_url():
parts = (settings.DRIVER_APP_URL, '#', 'bookings')
return '/'.join(parts)
def car_listing_url():
parts = (settings.DRIVER_APP_URL, '#', 'listings')
return '/'.join(parts)
def car_... |
#This code organizes the individual output files for HFBTHOv300 into two separate files:
# 1. HFBTHOv300_"functional-name"_All_Data.dat (containing the data from every constrained calculation)
# 2. HFBTHOv300_"functional-name"_Ground_State_Data.dat (containing the ground state data for each nucleus from all of the co... |
import urllib2
from bs4 import BeautifulSoup
# Find and open the URL to scrape
url = 'http://ire.org/conferences/nicar-2014/schedule/'
html = urllib2.urlopen(url).read()
# Open an output file to put our scraper results
outfile = open('nicar_2014.csv', 'a')
# Use BeautifulSoup to extract the course/panel list
# from ... |
from abc import ABC
from modules import ModuleBase
import json
import traceback
from utils.log import init_logger
logger = init_logger(__name__)
class ParseDataModule(ModuleBase, ABC):
def __init__(self):
super(ParseDataModule, self).__init__()
self.script = ""
def init_custom_variables(self... |
from gluoncv import model_zoo
from mxnet.gluon import nn, HybridBlock
from mxnet import init
import mxnet as mx
class fashion_net_2_branches(HybridBlock):
def __init__(self, num_clothes, num_colors, ctx):
super(fashion_net_2_branches, self).__init__()
self._features = model_zoo.get_model('mobilene... |
# Question
# Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity.
# The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
# Now you want to find out who the celebrity is or verify that there is not... |
import datetime
import json
import logging
import webapp2
from google.appengine.api.app_identity import app_identity
from src.commons.config.configuration import configuration
from src.datastore_export.export_datastore_to_big_query_service import \
ExportDatastoreToBigQueryService
class ExportDatastoreToBigQuer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.