content stringlengths 7 1.05M |
|---|
AUTHOR = 'Sage Bionetworks'
SITENAME = 'Sage Bionetworks Developer Handbook'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
# FEED_ALL_ATOM = None
# CATEGORY_FEED_ATOM = None
# TRANSLATION_FEED_ATOM = None
# AUTHOR_FEED_ATO... |
'''
URL: https://leetcode.com/problems/diagonal-traverse
Time complexity: O(mn)
Space complexity: O(1)
'''
class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
m = len... |
'''
Author: jianzhnie
Date: 2022-01-24 11:36:20
LastEditTime: 2022-01-24 11:36:21
LastEditors: jianzhnie
Description:
'''
|
'''
Crear un programa que permita al usuario ingresar los montos de las compras de un cliente
(se desconoce la cantidad de datos que cargarรก, la cual puede cambiar en cada ejecuciรณn),
cortando el ingreso de datos cuando el usuario ingrese el monto 0.
Si ingresa un monto negativo, no se debe procesar y se debe pedir q... |
"""
@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... |
# Ex083.2
"""Create a program where the user types any espression that uses parentheses.
Your application should analyze where the expression passed has open and closed parentheses in the correct order."""
list = []
temp = []
expression = str(input('\033[32mType a expression: \033[m'))
for c in expression:
if c =... |
jogador = {}
lista = []
total = 0
jogador['Nome'] = input('Nome do jogador: ')
quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome'])))
for i in range(0, quantidade):
gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1)))
total += gol_quantidade
lista.append(gol_qu... |
def my_sum(*args):
# *args = 1, 2, 3
print(type(args))
print(args)
return sum(args)
def my_sum_2(args):
# args = [1, 2, 3]
return sum(args)
print(my_sum(1, 2, 3)) # a
# my_sum([1, 2, 3]) # b
# my_sum_2(1, 2, 3) # c
print(my_sum_2([1, 2, 3])) # d
_, *args = 0, 1, 2, 3
args_2 = [1, 2, 3]... |
"""Views for WillPress.
"An Excellent Blog Engine"
Copyright (c) 2021 by William Ellison. This program is licensed under
the terms of the Do What the Fuck You Want To Public License, version 2
or later, as described in the COPYING file at the root of this
distribution.
William Ellison
<waellison@gmail.com>
October ... |
#!/usr/bin/python3
def Encrypt(K, P):
cipher = []
for letter in P:
cipher.append(chr((ord(letter) - 65 + K) % 26 + 65))
return "".join(cipher)
def disp(K):
for i in range(0, 25):
print(chr(i + 65), end=" ")
print()
for i in range(0, 25):
print(chr((i + K) % 26 + 65),... |
sample = {
"asset": {
"ancestors": [
"projects/163454223397",
"organizations/673763744309"
],
"assetType": "compute.googleapis.com/Instance",
"name": "//compute.googleapis.com/projects/sc-vice-test/zones/us-central1-a/instances/instance-1",
"resource":... |
smile_dict = [b"\xF0\x9F\x98\x81",
b"\xF0\x9F\x98\x82",
b"\xF0\x9F\x98\x83",
b"\xF0\x9F\x98\x84",
b"\xF0\x9F\x98\x85",
b"\xF0\x9F\x98\x86",
b"\xF0\x9F\x98\x89",
b"\xF0\x9F\x98\x8A",
b"\xF0\x9F\x98\x8B",
b"\xF0\x9F\x98\x8C",
b"\xF0\x9F\x98\x8D",
b"\xF0\x9F\x98\x8F",
b"\xF0\x9F\x98\x92",
b"\xF0\x9F\x98\x93",... |
# Code generated by font-to-py.py.
# Font: dsm.ttf
version = '0.26'
def height():
return 21
def max_width():
return 12
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font =\... |
# CPU: 0.42 s
ids = set()
for _ in range(int(input())):
ids.add(int(input()))
m = 1
while True:
reduced_ids = set()
for id_ in ids:
reduced_id = id_ % m
if reduced_id not in reduced_ids:
reduced_ids.add(reduced_id)
else:
break
else:
break
m += 1
print(m)
|
"""
|-------------------------------------------|
| Problem 2: Write a program to convert |
| temperature in Celsius to Fahrenheit |
| & vice versa |
|-------------------------------------------|
| Approach: |
| We use the formula ... |
_item_fullname_='mdtraj.Topology'
def is_mdtraj_Topology(item):
item_fullname = item.__class__.__module__+'.'+item.__class__.__name__
return _item_fullname_==item_fullname
|
# -*- coding: utf-8 -*-
# author: @RShirohara
__version__ = "0.1.1"
__doc__ = f"""
tegaki v{__version__}
Released under MIT License.
https://github.com/RShirohara/handwriting_detection
"""
|
# Find the Runner-Up Score or Finding second largest number
n = int(input())
arr = list(map(int, input().split()))
l = max(arr)
for i in range(n):
if l == max(arr):
arr.remove(max(arr))
print(max(arr))
|
class Solution:
def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float:
def helper(A, B, k):
if not A or not B:
return (A or B)[k]
else:
ia, ib = len(A) // 2, len(B) // 2
ma, mb = A[ia], B[ib]
if k > ia + ... |
"""
Profile ../profile-datasets-py/div83/068.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/068.py"
self["Q"] = numpy.array([ 2.83917200e+00, 3.51202800e+00, 4.81389700e+00,
6.13220200e+00, 6.51049800e+00, 6.51553800e+00,
6.5143... |
"""Apparently you can't monkey-patch Curses windows, so we've got to
have this stupid module instead."""
def movedown(window, rows=1, x=None):
current_y, current_x = window.getyx()
window.move(current_y+rows, x if x is not None else current_x)
def movex(window, new_x):
current_y = window.getyx()[0]
wi... |
def translate(message):
"""
A dumb translator which does not actually translate anything.
:param message: The message.
:return: A translated message (dummy: actually, the same message).
"""
return message
|
while True:
try:
l = int(input())
except EOFError:
break
lesmas = map(int, input().split())
maior = max(lesmas)
if maior < 10:
print(1)
elif maior >= 10 and maior < 20:
print(2)
else:
print(3) |
# Module to flatten a list
def flatten(array, flattened=[]):
for value in array:
if(isinstance(value, list)):
flatten(value, flattened)
else:
flattened.append(value)
return flattened
|
# input
N, K = map(int, input().split())
# process
'''
1. ์ชฝ์ง๋ค์ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ๋ค๊ณ ๊ฐ์ .
2. i๋ฒ ์ชฝ์ง๋ฅผ 1๋ฒ ์ชฝ์ง ๋ฐ๋ก ์ผ์ชฝ์ผ๋ก ์ฎ๊ธฐ๋ฉด i-1๊ฐ์ ๊ทธ๋ ๊ณ ๊ทธ๋ฐ ์ฌ์ด ํ์.
3. ํญ์ ๊ทธ๋ ๊ณ ๊ทธ๋ฐ ์ฌ์ด๊ฐ ๊ฐ์ฅ ๋ง์ด ์๊ธฐ๋ ์ชฝ์ง๋ฅผ ์ฎ๊น(0<i<=N && i<=K+1 ์ธ i ์ค ์ต๋).
ํ ๋ฒ ์ฎ๊ธด ์ชฝ์ง ๋ฒํธ ์ด์์ ์ชฝ์ง ๋ฒํธ๋ ์ฎ๊ธธ ์ ์์. (๋ชจ์์ผ๋ก ์ฆ๋ช
๊ฐ๋ฅ)
4. K := K - (i-1)
'''
moved = [0 for _ in range(N+1)]
left_1 = []
last = N
whil... |
class ComicException(Exception):
pass
class PathResolutionException(ComicException):
""" A path given to a COMIC template tag contained variables that could not
be resolved
"""
|
# -*- coding: utf-8 -*-
"""
Apache2 License Notice
Copyright 2018 Alex Barry
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 ... |
def se_come(tablero, n, i, j):
for col in range(n):
if tablero[i][col]:
return True
for fil in range(n):
if tablero[fil][j]:
return True
for x in range(j):
if tablero[i + j - x][x] or tablero[i - j + x][x]:
return True
for x in range(j + 1, n):
if tablero[i + j - x][x] or tablero[i - j + x][x]:
... |
class BaseAgent(object):
def __init__(self, config):
self.device = config.device
self.num_actions = config.action_dim
self.observation_dim = config.observation_dim
self.discount_factor = config.discount_factor
self.grad_clip_val = config.grad_clip_val
self.batch_siz... |
inp = input("please enter the text")
print("The original string : " + inp)
res = [int(i) for i in inp.split() if i.isdigit()]
# this basically makes a list of all the numbers
for i in res:
if len(str(i))==10:
print("the phone number in the text is:" + str(i))
|
### Static Array Sequence Implementation
# Static array has fixed size and can't grow or shrink.
# Static array has a O(1) constant time for get_at and set_at operations.
# Static array has a O(n) time for insert and delete operations at the back of the array.
# Reference implementation: MIT Introduction to Algorith... |
"""
Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.
Binary search has a huge advantage of time complexity over linear sea... |
# This sample tests the case where super() is used within a metaclass
# __init__ method.
class Metaclass(type):
def __init__(self, name, bases, attrs):
super().__init__(name, bases, attrs)
|
__author__ = 'studentmac'
def make_negative( number ):
if number >0:
number *=-1
return number
|
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 389 - Platonic Dice
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
An unbiased single 4-sided die is thrown and its value, T, is noted.
T unbiased 6-sided dice are thrown and their scores are added together. The sum, C, is noted.
... |
{
"targets": [
{
"target_name": "rsvg",
"sources": [
"src/Rsvg.cc",
"src/Enums.cc",
"src/Autocrop.cc"
],
"variables": {
"packages": "librsvg-2.0 cairo-png cairo-pdf cairo-svg",
"libraries": "<!(pkg-config --libs-only-l <(packages))",
"ldflags": "<!(pkg-config --libs-only-L --libs-... |
#!/usr/bin/python
class me:
# initialization routine
def __init__(self, foo):
self.myvar = foo
def getval(self):
return self.myvar
# this is an instance of the "me" class
my = me("this")
# my instantiation/assignment allows access to getval method
x = my.getval()
print(x) |
# OpenWeatherMap API Key
weather_api_key = "48ae7399e76d973a4b9ac9efe89908a3"
# Google API Key
g_key = "AIzaSyBrlKm1v_NyDl4nT9LOZWE5s_sQa2D5Hoc"
|
height=list(map(int,input().split()))
height
def trapped_water(h):
n=len(h)
total=0
for i in range(1,n-1):
left=h[i]
for j in range(i):
left=max(h[j],left)
right=h[i]
for j in range(i+1,n):
right=max(h[j],right)
total+=min(left,right)-h[i]
return total
print(trapped... |
a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256))
b=(( 4 , -3 , 4/3., -1/4. ), # matrix B #
(-13/3., 19/4., -7/3., 11/24.),
( 3/2., -2. , 7/6., -1/4. ),
( -1/6., 1/4., -1/6., 1/24.))
def MatrixMul( mtx_a, mtx_b):
tpos_b = list(zip(... |
def cria_matriz(num_linhas, num_colunas):
""" (int, int) -> matriz (lista de listas)
cria e retorna uma matriz comnum_linhas linhas e num_colunas
colunas em que cada elemento รฉ digitado pelo usuรกrio.
"""
matriz = [] # lista vazia
for i in range(num_linhas):
#cria a linha i
linha ... |
#
# PySNMP MIB module HPN-ICF-WEB-AUTHENTICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-WEB-AUTHENTICATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:42:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
COLORS = {
'darkest_blue': '#111111',
'background_blue': '#0C172D',
'text_green': '#54F041',
'dev_purple': '#ab52c5',
'loc_pink': '#f6c6fa',
'great_depression_red': '#C90705',
'walter_white': '#FFFFFF'
} |
class Order:
Clayful = None
name = 'Order'
path = 'orders'
@staticmethod
def config(clayful):
Order.Clayful = clayful
return Order
@staticmethod
def accept_refund(*args):
return Order.Clayful.call_api({
'model_name': Order.name,
'method_name': 'accept_refund',
'http_method': ... |
def neighboors(active, x, y, width, height):
number = 0
for i in range(-1, 2):
for j in range(-1, 2):
#Skip the choosen block
if 0 <= x+i < width and 0 <= y+j < height:
if i == 0 and j == 0:
pass
elif active[x+i][y+j] == 1:
... |
'''
--- Day 10: Balance botValues ---
You come upon a factory in which many robots are zooming around handing small microchips to each other.
Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it in a marked "outpu... |
#conjunto de cartas
class Card:
def __init__(self,suit,value):
super().__init__()
self.suit =suit
self.value = value
#reescribimos la salida al imprimir
def __repr__(self):
return " of ".join((self.value,self.suit))
|
#!/usr/bin/python
filename = input("Please enter your file name: ")
with open(filename, 'r') as f:
lines = f.readlines()
l = list(line.rstrip('\n') for line in lines)
measurements_count = 0
while len(l) != 1:
if l[0] < l[1]:
measurements_count += 1
del(l[0])
else:
print(f"There are {measurements_count} measur... |
class BasePlugin:
name = None
description = None
package_name = None
class ExportPlugin(BasePlugin):
format_type = None
def format(self):
raise NotImplementedError()
def help(self):
return f"For help check the official documentation for '{self.package_name}' plugin."
|
def get_talker_candidates(predictions_prob, entities, cluster_map, inverse_cluster_map, return_prob=False):
predictions_set = set()
entity_prob_map = {}
for prediction_prob, entity in zip(predictions_prob, entities):
if prediction_prob[1] < 0.5:
continue
if cluster_map[ent... |
"""
Module that defines the mappings for CSV rows, variable names in code and DHIS2 UIDs
set_order: used to set certain Verbal Autopsy properties before others (dependants).
needs to be an integer.
csv_name: CSV column name
if none => there is no column in the CSV for this property
example: Age in Days
dhis_uid: DH... |
'''
A builder design pattern is a type of design pattern in which large complex objects are created without letting
end user know about the complexity fo teh objects
E.g: In the example below teh document object is made up of text,image, line, table objects but the end used is
not aware of creation of all these obje... |
#Candidates
candidates_list = [
{
"name": "Joe Biden",
"party": "Democrat",
"twitter_url": "https://twitter.com/JoeBiden",
"twitter_screen_name": "JoeBiden",
"twitter_user_id": "939091",
"announcement_date": "April 25, 2019",
"status": "running"
},
{
... |
#Jackknife reduction templates for NIRC2 and OSIRIS pipelines.
#Author: Sean Terry
def jackknife():
"""
Do the Jackknife data reduction.
"""
##########
#
# NIRC2 Format
#
##########
##########
# Ks-band reduction
##########
# Nite 1
target = 'MB07192'
sci_file... |
# -*- coding: utf-8 -*-
class Data:
def __init__(self, d):
seqs = tuple, list, set, frozenset
for i, j in d.items():
if isinstance(j, dict):
setattr(self, i, Data(j))
elif isinstance(j, seqs):
setattr(self, i, type(j)(Data(sj) if isinstance(sj... |
#! /usr/bin/env python3
days = int(input("Enter days:"))
months = days // 30
days = days % 30
print("Months = {} Days = {}".format(months, days))
|
#
# PySNMP MIB module CISCO-ITP-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:46:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
nums = [1, 2, 3, 4, 5]
for num in nums:
print(num+1)
print('-------------')
for i in range(3):
print(i) |
"""20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the c... |
class Node:
def __init__(self, data: int):
self.data: int = data
self.next: Node = None
class LinkedList:
def __init__(self, head: Node = None):
self.head = head
def push(self, data: int):
node = Node(data)
if not self.head:
self.head = node
el... |
# <html><body><pre>
# RLinterface module
"""
This module provides a standard interface for computational experiments with
reinforcement-learning agents and environments. The interface is designed to
facilitate comparison of different agent designs and their application to different
problems (environments). See http... |
def convert(file_1, file_2, file_out):
def read_origin(file_in):
# Dumps from sfrolov are raw arrays of bytes strictly following the internal address space of 1/2 of BRP unit.
return file_in.read() if file_in is not None else bytes(2048)
def write_derivative(bytes_4096, file_out):
s = ... |
"""
Python - Binary Tree
Tree represents the nodes connected by edges. It is a non-linear data structure. It has the following properties.
One node is marked as Root node.
Every node other than the root is associated with one parent node.
Each node can have an arbiatry number of chid node.
We create a tree data st... |
def binSearchClosest(list, key):
if list==[]:
return None
elif len(list)==1:
return 0
left=0; right=len(list)-1
# binary search
while left<right:
mid = (left + right) // 2
if list[mid]==key: # found
return mid
elif list[mid]>key:
righ... |
"""
Created by ไธๆ on 2018-1-29.
"""
__author__ = 'ไธๆ'
class TradeInfo:
def __init__(self, trades):
self.total = 0
self.trades = []
self.__parse(trades)
def __parse(self, trades):
self.total = len(trades)
self.trades = [self.__map_to_trade(gift) for gift ... |
harmonization_table = {
"Trees": ["Trees", "CEO_Trees", "GO_Trees"],
"Shrubland": ["Shrubland", "CEO_Shrubland", "GO_Shrub"],
"Grassland": ["Grassland", "CEO_Grassland", "GO_Grass"],
"Cropland": ["Cropland", "CEO_Cropland", "GO_Cultivated"],
"Built-up": ["Built-up", "CEO_BuiltUp", "GO_BuiltUp"],
... |
"""
talking clock
returns word version of 24hour time
wisemonkey
oranbusiness@gmail.com
20181219
github.com/wisehackermonkey
run tests with command
python -m nose
"""
hour_names = ["twelve","one","two","three","four","five","six","seven",
"eight","nine","ten","eleven","twelve","thirteen","fourteen",
"fifteen","sixt... |
# ์ฐํ์ด๋ ์ด๋ฆฐ ์์ , ์ง๊ตฌ ์ธ์ ๋ค๋ฅธ ํ์ฑ์์๋ ์ธ๋ฅ๋ค์ด ์ด์๊ฐ ์ ์๋ ๋ฏธ๋๊ฐ ์ค๋ฆฌ๋ผ ๋ฏฟ์๋ค. ๊ทธ๋ฆฌ๊ณ ๊ทธ๊ฐ ์ง๊ตฌ๋ผ๋ ์ธ์์ ๋ฐ์ ๋ด๋ ค ๋์ ์ง 23๋
์ด ์ง๋ ์ง๊ธ, ์ธ๊ณ ์ต์ฐ์ ASNA ์ฐ์ฃผ ๋นํ์ฌ๊ฐ ๋์ด ์๋ก์ด ์ธ๊ณ์ ๋ฐ์ ๋ด๋ ค ๋๋ ์๊ด์ ์๊ฐ์ ๊ธฐ๋ค๋ฆฌ๊ณ ์๋ค.
#
# ๊ทธ๊ฐ ํ์นํ๊ฒ ๋ ์ฐ์ฃผ์ ์ Alpha Centauri๋ผ๋ ์๋ก์ด ์ธ๋ฅ์ ๋ณด๊ธ์๋ฆฌ๋ฅผ ๊ฐ์ฒํ๊ธฐ ์ํ ๋๊ท๋ชจ ์ํ ์ ์ง ์์คํ
์ ํ์ฌํ๊ณ ์๊ธฐ ๋๋ฌธ์, ๊ทธ ํฌ๊ธฐ์ ์ง๋์ด ์์ฒญ๋ ์ด์ ๋ก ์ต์ ๊ธฐ์ ๋ ฅ์ ์ด ๋์ํ์ฌ ๊ฐ๋ฐํ ๊ณต๊ฐ์ด๋ ์ฅ์น๋ฅผ ํ์ฌํ์๋ค. ํ์ง๋ง ์ด ๊ณต๊ฐ์ด๋ ์ฅ์น๋ ์ด๋ ๊ฑฐ๋ฆฌ๋ฅผ ๊ธ๊ฒฉํ๊ฒ ๋๋ฆด ... |
#!/usr/bin/env python
# coding: utf-8
_JOINT_NAMES_1 = [
'Waist',
'Torso',
'Neck',
'Head',
'LeftShoulder',
'LeftElbow',
'LeftWrist',
'LeftHand',
'RightShoulder',
'RightElbow',
'RightWrist',
'RightHand',
'LeftHip',
'LeftKnee',
'LeftAnkle',
'LeftFoot',
'RightHip',
'RightKnee',
'RightAnkle',
'RightFoo... |
F_BOIL_TEMP = 212.0
F_FREEZE_TEMP = 32.0
C_BOIL_TEMP = 100.0
C_FREEZE_TEMP = 0.0
F_RANGE = F_BOIL_TEMP - F_FREEZE_TEMP
C_RANGE = C_BOIL_TEMP - C_FREEZE_TEMP
F_C_RATIO = C_RANGE / F_RANGE
def ftoc(f_temp):
"Convert Fahrenheit temperature <f_temp> to Celsius and return it."
c_temp = (f_temp - F_FREEZE_TEMP) * F_... |
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict_s = {}
dict_t = {}
for c in s:
if c not in dict_s:
dict_s[c] = 1
else:
dict_s[c] += 1
for c... |
S = input()
t = 0
for i in range(0, len(S), 5):
if S[i:i + 5] == '(^^*)':
t += 1
print(t, len(S) // 5 - t)
|
"""
Insert sort
O(n**2)
"""
def insert_sort(a):
n = len(a)
for top in range(1, n):
k = top
while k > 0 and a[k-1] > a[k]:
a[k], a[k-1] = a[k-1], a[k]
k -= 1
return a
def test_insert_sort():
""" Tests """
assert(insert_sort([3, 2, 5, 7, 3, 4, 7, 0, 3, 1, ... |
class DotDict(dict):
"""A class that extends dict to allow accessing keys as attributes."""
def __init__(self, *args, **kwargs):
"""Initalize the DotDict.
This method does nothing other that initialize the parent dict
with the passed args and kwargs.
"""
super... |
class BasePayload(object):
_name = "Default"
_code = None
_activated = False
_conf = None
_stager_path = ""
def setHandler(self, IP, PORT):
d = dict()
d['SERVER'] = IP
d['PORT'] = PORT
self.setCode(d)
def setActivated(self, status):
... |
n = int(input())
registered_users = dict()
for i in range(n):
command = input()
tokens = command.split(' ')
action = tokens[0]
if action == 'register':
username = tokens[1]
licence_plate = tokens[2]
if username not in registered_users:
registered_users[usern... |
# How do you read and write to a specific file :
# We have a few different ways to do that using a file stream :
# To open a file, you create a stream object
# we determine the file name and the mode, most of time we leave the buffer_size ti the default
stream = open(file_name, mode, buffer_size)
# Modes :
# r - Rea... |
number_employee = int(input(''))
hours = int(input())
value_work_hour = float(input())
salary = hours * value_work_hour
print('NUMBER = {}'.format(number_employee))
print('SALARY = U$ {:.2f}'.format(salary))
|
# dummy request object
class DummyReq:
# constructor
def __init__(self,env,):
# environ
self.subprocess_env = env
# header
self.headers_in = {}
# content-length
if self.subprocess_env.has_key('CONTENT_LENGTH'):
self.headers_in["content-length"] = self.... |
#!/usr/bin/env python3
"""Enumerates primes using the sieve of Eratosthenes.
Verification: [0009](https://onlinejudge.u-aizu.ac.jp/status/users/hamukichi/submissions/1/0009/judge/4571021/Python3)
"""
def sieve_of_eratosthenes(end):
"""Enumerates prime numbers below the given integer `end`.
Returns (as a tu... |
'''
Listas em Python - fatiamento, append, insert, pop, del, clear, extend, +
min, max
range
nome_da_lista = [] "declaraรงรฃo"
'''
# รญndice 0 1 2 3 4
lista = ['A', 'Bacana', 'C', 'D', 'E']
# - 5 4 3 2 1
string = 'ABCD'
print(string[1])
print('-'*10)
print(lista[1])
print('-'*10)
print(list... |
class Person(object):
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
|
"""
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are u... |
class Solution:
def minCostToMoveChips(self, chips: List[int]) -> int:
count = [0] * 2
for chip in chips:
count[chip % 2] += 1
return min(count[0], count[1])
|
#!/usr/bin/env python
# encoding: utf-8
"""
symmetric_tree.py
Created by Shengwei on 2014-07-04.
"""
# https://oj.leetcode.com/problems/symmetric-tree/
# tags: medium, tree, recursion
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is ... |
"""
.. _compas_fea.app:
********************************************************************************
app
********************************************************************************
.. module:: compas_fea.app
The compas_fea package PyQt and Vtk application.
app
===
.. currentmodule:: compas_fea.app.app
:... |
test = {
'name': 'q2_1',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> prof_names.num_columns
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> prof_names.num_rows
71
... |
print("Welcome to the professor quality calculator by MillenniumWare!")
print("Follow the prompts below to calculate how good your professor is!!!")
print("************************")
print("")
name = input("Enter your professor's name! >")
print("")
print("On a scale of 1-5 (1 being horrible, 2 tolerable, 3 adequ... |
"""
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
"""
class ListNode(object):
def __init__(self, x):
... |
def convert_fasta_to_string(filename):
"""Takes a genome FASTA and outputs a string of that genome
Args:
filename: fasta file
Returns:
string of the genome sequence
"""
assert filename.split('.')[-1] == 'fasta' # assert correct file type
with open(filename) as f:
sequenc... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 16:27:44 2018
@author: positiveoutlier
Guess the Number Game!
The user thinks of an integer between 0 (inclusive) and 100 (not inclusive).
The computer makes guesses, and the user will give it input - is its guess too high or too low?
Using bisection search, the com... |
"""
49. How to filter every nth row in a dataframe?
"""
"""
Difficulty Level: L1
"""
"""
From df, filter the 'Manufacturer', 'Model' and 'Type' for every 20th row starting from 1st (row 0).
"""
"""
Input
"""
"""
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
"""
|
"""
# Gallery
.. include:: ../gallery/legend/README.md
.. include:: ../gallery/colorbar/README.md
.. include:: ../gallery/subplots/README.md
"""
|
def test_empty():
"""
I should learn how to write tests
"""
pass
|
class Solution(object):
def atMostNGivenDigitSet(self, D, N):
B = len(D) # bijective-base B
S = str(N)
K = len(S)
A = [] # The largest valid number in bijective-base-B.
for c in S:
if c in D:
A.append(D.index(c) + 1)
else:
... |
"""
0528. Random Pick with Weight
Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex will be called at most 10000 times.
Example 1:
Input:
["... |
#!/usr/bin/python3
def check(dx,dy):
f=open("input","r")
l=f.readlines()
l=[l.strip('\n\r') for l in l]
x=0
y=0
c=0
while(y<len(l)):
if l[y][x]=='#':
c+=1
x+=dx
if x>=len(l[0]):
x-=len(l[0])
y+=dy
return (c)
... |
Import("env")
# Access to global construction environment
build_tag = env['PIOENV']
# Dump construction environment (for debug purpose)
# print(env.Dump())
# Rename binary according to environnement/board
# ex: firmware_esp32dev.bin or firmware_nodemcuv2.bin
env.Replace(PROGNAME="firmware_%s" % build_tag) |
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
res = set()
dic = {}
for i in range(len(s)):
temp = s[i:i+10]
if temp not in dic:
dic[temp]=1
else:
res.add(temp)
return res
... |
def make_exchange_name(namespace, exchange_type, extra=""):
return "{}.{}".format(namespace, exchange_type) if not extra else "{}.{}@{}".format(namespace, exchange_type, extra)
def make_channel_name(namespace, exchange_type):
return "channel_on_{}.{}".format(namespace, exchange_type)
def make_queue_name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.