content stringlengths 7 1.05M |
|---|
FLAG_ALPHA_FEATURES_NAME = "alpha_features"
FLAG_ON_DEMAND_TRANSFORM_NAME = "on_demand_transforms"
FLAG_PYTHON_FEATURE_SERVER_NAME = "python_feature_server"
ENV_FLAG_IS_TEST = "IS_TEST"
FLAG_NAMES = {
FLAG_ALPHA_FEATURES_NAME,
FLAG_ON_DEMAND_TRANSFORM_NAME,
FLAG_PYTHON_FEATURE_SERVER_NAME,
}
|
PROXY = '' # 127.0.0.1:8123 for example
FEEDS = [
'http://www.heise.de/newsticker/heise-atom.xml',
'http://golem.de.dynamic.feedsportal.com/pf/578068/http://rss.golem.de/rss.php?feed=RSS2.0',
'https://news.ycombinator.com/rss',
]
|
entries = [
{
"env-title": "atari-alien",
"env-variant": "No-op start",
"score": 15962.10,
},
{
"env-title": "atari-amidar",
"env-variant": "No-op start",
"score": 1554.79,
},
{
"env-title": "atari-assault",
"env-variant": "No-op start"... |
# Question 9: Write a program that asks the user for an integer and creates a list that consists of the factors
# (divisors) of that integer.
num = int(input("enter a number"))
L = []
for i in range(num):
if i %num ==0:
L.append(i)
print(L) |
class ConstLanguage():
"""class for storing all const Language"""
MENU_RIG = 10
MENU_RIG_NEW = 11
MENU_RIG_REFRESH = 12
MENU_RIG_RENAME = 13
MENU_RIG_DELETE_CURRENT = 14
MENU_RIG_DELETE_ALL = 15
MENU_RIG_CHANGE_FOLDER = 16
MENU_RIG_OPTIONS = 20
MENU_RIG_OPTIONS_IMPORT = 21
... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... |
def quicksort(l):
if l:
left = [x for x in l if x < l[0]]
right = [x for x in l if x > l[0]]
if len(left) > 1:
left = quicksort(left)
if len(right) > 1:
right = quicksort(right)
return left + [l[0]] * l.count(l[0]) + right
return []
def q... |
#this file should contain all the sample date, location, concentration, species information for samples wanting to
#be included in the HYCOM model runs
#common locations:
#IFCB in Port Aransas, TX: -97.0318, 27.8304
#South Padre Island, TX: -97.05, 26.078
#Galveston, TX: -94.66, 29.28
#I'm having to add a fifth eleme... |
#!/usr/bin/env python
# Beginning of Chinese Range: 11904 (traditional), 19968 (simplified?)
for i in range(1, 100000):
s = '\\u%04x'%(i,)
print(' ', chr(i), ' ', i, s)
|
'''
https://leetcode.com/contest/weekly-contest-175/problems/maximum-students-taking-exam/
'''
class Solution:
def maxStudents(self, seats: List[List[str]]) -> int:
n, m = len(seats), len(seats[0])
rows = []
for r in seats:
br = 0
for s in r:
... |
# class Solution(object):
# def generateParenthesis(self, N):
# ans = []
# def backtrack(S = '', left = 0, right = 0):
# if len(S) == 2 * N:
# ans.append(S)
# # print(ans)
# return
# # print(left, right)
# # 下面这两个if有... |
# Animal class
class Animal(object):
"""
preceding variable with __ makes them private that means
if we want to use them we first need to create a function in this class
"""
__name = ""
__height = 0
__weight = 0
__sound = 0
# constructor
def __init__(self, name, height, weight,... |
set_name(0x80137B7C, "EA_cd_seek", SN_NOWARN)
set_name(0x80137BA4, "MY_CdGetSector", SN_NOWARN)
set_name(0x80137BD8, "init_cdstream", SN_NOWARN)
set_name(0x80137BE8, "flush_cdstream", SN_NOWARN)
set_name(0x80137C0C, "check_complete_frame", SN_NOWARN)
set_name(0x80137C8C, "reset_cdstream", SN_NOWARN)
set_name(0x80137CB4... |
# Copyright 2021 Cory Paik. 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 applicable law or ag... |
coins = [1, 2, 5, 10, 20, 50, 100, 200]
amount = 200
ways = [0] * (amount + 1)
ways[0] = 1
for coin in coins:
for n in range(coin, amount + 1):
ways[n] += ways[n - coin]
print(ways[amount])
|
# Simple read() method around a bytearray
class BytesBuffer():
def __init__(self, b):
self.buf = b
self.readCount = 0
def count(self):
return self.readCount
def reset_count(self):
self.readCount = 0
def size(self):
return len(self.buf)
def peek(self):
... |
# Schemas corresponding to Myrial examples
{
'public:adhoc:sp2bench' : [('subject', 'STRING_TYPE'), ('predicate','STRING_TYPE'), ('object','STRING_TYPE')],
}
|
# Python function to find a range of primes
def findprimes(min, max):
for Number in range(min, max + 1):
count = 0
for i in range(2, (Number // 2 + 1)):
if (Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
prin... |
"""
Enunciado
Reto 4: Detectando copia en los exámenes de programación:
Uno de los profesores de programación de la Universidad Sergio Arboleda
está comenzando a perder su memoria. Hace algún tiempo, cuando comenzó
a trabajar como docente, no únicamente conocía perfectamente todos los nombres
y apelli... |
{
"targets": [
{
"target_name": "mozporter",
"type": "shared_library",
"sources": [
"vendor/Normalize.c",
"vendor/fts3_porter.c",
"vendor/rank.m"
],
'dependencies': ["./node_modules/better-sqlite3/deps/sqlite3.gyp:sqlite3"],
'cflags': [
'-std=c99... |
b=int(input())#bot's answer
a=int(input())#student's answer
if (b == 1 and b!=a) or (a==1 and a!=b):
print("NO")
if (a != 1 and b != 1) or (b==1 and a==1):
print("YES") |
"""
Marker class to allow registrations, DI, and type hinting for
subclasses.
"""
class Adapter:
""" Marker adapter all adapters are expected to subclass from """
pass
|
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2021
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2022/1/10 1:51 下午'
class TestHyperLogLog:
def test_pfadd(self, master, slave):
master.pfadd("HLL:K1", "V1", "V2", "V1", "V2")
master.pfadd("-HLL:K2",... |
def pluralize(num,word):
if num == 1:
print("1 {}".format(word))
else:
plural = ""
if word[-2:] == "fe":
plural = word[:-2] + "ves"
elif word[-2:] == "ey" or word[-2:] == "ay" or word[-2:] == "uy" or word[-2:] == "oy":
plural = word + "s"
elif word... |
"""
File: exercise_4.5.py
Author: William Gatharia
This code demonstrates reading text from a text file.
"""
file_name = input("Enter file to read:")
file = open(file_name, 'r')
while True:
line = file.readline()
if line == "":
break
print(line.strip())
|
"""
..module: Generator - help to guess the riddled number
- the basis to play "Bools&Cows" with computer
..author: Sergey Sumburov <sumburovsn@gmail.com>
"""
# trialLog dictionary keeps all the responses of the current session of the game
# in form "attempt: response"
game_log = {
'81... |
__author__ = "Robert Kist"
# QLineEdit
lineedit_style = '''
QLineEdit {
background: palette(dark);
border-radius: 5px;
height: 22px;
min-height: 22px;
max-height: 22px;
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
border: 2px solid transparent;
}
Q... |
# --------------------------
# UFSC - CTC - INE - INE5603
# Exercício do Navio
# --------------------------
# Classe que permite mostra na tela os dados de um navio.
#
class PainelMostraNavio:
def mostre(self, navio):
pt = navio.peso_transportado()
pm = navio.peso_maximo()
perc_t = (pt / p... |
"""Setup script for CWLite/1200 with XMEGA (CW303/CW308-XMEGA/CWLite target)
Configures scope settings to prepare for capturing SimpleSerial power traces
"""
# GUI compatibility
try:
scope = self.scope
except NameError:
pass
scope.gain.gain = 45
scope.adc.samples = 25000
scope.adc.offset = 0
scope.adc.ba... |
# --------------
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {... |
def assert_browsing_context(info, children, context, url, parent=None):
assert "children" in info
if children is not None:
assert isinstance(info["children"], list)
assert info["children"] == children
assert "context" in info
assert isinstance(info["context"], str)
# TODO: Always check ... |
#__________________ Script Python - versão 3.8 _____________________#
# Autor |> Abraão A.da Silva
# Data |> 06 de Março de 2021
# Paradigma |> Procedural
# Objetivo |> Desenvolver um conversor de médidas inteligente
#___________________________________________________________________#
"Este módulo armazena o cód... |
# -*- coding: utf-8 -*-
def pi(N=2**7):
pi = 0
for n in range(0, N + 1):
pi += 1 / (16**n) * (4 / (8 * n + 1) - 2 / (8 * n + 4) -
1 / (8 * n + 5) - 1 / (8 * n + 6))
return pi
|
# You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically cont... |
#Config
MYSQL_HOST = 'dockerMysql'
MYSQL_PORT = 3306
MYSQL_USER = 'ssuser'
MYSQL_PASS = 'sspasswd'
MYSQL_DB = 'sspanel'
MANAGE_PASS = 'ss233333333'
#if you want manage in other server you should set this value to global ip
MANAGE_BIND_IP = '127.0.0.1'
#make sure this port is idle
MANAGE_PORT = 23333
|
'''
Sum of number from 1 to n
return 1 + 2 + 3 + 4 + .... + (n-1) + n
'''
# # TRUST the function
# def sum_n(n):
# if(n == 1): # Or base case could be 0 --> return 0
# return 1
# left_part = sum_n(n-1)
# print(f"Left Part is {left_part}")
# return left_part + n
'''
Sum of Digit of th... |
"""
cloudscheduler is a module that contains various cloud connection classes for
starting virtual machines in the cloud in conjuction with HTCondor to assemble
a distributed computing resource for batch jobs.
"""
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Universidad Nacional Autonoma de Mexico / Facultad de Ingenieria
# Inteligencia Artificial
# Alumnos:
# Almazán García Giovanni
# Barriga Martínez Diego Alberto
# Bustamante Carrera Manuel Alejandro
# Juárez Pascual Karla Vanessa
# Hecho en Python 3.5
def tabla(letras):
... |
if __name__ == '__main__':
print('Eu sou a main')
else:
print('Sou só um módulo')
|
# program globals #
initLoadDir = "" # should be something like initLoadDir = <get dir from program state save file>
initSaveDir = "" # should be something like initSaveDir = <get dir from program state save file>
initVidFmt = ""
initAudFmt = ""
def updateUserData(loadDir="./", saveDir="./", vidFmt=None, audFmt=Non... |
# O(n^2) time | O(1) space
def selectionSort(array):
currentIdx = 0
while currentIdx < len(array) -1:
smallestIdx = currentIdx
for i in range(currentIdx + 1, len(array)):
if array[smallestIdx] > array[i]:
smallestIdx = i
array[smallestIdx], array[currentIdx] =... |
class Node:
def __init__(self,data):
self.data = data
self.left = self.right = None
def utility(root,ans):
if root is None:
return 0
## get the sum of tree using function
currsum = (root.data + utility(root.left,ans) + utility(root.right,ans))
ans[0] = max(ans... |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ans = []
while matrix:
ans += matrix.pop(0)
# Rotate
matrix = list(zip(*matrix))[::-1]
return ans
|
# AUTHOR: Sanket Khadse
# Python3 Concept: Find first and last positions of an element in a sorted array
# GITHUB: https://github.com/edusanketdk
def sol_1(ar: list, x: int) -> tuple:
"""using index function"""
return (ar.index(x), len(ar)-ar[::-1].index(x)-1) if x in ar else (-1, -1)
def sol_2(ar: list, x:... |
# brute force, dynamic programing O(n^2)
def max_area(height):
max_area = 0
for j in range(1, len(height)):
for i in range(j-1, -1, -1):
area = min(height[i], height[j]) * (j - i)
max_area = max(max_area, area)
return max_area
'''
If we try to move the pointer at t... |
class Namespace:
"""A shortcut for defining a namespace with a prefix.
Attributes:
uri: The full uri of the namespace.
prefix: Name of the prefix that will be used.
"""
uri = None
prefix = None
def __str__(self):
return self.prefix
class Uri:
"""A shortcut for co... |
# -*- coding: utf-8 -*-
"""
A base class for pipable objects
"""
class Pipable(object):
""" A class for pipable objects """
def __init__(self, this, parent=None):
super(Pipable, self).__init__()
self.this = this
self.call = this
self.parent = parent
def pipe(self, other):
... |
#
# Metrix++, Copyright 2009-2019, Metrix++ Project
# Link: https://github.com/metrixplusplus/metrixplusplus
#
# This file is a part of Metrix++ Tool.
#
# Copied from http://code.activestate.com/recipes/577268-python-data-structure-to-xml-serialization/
# - indent feature and better formatting... |
def levenshtein_distance(word1: str, word2: str) -> int:
small = word1 if len(word1) < len(word2) else word2
big = word1 if len(word1) >= len(word2) else word2
even_edits = [x for x in range(len(small) + 1)]
odd_edits = [_ for _ in range(len(small) + 1)]
for row in range(1, len(big) + 1):
if... |
n = int(input())
b = []
for i in range(30):
i += 2
s = i*i
while s <= 1000:
b.append(s)
s = s*i
answer = 1
for i in range(len(b)):
if b[i] <= n and answer < b[i]:
answer = b[i]
print(answer) |
#Desafio: Crie um programa que leia vários números inteiros pelo teclado.
# No final da execução, mostre a média entre todos os valores e qual foi o maior e menor valores lidos.
# O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores.
continuar = 'S'
cont = 0
tot = 0
maior = 0
menor = 0
w... |
#!/usr/bin/python
# if_kwd.py
age = 17
if age > 18:
print ("Driving licence issued")
else:
print ("Driving licence not permitted")
|
"""
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load
load("@bazel_tools//too... |
"""
Lists builtin plugins.
"""
plugins = []
builtins = (
('nose.plugins.attrib', 'AttributeSelector'),
('nose.plugins.capture', 'Capture'),
('nose.plugins.logcapture', 'LogCapture'),
('nose.plugins.cover', 'Coverage'),
('nose.plugins.debug', 'Pdb'),
('nose.plugins.deprecated', 'Deprecated'),
... |
def fail(request, domain):
# if you want to play with it, wire this to a url
raise Exception("HQ Couchlog simulated failure in domain %s!" % domain)
|
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [0] * len(nums)
total = 1
zeros = 0
zpos = 0
for i in range(len(nums)):
if not(nums[i]):
zeros += 1
... |
TMI_TOKEN = ""
CLIENT_ID = ""
BOT_NICK = "pequeninancientbot"
BOT_PREFIX = "!"
CHANNEL = "#hector_pulido_"
CLIENT_SECRET = ""
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
limit = 500
fib = 0
pFib = 1
print(fib)
print(pFib)
while pFib < limit:
temp = pFib
pFib = fib + pFib
print(pFib)
fib = temp
|
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
largest_three = [-1003,-1002,-1001]
smallest_three = [1003,1002,1001]
for i in nums:
if i > largest_three[0]:
largest_three[0... |
__all__ = [
"loghandler",
"githandler"
]
|
# The next lines will make the Pixel Turtle and its heading invisible
# and will clear the screen for light show
hidePixel()
hideHeading()
clear()
# First we move to the top left corner
moveTo(0, 0)
right(2)
forward(15)
right(2)
forward(7)
right(2)
forward(15)
right(2)
forward(6)
right(2)
forward(14)
right(2)
forwar... |
wiz.response.render('/auth/login', "page.signin")
wiz.response.render('/auth/join', "page.signup")
if wiz.match("/auth/logout") is not None:
if wiz.session.has("id"):
wiz.session.clear()
wiz.response.redirect("/auth/login")
if wiz.session.has("id"):
wiz.response.redirect("/")
wiz.response.redirec... |
# Created by yingwen at 2019-03-10
def IGA(pi_alpha,
pi_beta,
payoff_0,
payoff_1,
u_alpha,
u_beta,
iteration=1000,
lr=0.01):
pi_alpha_history = [pi_alpha]
pi_beta_history = [pi_beta]
pi_alpha_gradient_history = [0.]
pi_beta_gradient_history = [0.]... |
def main():
a = input().strip()
b = input().strip()
print(number_needed(a, b))
def number_needed(a, b):
sort_a = sorted(a)
sort_b = sorted(b)
a_len = len(sort_a)
b_len = len(sort_b)
if a_len < 1:
return b_len
elif b_len < 1:
return a_len
else:
num_need... |
class StreamingMetric:
'''
Class for updating measurement mean and variance
statistics in an online fashion using a moving
(and possibly decaying) average
Parameters
----------
decay: float or None
Decay value between 0 and 1 for measurement updates.
Higher values mean older ... |
def owl_count(text):
owl_count = 0
char_check = 0
realText = text.lower()
for char in list(realText):
if char == 'o' or char == 'w' or char == 'l':
char_check += 1
if char_check == 3:
owl_count += 1
else:
char_check = 0
print(owl_co... |
with open('input') as f:
lines = f.readlines()
count = 0
for l in lines:
if l[0] == '+':
count += int(l[1:])
else:
count -= int(l[1:])
print(count)
|
# Copyright Google Inc. All Rights Reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file at https://angular.io/license
"Install toolchain dependencies"
load("@build_bazel_rules_nodejs//:defs.bzl", "yarn_install")
load("@build_bazel_rules_typescript//:defs.bz... |
""" P6E10 VICTORIA PEÑAS
Escribe un programa que te pida los nombres y notas de alumnos.
Si escribes una nota fuera del intervalo de 0 a 10, el programa
entenderá que no quieres introducir más notas de este alumno. Si
no escribes el nombre, el programa entenderá que no quieres introducir
más alumnos. Nota: La lista en ... |
N, *a = map(int, open(0).read().split())
pos = [0] * (N + 1)
for i in range(N):
pos[a[i]] = i
l = [-1] * N
r = [-1] * N
result = 0
for x in range(N, 0, -1):
i = pos[x]
j = i
while j != 0 and a[j - 1] > x:
j = l[j - 1]
l[i] = j
j = i
while j != N - 1 and a[j + 1] > x:
j = ... |
""" Version And Diverse Info
**Module CONSTANTS:**
__version__ `str` - the released version (last release)
RELEASE_DATE `str` - the date of the last release
SHORT_VERSION `str` - the main version is the: __version__ stripped of the last part: e.g. used by sphinx conf.py
TESTED_HOST_OS `st... |
"""Top-level package for msm_we."""
__author__ = """John Russo"""
__email__ = 'russojd@ohsu.edu'
__version__ = '0.1.0'
|
# _ _ _
# | | | | | |
# __ _____| |__ ___| | ___ _ __ ___ ___ _ __ | |_ ___ _ __ _ _
# \ \ /\ / / _ \ '_ \ / _ \ |/ _ \ '_ ` _ \ / _ \ '_ \| __/ __| '_ \| | | |
# \ V V / __/ |_) | __/ | ... |
# Tamanho do container ---> container
# Qtd de colunas em seu grid ---> colunas
# grid específico ---> grid
# gutter ---> distância entre um grid para outro
# @media only screen and (min-width: 768px) and (max-width: 959px)
container = 768
colunas = 16
grid = 1
gutter =... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# For sample predict functions for popular libraries visit https://github.com/opendatahub-io/odh-prediction-samples
# Import libraries
# import tensorflow as tf
# Load your model.
# model_dir = 'models/myfancymodel'
# saved_model = tf.saved_model.load(model_dir)
# predictor = saved_model.signatures['default']
# Wri... |
"""
– à vista dinheiro/cheque: 10% de desconto
– à vista no cartão: 5% de desconto
– em até 2x no cartão: preço formal
– 3x ou mais no cartão: 20% de juros
"""
#Coletando o valor da compra
valor = float(input('Informe o valor da compra: R$'))
print('-' * 30)
#Coletando a forma de pagamento
print('FORMA DE PAGAMENTO:... |
Scale.default = Scale.major
Root.default = 0
Clock.bpm = 120
~n1 >> noise(
P(PSine(32),PSine(24),PSine(27),PSine(18)*.7,PSine(45)),
amp=P(.8,.7,.8,.7,.9)*.4,
delay=P(PRange(5)/5),
dur=.5,
formant=(linvar([1,3],48), linvar([3,1],53)),
chop=linvar([0,16],65),
lpf=1200,
lpr=(linvar([0,6],6... |
print("--- CONFERINDO GÊNERO ---")
def main():
genero = str(input("Informe seu gênero [M - Masculino / F - Feminino]: ")).title().strip()
if genero[0] == "M":
print("O gênero informado MASCULINO.")
elif genero[0] == "F":
print("O gênero informado é FEMININO.")
else:
print("Gêne... |
"""About sampler"""
__name__ = 'sampler'
__version__ = '0.0.1'
__author__ = "Tristan R. Brown",
__email__ = "brown.tristan.r@gmail.com",
__desc__ = "A vector space sampling package.",
__license__ = "MIT",
|
def f():
x=2
print("x:",x)
#Hauptprogramm
x=1
f()
print("x:",x)
|
"""
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
... |
S = input()
result = []
for s in S:
if s == 'I' or s == 'l':
result.append('1')
elif s == 'O' or s == 'o':
result.append('0')
else:
result.append(s)
print(''.join(result))
|
n, k = map(int, input().split())
h = [int(input()) for _ in range(n)]
h = sorted(h, reverse=True)
t = []
for i in range(n - k + 1):
t.append(h[i] - h[i + k - 1])
print(min(t))
|
"""
@author:
@file: python_dict.py
@time: 2018/6/15 13:54
"""
'''
解析字典的最新封装,可以解决大部分字典类型的数据的读取
'''
def getdictvalue(d, code):
result = []
if isinstance(d, dict) and code in d.keys():
value = d[code]
result.append(value)
return result
elif isinstance(d, (list, tuple)):
for... |
def paginate(objects, context):
"""
yields: page, page_index, total_pages
"""
DEFAULT_PAGINATION = getattr(context.settings, 'DEFAULT_PAGINATION')
object_count = len(objects)
if object_count > DEFAULT_PAGINATION:
total_pages = (
(object_count - (object_count %
... |
# Copyright 2019 Ministry of Education and Culture, Finland
# SPDX-License-Identifier: MIT
'''
Custom exception classes.
'''
class BaseException(Exception):
status_code = 500
message = 'something went wrong'
def __init__(self, message=None, status_code=None, data=None):
super().__init__()
... |
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/)
# Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
# -*- coding: utf-8 -*-
class Scope:
def apply(self, builder, model):
"""
Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.Builder
:param model: The model
:type model: orator.orm.Model
"""
raise... |
#!/usr/bin/env python
#
# Copyright (c) 2015 Pavel Lazar pavel.lazar (at) gmail.com
#
# The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED.
#####################################################################
SUPPORTED_COMPLEX_MATCH = ['basic']
SUPPORTED_MATCH_FIELDS = ['ETH_SRC', 'ETH_DST', 'ETH_TYPE',... |
# -*- coding: utf-8 -*-
"""
@author: Dr Michael GUEDJ
Algorithmique --
TP8 --
Mots
"""
# 2
def concatener(lst):
res = lst[0]
i = 1
while i < len(lst):
res += " "+lst[i]
i +=1
return res
# 3
def est_present(m, c):
for x in m:
if x == c:
r... |
def add(a):
return len(a)
# from tsfresh.feature_extraction.feature_calculators import cid_ce
# import pandas as pd
# def add(a, b):
# data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])
# data = cid_ce(data, True)
# return data
|
#a1z26 cipher by kenny zhang
def main():
menu = 'a1z26 cipher menu'
print(menu)
print('-'*len(menu))
print('[1] cipher a message\n[2] decipher a message\n[3] quit')
option = input('\nenter a menu option and ENTER: ')
if option == '1':
cipher()
elif option == '2':
... |
#
# Copyright 2017 Anil Thomas
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
guestlist = ['Barack Obama', 'Stanley Kubrick', 'Thomas Pynchon']
print("This new dinner table, I have, however, now seats 120 dinner guests.")
guestlist.insert(0, 'Bill Murray')
guestlist.insert(2, 'Stephen King')
guestlist.append('Kim Kardashian')
message = (f"How does McDonalds sound, {guestlist[0]}?")
print(mes... |
'''
max Int range in python
[-2**31] to [(2**31) -1]
'''
class Solution:
def reverse(self, x: int) -> int:
isNegative = False
reverseDigit = 0
if(x < 0):
isNegative = True
x = -1 * x
while(x > 0):
lastDigit = x % 10
... |
#!/usr/bin/python
# partition.py
s = "1 + 2 + 3 = 6"
a = s.partition("=")
print (a)
|
class Symbol:
"""
Representa um símbolo Lisp.
Diferentemente de strings, símbolos com o mesmo valor possuem a mesma identidade.
"""
data = str
CACHE = {}
def __new__(cls, data):
if isinstance(data, Symbol):
return data
try:
return cls.CACHE[data]
... |
candy_title = input('What is the candy title? ')
candy_flavor = input('What is the candy flavor? ')
print('It shall be called {0} {1}!'.format(candy_title, candy_flavor))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.