content stringlengths 7 1.05M |
|---|
class TIFFImageCropperTest(object):
"""
Test Suite for TIFFImageCropper.
"""
pass |
dataset=["gossipcop_fake" "gossipcop_real" "politifact_fake" "politifact_real" "Aminer"]
methods=["proposed" "HITS" "CoHITS" "BGRM" "BiRank"]
|
# -*- coding: utf-8 -*-
##############################################################################
#Author:QQ173782910
##############################################################################
CLIENT_NAME = 'wrobot'#注意:这个是项目名
DEBUG='1'
L_no=['newscontent','text_contents']#不判断副文本
|
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 2:
return [nums]
def order(prefix, suffix):
if len(suffix) == 1:
return [prefix+suffix]
results =... |
'''
https://docs.python.org/3/reference/datamodel.html#object.__getitem__
'''
class XXX(object):
def __init__(self):
self.data = {int(i): str(i) for i in range(3)}
def __len__(self):
return len(self.data)
def __getitem__(self, index):
if index >= len(self): raise IndexError
r... |
# Exercice 2.2 : Calcul des mentions (corrigé)
## Question 1
def mention(note : float) -> str:
"""Précondition : (note>=0) and (note<=20)
Retourne la mention correspondant à la note spécifiée.
"""
if note < 10:
return 'Eliminé'
elif note < 12:
return 'Passable'
elif note < 14:... |
def search(list, key):
pos = -1
for i in range(0,len(list)):
if list[i] == key:
pos = i + 1
break
if pos != -1:
print("\n\nThe value {} is found to be at {} position!".format(key,pos))
else:
print("\n\nThe value {} cannot be found!".format(key))
print("\nEnter the elements of ... |
def diagonalDifference(arr, n):
mtotal = 0
stotal = 0
for i in range(n):
mtotal += arr[i][i]
stotal += arr[n - 1 - i][i]
return abs(mtotal - stotal)
n = int(input())
arr = [
list(map(int, input().split())) for _ in range(n)
]
print(diagonalDifference(arr, n))
|
first_name = "Hannah"
last_name = "Louisa"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.upper()}")
message = f"Howdy, {full_name.title()}"
print(message)
|
#
# PySNMP MIB module DOCS-MCAST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-MCAST-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:38:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# -*- coding: utf-8 -*-
DESC = "ame-2019-09-16"
INFO = {
"DescribeItems": {
"params": [
{
"name": "Offset",
"desc": "offset (Default = 0),(当前页-1) * Limit"
},
{
"name": "Limit",
"desc": "条数,必须大于0,最大值为30"
},
{
"name": "CategoryId",
"desc"... |
def square(x):
return x*x
print(type(square))
print(id(square))
print(str(square)) |
#
# PySNMP MIB module CISCO-VOICE-ATM-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-ATM-DIAL-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:19:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
"""
DESAFIO 087: Mais Sobre Matriz em Python
Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
0 [_][_][_]
1 [_][_][_]
2 [_][_][_]
0 1 2
"""
matriz = [
[],
[],
[]
]
pares = ter... |
def visualization():
"""Extract final adjust process values from BHDS tables.
Args:
pri_df {pyspark.sql.dataframe.DataFrame} -- Primary BHDS data
Returns:
[pyspark.sql.dataframe.DataFrame] -- Dataframe with features.
"""
print('visualizing data....')
|
def quote(msg: str):
return msg.replace("`", "")
def cleanup_code(content):
if content.startswith("```") and content.endswith("```"):
output = content[3:-3].rstrip("\n").lstrip("\n")
return output
return content.strip("` \n") |
# Reading and Writing Plain Text Files
print("""Steps to reading and writing text files in Python:
Open
1. open() function: open's the file
helloFile = open('<file name.txt>')
helloFile.read()
helloFile.close()
Read
2. readlines() method: returns all of the lines as strings inside of a list.
helloFile ... |
# Joe defined a dictionary listing his favorite artists, their albums,
# and the song from each of the albums. It looks as follows:
#tracks = {"Woodkid": {"The Golden Age": "Run Boy Run",
# "On the Other Side": "Samara"},
# "Cure": {"Disintegration": "Lovesong",
# "Wish":... |
# Challenge Link - https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
# My Results - https://app.codility.com/demo/results/trainingFGAZZW-5XB/
def solution(A, K):
# write your code in Python 3.6
if not A:
return []
idx = [i for i in range(0, len(A))]
while K:
idx = [... |
class Account:
resource = 'accounts'
def __init__(self, requestor):
self.requestor = requestor
def retrieve(self):
return self.requestor.request('GET', '{}'.format(self.resource))
|
class Mapper:
"""This module takes a user-input string and chunks it into formatted tuples which
contains relevant data for all essential pieces of string."""
def maptolist(self, arg, langbound):
"""Returns formatted-tuple containing relevant processing data for each token.""" #update
ret... |
_base_ = 'resnet50_head1_4xb64-steplr1e-1-20e_in1k-10pct.py'
# optimizer
optimizer = dict(lr=0.01)
|
#!/usr/bin/env python3
class Text:
"""A probably unnecessary wrapper for a \\n-delimited block of text."""
def __init__(self, raw_text:str):
self.raw_text = raw_text
self.lines = [l.strip() for l in raw_text.split("\n")]
def get_block(self, start, length):
return self.lines[start:... |
#!/usr/bin/env python3
'''
Cкрипт принимает x1, x2, y_upped, y_bottom, x_start, y_start, x_end, y_end
предполагается, что линия движения лежит вдоль парковок
предполагается, что парковочные места друг с другом соеденены
Скрипт будет возвращать текстовый файл parking_points.txt с кординатами
необхо... |
N, K = map(int, input().split())
a_list = list(map(int, input().split()))
point = [[0] * 2 for _ in range(40)]
for i in range(40):
tmp = 0
for a in a_list:
if (a >> (39 - i)) & 1:
tmp += 1
# 上位からiビット目が 0 のときに得られる値
point[i][0] = tmp * 2 ** (39 - i)
# 上位からiビット目が 1 のときに得られる値
p... |
# -*- coding: utf-8 -*-
def search(key, arr):
return list(filter(lambda n: n[0] == key, arr))
def main():
arr = [[100, 2], [300, 3], [500, 4], [800, 5], [200, 6]]
inp_id = 200
ret = search(inp_id, arr)
print(ret)
if len(ret) > 0:
print("ok")
else:
print("Error")
if __name... |
file = open("BoyNames.txt", "r")
data = file.read()
boys_names = data.split('\n')
file = open("GirlNames.txt", "r")
data = file.read()
girls_names = data.split('\n')
file.close()
choice = input("Enter 'boy', 'girl', or 'both':")
if choice == "boy":
name = input("Enter a boy's name:")
if name in boys_names:
print... |
a = int(input())
for _ in range(a):
x = input()
y = x[::-1]
counter = 0
while x != y or not counter:
x = str(int(x) + int(y))
y = x[::-1]
counter += 1
print(counter, x)
|
# ------------------------------
# 81. Search in Rotated Sorted Array II
#
# Description:
# Follow up for "Search in Rotated Sorted Array":
# What if duplicates are allowed?
#
# Would this affect the run-time complexity? How and why?
#
# Suppose an array sorted in ascending order is rotated at some pivot unknown to ... |
#!/usr/bin/env python3
# coding: utf-8
class K8sResponseHelper(object):
LOCATION_NOT_DEFINE = "NOT_DEFINE"
NGINX_INGRESS_SUFFIX = "nginx-ingress-controller"
def __init__(self):
self.input_data_list = None
def set_input_data_list(self, input_data_list):
"""
:return: K8sRespon... |
# Input.
s = '367436765224262147416876392821832169781285655941123648172835986213848397566284241467793119283183835972359686446876651595915734132336167171121577524691918457577129283476247264385162111539468922414495231484194262592917889386218863347344978231632813893898536759322467341535638612338949526576258684154323161554... |
try:
a = int(input("Primeiro numero: "))
b = int(input("Segundo numero: "))
r = a / b
except Exception as erro:
print("Problema encontrado foi {}".format(erro.__class__))
else:
print("O resultado e {:.1f}".format(r))
finally:
print("Volte Sempre! Muito Obrigado :)")
|
# Isaac Roberts
# Imports
# Functions
# Main execution of the program.
def main():
# Open provided CSV file
f = open("Python/airport-project/Airports.txt", 'r')
# Define list to store seperated CSV file in.
airports_list = []
# Loop through file and split each line into seperate lists.
for ... |
class settings:
def init():
global baseURL
global password
global username
global usertestingpassword
global usertestingemail
global twilliotemplate |
#
# PySNMP MIB module NETONIX-SWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETONIX-SWITCH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:19:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
###checks to see which elements in array1, a1, are substrings of elements in array2, a2###
###returns sorted array of these elements###
def in_array(a1, a2):
inArray = set()
for i in a1:
for x in a2:
if i in x:
inArray.add(i)
return sorted(inArray)
|
#Desafio10
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
#e mostre quantos dólares ela pode comprar
#Considere US$1,00 = R$3,27
rs=float(input('Quanto dinheiro você tem na carteira?: R$ '))
dolar = rs/3.27
print('Com R${:.2f} você pode comprar US${:.2f}'.format(rs,dolar))
|
AI_TYPE_TO_ROLE = {"redis_ycsb": ("ycsb", "redis"), "hadoop": ("hadoopmaster", "hadoopslave"),
"linpack": ("linpack",), "wrk": ("wrk", "apache"), "filebench": ("filebench",),
"sysbench": ("sysbench", "mysql"),
#"unixbench": ("unixbench",), "netperf": ("netclient"... |
def permutation(input_list):
if len(input_list) == 0:
return []
elif len(input_list) == 1:
return [input_list]
else:
result = []
for i in range(len(input_list)):
element = input_list[i]
other_elements = input_list[:i] + input_list[i + 1:]
f... |
def cut_log(p, n):
maximum=[0]
for j in range(1, n+1):
comp=-float("inf")
for i in range(1, j+1): # Two nested loops = Θ(n^2)
comp=max(p[i-1+1]+maximum[j-i], comp)
maximum.append(comp)
return maximum[-1] |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
... |
"""
[12/03/13] Challenge #143 [Easy] Braille
https://www.reddit.com/r/dailyprogrammer/comments/1s061q/120313_challenge_143_easy_braille/
# [](#EasyIcon) *(Easy)*: Braille
[Braille](http://en.wikipedia.org/wiki/Braille) is a writing system based on a series of raised / lowered bumps on a
material, for the purpose of b... |
"""
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D again, go full D.
Difference between tft... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
REAL_FLAG = "oren_ctf_spectre!"
FAKE_FLAG = "oren_ctf_z3r0d4y!"
license = [chr(ord(c1) ^ ord(c2)) for c1,c2 in zip(REAL_FLAG, FAKE_FLAG)]
with open('license.bin', 'wb') as licensefile:
for byte in license:
licensefile.writ... |
class OUTGOING:
TOKEN = 'token'
TEAM_ID = 'team_id'
TEAM_DOMAIN = 'team_domain'
CHANNEL_ID = 'channel_id'
CHANNEL_NAME = 'channel_name'
TIMESTAMP = 'timestamp'
USER_ID = 'user_id'
USER_NAME = 'user_name'
TEXT = 'text'
TRIGGER_WORD = 'trigger_word'
class INCOMING:
USER_NAME ... |
ODL_IP = "127.0.0.1"
ODL_PORT = "8181"
ODL_USER = "admin"
ODL_PASS = "admin"
|
def arithmetic_arranger(problems, solutions = False):
if len(problems) > 5:
return 'Error: Too many problems.'
problem_list = []
for prob in problems:
output = ''
arr = prob.split(' ')
if arr[1] != '+' or arr[1] != '+':
return "Error: Operator must be '+' or '-'."
if arr[0].isdig... |
_, ax = plt.subplots(figsize=(8, 8))
ax = sns.kdeplot(
data=X_train_scaled,
x="Culmen Length (mm)",
y="Culmen Depth (mm)",
levels=10,
fill=True,
cmap=plt.cm.viridis,
ax=ax,
)
_ = ax.axis("square")
|
def doiList():
return [
"10.1016/j.jksuci.2019.05.004", # ScienceDirect good example
"10.1016/j.eswa.2019.04.070"
]
|
class IPGroup():
def __init__(self, key, packet_count, total_packet_size, process_number):
self.packet_count = packet_count
self.total_packet_size = total_packet_size
self.process_number = process_number
self.groupname = key
@property
def averagePacketSize(self):
ret... |
# Specifies the login method to use -- whether the user logs in by entering
# his username, e-mail address, or either one of both. Possible values
# are 'username' | 'email' | 'username_email'
# ACCOUNT_AUTHENTICATION_METHOD
# The URL to redirect to after a successful e-mail confirmation, in case no
# user is logged i... |
'''
A Popular Strategy Using Autocorrelation
One puzzling anomaly with stocks is that investors tend to overreact to news. Following large jumps, either up or down, stock prices tend to reverse. This is described as mean reversion in stock prices: prices tend to bounce back, or revert, towards previous levels after la... |
# Colors
blue = '#377EB8'
red = '#E41A1C'
green = '#4DAF4A'
|
# ------------------------------
# 228. Summary Ranges
#
# Description:
# Given a sorted integer array without duplicates, return the summary of its ranges.
#
# Example 1:
# Input: [0,1,2,4,5,7]
# Output: ["0->2","4->5","7"]
# Example 2:
# Input: [0,2,3,4,6,8,9]
# Output: ["0","2->4","6","8->9"]
#
# Version: 1.0
# 1... |
class ConfigClass:
def __init__(self):
# link to a zip file in google drive with your pretrained model
self._model_url = "https://drive.google.com/file/d/14VduVhV12k1mgLJMJ0WMhtRlFqwqMKtN/view?usp=sharing"
# False/True flag indicating whether the testing system will download
# ... |
'''4. Write a Python program to add two positive integers without using the '+' operator.
Note: Use bit wise operations to add two numbers.'''
num1 = 4
num2 = 34
num3 = num1.__add__(num2)
print(num3) |
__copyright__ = "Copyright 2019, RISE Research Institutes of Sweden"
__author__ = "Naveed Anwar Bhatti and Martina Brachmann"
def maprange(a, b, s):
'''
Maps an input value to an ouput value depending on a sensors' and actuators's range
Parameters
----------
a : tupel (float, float)
the s... |
class Card:
def __init__(self,rank,suit): # instance recevies two parameters rank and suit
self.rank = rank
self.suit = suit
self.rank_list = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] # a list contains all ranks
self.suit_list = ['H', 'C', 'D', 'S'] # a list c... |
n = 1
while True:
num = int(input(f"Enter value{n}: "))
if num == -99:
break
n += 1
print(f"You entered {n-1} numbers.") |
while True:
n = int(input())
if n == -1:
break
last_elapsed = 0
distance = 0
for _ in range(n):
s, t = map(int, input().split())
_t = t - last_elapsed
distance += s * _t
last_elapsed = t
print(distance, "miles")
|
POSTGRES_DATA_TYPES = {
"int2": "smallint",
"integer": "integer",
"uuid": "uuid",
"string": "varchar",
"timestamp": "timestamp",
}
|
def rotLeft(a, d):
for x in range(d):
temp = a[0]
a.pop(0)
a.append(temp)
return a
no_of_inputs = 5
no_of_rotation = 4
my_str = "1 2 3 4 5"
my_arr = [s for s in my_str.strip().split()]
print(rotLeft(my_arr, no_of_rotation))
|
"""
问题描述:给定两个字符串str和match,长度分别为M和N,实现一个算法,如果字符串str
中含有子串match,则返回match在str中的开始位置,不含有则返回-1
要求:
算法时间复杂度为O(N)
"""
class KMP:
@classmethod
def get_index(cls, search_str, match):
if not search_str or not match or len(search_str) < len(match):
return -1
index = 0
mindex = 0
... |
# We have tossed a coin a 6 times and saved the results in a list
# called heads_or_tails. The values are integers: 1 stands for a
# head, while 0 denotes a tail.
# Add some code to find out whether the list has any heads. Do
# not print the variable check, just store the result in it.
# Fingers crossed
check = any(h... |
A, B, C = list(map(int, input().split()))
if C <= B:
print('-1')
else:
print(int(A / (C-B) + 1))
|
'''
Intuition
----
Intuition is an engine, some building bricks and a set of tools meant to let
you efficiently and intuitively make your own automated quantitative trading
system. It is designed to let traders, developers and scientists explore,
improve and deploy market technical hacks.
:copyright (c)... |
"""jotter
The main functionality of jotter, including CLI and other modules.
Author:
Figglewatts <me@figglewatts.co.uk>
"""
__version__ = "0.1.3" |
#assignment2 homework1
student1=input("Enter student name1:")
student2=input("Enter student name2:")
student3=input("Enter student name3:")
print("Student1 Name is:"+student1+"\n"+"Student2 Name is:"+student2+"\n"+"Student3 Name is:"+student3)
#assignment2 homework2
def function1():
print("Function1 output:",ag... |
"""
26 / 26 test cases passed.
Runtime: 36 ms
Memory Usage: 15 MB
"""
class Solution:
def lengthLongestPath(self, input: str) -> int:
ans = 0
level_depth = {-1: 0}
for path in input.split('\n'):
depth = path.count('\t')
level_depth[depth] = level_depth[depth - 1] + le... |
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
sign = 1 if (dividend >= 0) == (divisor >= 0) else -1
dd = abs(dividend)
dr = abs(divisor)
if dd < dr:
return 0
... |
class LimitedStack:
def __init__ (self,max_size=200):
self.stack = []
self.max_size = max_size
def add (self,item=None):
self.stack.append(item)
if len(self.stack) > self.max_size:
self.stack = self.stack[1:]
def get (self):
... |
"""Top-level package for spotibox."""
__author__ = """Martin Hanewald"""
__email__ = 'martin.hanewald@gmail.com'
__version__ = '0.2.0'
|
class Config(object):
env = 'default'
backbone = 'resnet18'
classify = 'softmax'
num_classes = 5000
metric = 'arc_margin'
easy_margin = False
use_se = False
loss = 'focal_loss'
display = False
finetune = False
meta_train = '/preprocessed/train_meta.csv'
train_root = '/p... |
"""Exception hierarchy for the zeekscript package."""
class Error(Exception):
"""Base class for all zeekscript errors."""
class FileError(Error):
"""System errors while processing script files"""
class ParserError(Error):
"""A hard parsing error, producing no parse tree."""
|
'''
Flip
https://www.interviewbit.com/problems/flip/
Asked in: VMWare
You are given a binary string(i.e. with characters 0 and 1) S consisting of characters S1, S2, …, SN.
In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters SL, SL+1, …, SR. By flipping,
we mean ... |
#ler varios nr inteiros, até digitarem 999
#mostrar a soma e a quantidade dos nrs digitados
soma = contagem = 0
maior = menor = 0
while True:
numero = int(input("Digite um nr (ou 999 para sair): "))
if numero == 999:
break
if contagem == 0:
menor = numero
if numero > maior:
maior = numero
if numero < menor:... |
#
# PySNMP MIB module ENTERASYS-POWER-ETHERNET-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-POWER-ETHERNET-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
""" version which can be consumed from within the module """
VERSION_STR = "0.0.11"
DESCRIPTION = "module to help you tag interesting places in your code"
APP_NAME = "pytags"
LOGGER_NAME = "pytags"
|
# vim: fdm=indent
'''
author: Fabio Zanini
date: 31/08/15
content: Module that contains fast conversion factories between private and
anonymyzed versions of data.
Such a module is useful during research development, when consensus
on anonymized patient/sample names has ... |
def get_index(word):
while True:
try:
pos = int(input("Enter an index: "))
if pos == -1:
return pos
elif pos >= len(word):
print("invalid index")
elif pos <= -1:
print("invalid index")
els... |
"""
a) Создать список, состоящий из кубов нечётных чисел от 1 до 1000 (куб X - третья степень числа X):
Вычислить сумму тех чисел из этого списка, сумма цифр которых делится нацело на 7.
Например, число `19 ^ 3 = 6859` будем включать в сумму, так как `6 + 8 + 5 + 9 = 28` – делится нацело на `7`.
Внимание: использоват... |
"""
lists
"""
myUniqueList = []
myLeftovers = []
def addToList(animal):
if animal in myUniqueList:
addToLeftovers(animal)
return False
else:
myUniqueList.append(animal)
return True
def addToLeftovers(animal):
myLeftovers.append(animal)
# Test the addToList function
p... |
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x) |
# package information.
INFO = dict(
name = "latexutils",
description = "Utils for making Latex documents",
author = "Daisuke Kataoka",
author_email = "daisuke.1221.canoe@gmail.com",
url = "https://github.com/dai39suke/latexutils",
classifiers = [
"Programming Language :: Python :: 3.... |
## (y - y1) / (x - x1) = (y2 - y1) / (x2 - x1)
y = lambda x, x1, x2, y1, y2: y1 + (y2-y1) / (x2-x1) * (x-x1)
def interpolation(xp, X, Y):
if xp < X[0]:
print("Given x-value is out of range")
return None
for i, Xi in enumerate(X):
if xp < Xi:
return y(xp, X[i-1], X[i], Y[i-1... |
'''
Let us say your expense for every month are listed below,
January - 2200
February - 2350
March - 2600
April - 2130
May - 2190
Create a list to store these monthly expenses and using that find out,
1. In Feb, how many dollars you spent extra compare to January?
2. Find out your total expense in first quarter (first... |
num = int(input('Informe um número: ')).strip()
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print('Analisando o número {}'.format(num))
print('minhar: {}'.format(m))
print('centena: {}'.format(c))
print('dezena: {}'.format(d))
print('unidade: {}'.format(u)) |
# Course: CS 30
# Period: 1
# Date created: 2020/02/12
# Date last modified: 2020/03/11
# Name: Kate Pepper
# Desrcription: A set of lists for a Clue RPG
"""A list of all of the suspects of the murder"""
# Original suspect list
suspects = ['Evelyn Finch', 'George Brown', 'Madeline Brown', 'Stephen Turner']
p... |
#!/usr/bin/python3
#kanto kor pirka nociw AI system
#data.py:各種データやログなどを記録
#一度しかないこの人生で、自分の夢を追いかけないでいつ追いかけるのだろう。-孫正義
#©2019 Mamoru Itoi
#会話ログ
class Log:
pass
#入力応答用辞書「kanto」
class Kanto:
#バージョン
version = "α0.0"
class Learn:
#バージョン
version = "α0.0"
#感情変動用辞書「nociw」
class Nociw:
#バージョン
version = "α0.0"
cl... |
def selected_cols(largeset = False, parties=True, pnroalue = True):
if largeset==True:
numeric_features = ['Miehet, 2018 (HE) osuudesta asukkaat',
'Naiset, 2018 (HE) osuudesta asukkaat',
'Asuntojen keskipinta-ala, 2018 (RA) osuus total',
... |
"""7. 使用round(x, y)函数,可以将浮点数x保留y位小数。
使用键盘,输入两个非零数,求这两个数的商,结果保留两位小数。
输出的时候,请注意使用“➗”(十进制Unicode编码:10135)作为连接符表示除号。"""
num1 = float(input("请输入第一个数:"))
num2 = float(input("请输入第二个数:"))
num3 = num1 / num2
num3 = round(num3, 2)
print(str(num1) + chr(10135) + str(num2) + "=" + str(num3))
|
class Solution:
def shortestWordDistance(self, words: 'List[str]', word1: 'str', word2: 'str') -> 'int':
i1 = i2 = -1
ans = math.inf
equal = word1 == word2
for i, word in enumerate(words):
if word == word1:
i1 = i
if word == word2:
... |
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
def dirToIndex(x, y, d):
if d == "r": return (x, y + 1, d) if y + 1 < n and matrix[x][y + 1] == 0 else (x + 1, y, "d")
elif d == "d": return (x + 1, y, d) if x + ... |
f = open("HaltestellenVVS_simplified_utf8.csv", "r")
r = open("HaltestellenVVS_simplified_utf8_stationID.csv", "w")
r.write(f.readline())
lines = f.readlines()
for line in lines:
stationID = line.split(",")[0]
newStationID = int(stationID)+5000000
outLine = str(newStationID) + line[len(stationID):]
r.write(outL... |
# По закону Ома U = IR (напряжение равно произведению силы тока на сопротивление). Определите U (напряжение), если
# I = 102341132412344234, R = 9876387639476324727.
print(102341132412344234 * 9876387639476324727)
|
name = QInputDialog.getText(self, "Name", "Enter the name of your sidebar here:")
if name[1]:
name = name[0]
url = QInputDialog.getText(self, "URL", "Enter the URL of your sidebar here:")
if url[1]:
url = url[0]
common.sidebar_maker_path = os.path.join(settings.extensions_folder, name.lower(... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
vals = []
if not roo... |
def quicksorted(L):
#base case
if len(L) < 2:
return L[:]
# Divide!
pivot = L[-1]
LT = [e for e in L if e < pivot]
ET = [e for e in L if e == pivot]
GT = [e for e in L if e > pivot]
# Conquer
A = quicksorted(LT)
B = quicksorted(GT)
# Combine
return A + ET + B
... |
"""
WGS84 constants
Reference:
Paul Groves
http://www.oosa.unvienna.org/pdf/icg/2012/template/WGS_84.pdf
"""
R0 = 6378137.0
f = 298.257223563
omega_E = 7.2921151467e-5
GM = 3.986005e14
ecc = 0.0818191908425
Rp = 6356752.314245 |
# Parsed from https://www.ibm.com/docs/en/spectrum-lsf/10.1.0?topic=options-o
bjobs_fields = [
{"name": "jobid", "width": 7, "aliases": "id", "unit": None},
{"name": "jobindex", "width": 8, "aliases": None, "unit": None},
{"name": "stat", "width": 5, "aliases": None, "unit": None},
{"name": "user", "wid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.