Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad
Algorithms
Arrays

create a pop_first and pop_last functions which will delete first/last element from vector and then return it

#include<vector>

template <typename T>
T
pop_last(std::vector<T>* v) {
  T result = (*v)[v->size() - 1];
  v->pop_back();
  return result;
}

template <typename T>
T
pop_first(std::vector<T>* v) {
  T result = (*v)[0];
  v->erase(v->begin());
  return result;
}

template int pop_last(std::vector<int>*);
template int pop_first(std::vector<int>*);
Databases
Object-oriented Programming

SQLite is a lightweight disk-based database that doesn’t require a server process and allows accessing the database using a nonstandard variant of the SQL.

Objective

  • Build a survey application that utilizes Python's built-in sqlite3 module.

Scenario

What is your favorite programming language? This Survey application prompts a user to enter their username, and favorite programming_language. It saves the results to a sqlite3 database, and displays the results afterwards.

import sqlite3
import os

# constants:
CREATE_SURVEY_TABLE = """
CREATE TABLE IF NOT EXISTS Survey_tb (
    id INTEGER,
    username VARCHAR(50) UNIQUE,
    language VARCHAR(20),
    PRIMARY KEY(id)
    );"""

INSERT_INTO_SURVEY = """
INSERT INTO Survey_tb (username, language) VALUES(?,?);
"""

DISPLAY_RESULTS = """
SELECT * FROM Survey_tb;
"""

MENU_PROMPT = """ -- Favorite Programming Language Survey!--"""


class SurveyConnection:
    """SQLite3 Survey connection class"""

    def __init__(self):
        self.conn = sqlite3.connect(os.path.join(os.getcwd(), 'survey.db'))
        self.curr = self.conn.cursor()
        self.__create_table()

    def __create_table(self):
        """Creates tables used to store survey results."""
        with self.conn:
            self.conn.execute(CREATE_SURVEY_TABLE)

    def save_to_db(self, username, language):
        """This function saves survey results to database."""
        try:            
            with self.conn:
                self.conn.execute(INSERT_INTO_SURVEY, (username, language))
                return 'Your results have been saved successfully!'             
        except sqlite3.IntegrityError:
            print("You have already taken the survey")
            return False


class Survey:
    """A survey class with a sqlite3 connection class."""

    def __init__(self, connection):
        self.connection = connection

    def take_survey(self):
        """Prompts user for username, and favorite programming language, and save results to database."""
        print(MENU_PROMPT)
        username = input('Enter your username:\n> ')
        language = input('What is your favorite programming?:\n> ')
        
        self.connection.save_to_db(username, language)
        self.connection.conn.commit()

    def show_survey_results(self):
        """Displays results of database."""
        row = self.connection.curr.execute(DISPLAY_RESULTS).fetchall()
        for result in row:
            print(result)


def main():          
    connection = SurveyConnection()
    survey = Survey(connection)
    survey.take_survey()
    survey.show_survey_results()


if __name__ == '__main__':
    main()
int main;
import socket
def setup():
    print('setup done')
    
def http_server(port = 80):
    with socket.create_server(('127.0.0.1',port)) as my_server:
        with my_server.accept()[0] as con:
            packet = con.recv(1024).decode()
            con.send(b'sent mssg')
def close():
    pass

Description: Write a function number_sum that takes a list of integers as input and returns the sum of all positive numbers in the list. If the list contains only negative numbers or is empty, the function should return 0.

Function signature: def number_sum(numbers: List[int]) -> int:

Example
number_sum([1, 2, 3, -4, -5]) # returns 6 (1 + 2 + 3)
number_sum([-1, -2, -3]) # returns 0

from typing import List

def number_sum(numbers: List[int]) -> int:
    return sum(num for num in numbers if num > 0)

# Example usage
print(number_sum([1, -2, 3, -4, 5]))  # Output: 9
print(number_sum([-1, -2, -3]))  # Output: 0

Write a function that will have one argument which will be a string (sentence) and you have to capitalize every words first letter in that sentence. For example: if the input is "i am a javascript programmer" then the output shoud come "I Am A Javascript Programmer"

function capitalize(sentence) {
    let words = sentence.split(' ');
    const length = words.length;
    for (let i = 0; i < length; ++i) {
        words[i] = words[i][0].toUpperCase() + words[i].substr(1)
    }
    return words.join(' ');
}
console.log(capitalize("i am a javascript programmer"));
from random import randint
quotes= ["Captain Teemo on duty.","Yes, sir!", "Armed and ready.","Reporting in.","Hut, two, three, four.","I'll scout ahead!","Swiftly!","That's gotta sting.","Never underestimate the power of the Scout's code.","Size doesn't mean everything."]
def motivation():
    return quotes[randint(0,len(quotes)-1)]
Debugging

Task

  • Debug the authenticated_request function. There are several bugs in this code preventing it from executing correctly. If properly debugged, it will autheniticate the request to the given url, and return a 200 HTTP response status code (which means there was a successfful response).

Rule

  • Do not edit the URL constant in the Code or Preloaded tab. The purpose of this kumite is to debug the code within the authenticated_request method, and generated a 200 response code to this given url.

Hint

Click to view
  • You must look at the URL constant in the Preloaded tab to successfully debug this.
  • There is an incorrect: data structure, method, and parameter.
import requests



def authenticated_request():
    credentials = {'username': 'seraph', 'password': 'secret'}
    try:
        response = requests.post(url=URL, data=credentials)

    except (ValueError, NameError, TypeError) as e:
        return False
    else:
        return response.status_code == 200
def get_of_my_lawn(on_my_lawn):
    if on_my_lawn:
        return "get of my lawn"
Data Science
Mathematics

Background information

Time is measured differently on each planet. One Earth year is equivalent to the amount of
time it takes for Earth to orbit the sun. On other planets, this orbital time is shorter or longer.

image

Planet Rotation period (hours) Orbit period (days)
Mercury 58.6 88.0
Venus 243 224.7
Earth .99 365.25
Mars 1.03 687
Jupiter .41 4331
Saturn .45 10747
Uranus .72 30589
Neptune .67 59800
Pluto 6.39 90560

Task

Create a function named planetary_age that takes two parameters, planet, and age which are str, and int respectively. The function should calculate your age on other planets.

def planetary_age(planet, age):
    hashmap = {
        'mercury': {'rotation': 58.6, 'revolution': 88.0},
        'venus': {'rotation': 243, 'revolution': 224.7},
        'earth': {'rotation': .99, 'revolution': 365.25},
        'mars': {'rotation': 1.03, 'revolution': 687},
        'jupiter': {'rotation': .41, 'revolution': 4331},
        'saturn': {'rotation': .45, 'revolution': 10747},
        'uranus': {'rotation': .72, 'revolution': 30589},
        'neptune': {'rotation': .67, 'revolution': 59800},
        'pluto': {'rotation': 6.39, 'revolution': 90560}
    }

    earth_days = age * hashmap['earth']['revolution']
    planet_age = earth_days / hashmap[planet]['revolution']
    days = earth_days / hashmap[planet]['rotation']
    return planet_age, days