text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
[CS Wikipedia] Zdeněk Kluiber Doc. RNDr. Ing. Zdeněk Kluiber, CSc., Ph.D. (20. března 1950, Ústí nad Labem – 14. prosince 2010) byl český středoškolský a vysokoškolský pedagog a popularizátor výuky fyziky. V roce 2001 byl zařazen mezi tisícovku lidí, kteří měli na světě největší vliv na přírodovědné vzdělávání. Se svo...
null
null
null
null
Write a Python script to extract all the values for a given key from a dictionary.
dictionary = { 'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4', }
def get_key_values(dictionary, key): return [value for key, value in dictionary.items() if key == key]
null
Compute the factorial of a given number using a recursive algorithm.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
null
Implement a decision tree classifier in Python to predict car prices.
[Number_of_Doors, Vehicle_Size, Price] [2, Small, 12000] [4, Small, 18000] [4, Large, 20000] [4, Small, 25000]
import pandas as pd from sklearn import tree # Dataset data = [[2, 'Small', 12000], [4, 'Small', 18000], [4, 'Large', 20000], [4, 'Small', 25000]] # Columns Headers columns= ['Number_of_Doors', 'Vehicle_size', 'Price'] # Create Dataframe df = pd.DataFrame(data, columns=columns) # Create Features X = df.iloc[:, :2]....
null
Edit the following HTML code so that it displays a black, 100px border-radius circle.
<div class="circle"></div>
<div class="circle" style="border-radius: 100px; background-color: black; height: 100px; width: 100px;"></div>
null
Generate an optimized python code for finding the maximum element in a list of numbers.
def find_max(l): max_elmt = l[0] for x in l: if x > max_elmt: max_elmt = x return max_elmt
null
Explain the purpose of each line of code in the following program.
""" def fun(x): y = x * 2 return y """
""" The first line of code defines a function named `fun` which takes a single parameter `x`. The second line multiplies the parameter `x` by 2 and assigns the resulting value to a new variable called `y`. The third line returns the value stored in `y` as the output of the function. """
null
Write a function that takes a sentence as an argument and returns a Dictionary of all the words and their counts in the sentence.
'The quick brown fox jumps over the lazy dog'
def count_words(sentence): words_counts = {} words = sentence.split(" ") for word in words: if word not in words_counts: words_counts[word] = 0 words_counts[word] += 1 return words_counts print(count_words('The quick brown fox jumps over the lazy dog'))
null
Convert the following HTML string to a DOM tree using JavaScript.
<div><span>Hello World</span></div>
let parser = new DOMParser(); let div = parser.parseFromString('<div><span>Hello World</span></div>', 'text/html'); let domTree = div.querySelector("div");
null
Develop a python code to evaluate the sum of all the even numbers in a given sequence.
def sum_even_numbers(sequence): result = 0 for num in sequence: if num % 2 == 0: result += num return result
null
Create a Python program to generate multiplication tables from 1 to 10.
for i in range(1, 11): for j in range(1, 11): print(i*j, end = " ") print()
null
Construct a Python class for playing 'Rock, Paper, Scissors'.
class Game: def __init__(self): pass def play_game(self, player_choice): # list of possible choices choices = ["rock", "paper", "scissors"] # randomly choose one from the list computer_choice = choices[random.randint(0, 2)] # compare choice ...
null
Modify the following code segment to add multiple values in an array
var myArray = []; myArray[0] = 'x';
var myArray = []; myArray.push('x', 'y', 'z');
null
Construct a program to shuffle the content of a list.
import random def shuffle_list(lst): for i in range(len(lst)-1, 0, -1): j = random.randint(0, i) lst[i], lst[j] = lst[j], lst[i] return lst
null
You are given a string array. Code a JavaScript function to remove duplicate strings from the array.
let arrStrings = ["apple", "orange", "apple", "banana"]
function removeduplicates(arr){ let arrDupRemoved = []; for (let i = 0; i < arr.length; i++){ if(arrDupRemoved.indexOf(arr[i]) === -1){ arrDupRemoved.push(arr[i]); } } return arrDupRemoved; } console.log(removeduplicates(arrStrings)) // prints ["apple", "orange", "banana"]
null
Using the bubble sort algorithm, sort the following array.
[3, 5, 2, 1, 4]
def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] retur...
null
We need to write a program to generate all permutations of a given string.
def generate_permutations(s): results = [] if len(s) == 1: results.append(s) else: for i, c in enumerate(s): for perm in generate_permutations(s[:i] + s[i + 1:]): results.append(c + perm) return results
null
Compare the following two strings and list the differences.
string1 = "Hello World" string2 = "Hello World!"
The strings are different as the second string has an exclamation mark at the end.
null
Identify the output of this snippet of C code.
int x = 10, y = 5; int z = (x * y) - 15;
The output of this snippet of C code is z = 25.
null
Use CSS to create a text area with the width of 300px and the height of 200px
<style> textarea{ width: 300px; height: 200px; } </style>
null
Construct a while loop in the code to print the integers from 0 to 9.
i = 0 while i < 10: print(i) i += 1
null
Create an algorithm in Python to find the largest element in an unsorted list of numbers.
[10, 5, 20, 8, 9, 12]
def find_large_element(lst): largest_number = lst[0] for i in range(1, len(lst)): if lst[i] > largest_number: largest_number = lst[i] return largest_number my_list = [10, 5, 20, 8, 9, 12] print(find_large_element(my_list)) # 20
null
Write an algorithm using Python that calculates the prime factors of an input number.
def prime_factorize(x): if x == 1: return [] i = 2 prime_factors = [] while x > 1: if x % i == 0: prime_factors.append(i) x= x / i else: i += 1 return prime_factors prime_factorize(10) # Output: [2, 5]
null
Add two matrices of size 3x3.
mat1 = [[1,2,3], [4,5,6], [7,8,9]] mat2 = [[10,11,12], [13,14,15], [16,17,18]]
# adding two matrices res = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # iterating through rows for i in range(3): # iterating through columns for j in range(3): res[i][j] = mat1[i][j] + mat2[i][j] # printing the result for i in range(3): for j in range(3): print(res[i][j], end=" ") print() # Output: 11 13 15 17 19 21 23 25 27
null
Create an algorithm in Python to find the GCD of two numbers.
Number 1: 28 Number 2: 56
# function to calculate GCD def gcd(x, y): # This function implements the Euclidian # algorithm to find GCD while(y): x, y = y, x % y return x # Driver program to test above function n1 = 28 n2 = 56 print("GCD of", n1, "and", n2, "is", gcd(n1, n2))
null
Split the following sentence into tokens.
Sentence: I cannot wait to go to the movies.
['I', 'can', 'not', 'wait', 'to', 'go', 'to', 'the', 'movies', '.']
null
Can you create a web scraper in Python to extract the titles of articles from a newspaper website?
http://example.com/newspaper
import requests from bs4 import BeautifulSoup url = "http://example.com/newspaper" # fetch data from the given URL r = requests.get(url) # create a BeautifulSoup object soup = BeautifulSoup(r.content, "lxml") # extract the title of all articles for article_title in soup.find_all('h3', class_='title'): print(art...
null
Write a JavaScript function to format a given number to HH:MM:SS.
// Given a number of seconds input let secs = 85
const formatTime = (secs) => { let d = new Date(0); d.setSeconds(secs); let hh = d.getHours().toString().padStart(2, '0'); let mm = d.getMinutes().toString().padStart(2, '0'); let ss = d.getSeconds().toString().padStart(2, '0'); return `${hh}:${mm}:${ss}`; }
[HI Wikipedia] रामेश्वरम शहर रामेश्वरम (Rameswaram), जिसे तमिल लहजे में "इरोमेस्वरम" भी कहा जाता है, भारत के तमिल नाडु राज्य के रामनाथपुरम ज़िले में एक तीर्थ नगर है, जो हिन्दू धर्म के पवित्रतम चार धाम तीर्थस्थलों में से एक है। यह रामेश्वरम द्वीप (पाम्बन द्वीप) पर स्थित है, जो भारत की मुख्यभूमि से पाम्बन जलसन्धि द्वारा...
null
null
null
null
Compile a Python program to retrieve the nth Fibonacci number in the series.
5
def Fibonacci(n): if n<0: print("Incorrect input") elif n==1: return 0 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) num = 5 print(Fibonacci(num))
[DE Wikipedia] Istituto di Studi Comunisti Palmiro Togliatti Das Istituto di Studi Comunisti Palmiro Togliatti (Institut für Kommunistische Studien Palmiro Togliatti) war von 1944 bis 1993 die zentrale Parteihochschule des Partito Comunista Italiano (PCI). Die Schule war in Rom gegründet worden und hatte ab 1955 ihren...
null
null
null
null
Create a Javascript function to take an array of numbers and return the sum of all its elements.
[1, 2, 3, 4, 5]
function sumArrayElements(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; }
null
Rewrite the following Python code using list comprehensions.
def divisible(x): out = [] for i in range(1, x): if (i % 3 == 0) or (i % 5 == 0): out.append(i) return out
def divisible(x): return [i for i in range(1, x) if (i % 3 == 0) or (i % 5 == 0)]
[CS Wikipedia] Reichswerke Hermann Göring Reichswerke Hermann Göring (oficiální označení Reichswerke AG für Erzbergbau und Eisenhütten „Hermann Göring“) byly spolu s I.G. Farben a Vereinigte Stahlwerke AG největšími německými koncerny v Třetí říši. Od března 1937 plánoval Hermann Göring, Paul Pleiger a Hermann Alexand...
null
null
null
[EN Wikipedia] Cornelis Bastiaan Vaandrager Cornelis Bastiaan Vaandrager (26 August 1935, in Rotterdam – 18 March 1992, in Rotterdam), who generally published with only his initials as C. B. Vaandrager, was a Dutch writer and poet who lived and worked in Rotterdam. Later he came to be known simply by the shortened ver...
null
null
null
[DE Wikipedia] Ruacanafälle Die Ruacanafälle sind ein Wasserfall des namibisch-angolanischen Grenzflusses Kunene, der hier in der Regenzeit bis zu 107 Meter tief in eine bis zu 1067 Meter breite Schlucht stürzt. Beschreibung Ihren Namen tragen die Fälle nach der in der Nähe gelegenen Kreisstadt Ruacana. Direkt am Wass...
null
null
null
null
Create a program in Python that takes two numbers as an input and returns the sum of the two numbers.
def sum_nums(a, b): """Returns the sum of two numbers a and b.""" return a + b
null
Write a SQL query to select the latest registration record for each user.
SELECT * FROM registrations WHERE registration_date IN (SELECT MAX(registration_date) FROM registrations GROUP BY user_id);
[DE Wikipedia] Benito Rigoni Benito Rigoni (* 11. April 1936 in Asiago; † 23. Dezember 2021 in Dueville) war ein italienischer Bobfahrer. Biografie Benito Rigoni kam bereits in jungen Jahren mit dem Wintersport in Berührung. Am Anfang seiner sportlichen Karriere trat er im Skilanglauf auf den langen Distanzen an, ohne...
null
null
null
null
Write a function in Python which converts a given string to a list, split by words.
"Hello world!"
# Function to convert a string to a list, split by words def string_to_list(string): # Initialize an empty list word_list = [] # Iterate through each character of the string for character in string: word = "" while character != " " and character != "": word += character ...
null
Find the total area of all countries from the table.
Table name: countries Columns: - name (text) - population (integer) - area (float) - capital_city (text)
SELECT SUM(area) FROM countries;
null
Create a function to generate the nth term in the Fibonacci sequence.
n = 3
def get_fib_term(n): if n <= 1: return n else: return get_fib_term(n-1) + get_fib_term(n-2) print(get_fib_term(3))
[EN Wikipedia] Hlavenec Hlavenec is a municipality and village in Prague-East District in the Central Bohemian Region of the Czech Republic. It has about 500 inhabitants. Sights The most important monument is the memorial of Emperor Charles VI made by Matthias Braun in 1724–1725. References Villages in Prague-East Dis...
null
null
null
null
Write a Java program to read the following text and count the number of words in the given sentence.
This is a sample sentence.
import java.util.*; public class CountWords { public static void main(String[] args) { String str = "This is a sample sentence."; int wordCount = 0; for (int i = 0; i < str.length(); i++) { if ((str.charAt(i) == ' ') || (str.charAt(i) == '.')) { wordCount++; } } System.out.println("The number of words in the given sent...
[EN Wikipedia] Asterism Asterism may refer to: Asterism (astronomy), a pattern of stars Asterism (gemology), an optical phenomenon in gemstones Asterism (typography), (⁂) a moderately rare typographical symbol denoting a break in passages See also Aster (disambiguation) Asterisk (disambiguation)
null
null
null
null
Write a Python program to detect if an array contains any duplicate elements.
[3, 5, 8, 1, 2, 3]
def check_duplicates(arr): seen = set() for element in arr: if element in seen: return True else: seen.add(element) return False arr = [3, 5, 8, 1, 2, 3] result = check_duplicates(arr) print(result)
[DE Wikipedia] Bendere Oboya Bendere Opamo Oboya (* 17. April 2000 in Gambela, Äthiopien) ist eine australische Sprinterin, die sich auf den 400-Meter-Lauf spezialisiert hat. Sportliche Laufbahn Erste internationale Erfahrungen sammelte Bendere Oboya im Jahr 2017, als sie bei den Commonwealth Youth Games in Nassau in ...
null
null
null
null
Create a Visual Basic function to print the contents of an array.
Public Sub PrintArray(arr() As Integer) For i = 0 To arr.Length - 1 Console.WriteLine(arr(i)) Next End Sub
[EN Wikipedia] Tagara Tagara may refer to: Țâgâra, a village in Plopana Commune, Bacău County, Romania Ter, Maharashtra, a village in India, identified as the ancient Tagara trading centre mentioned in the Periplus of the Erythraean Sea. Tagara was the important trade centres of ancient India was on the trade route co...
null
null
null
null
Write a function in Python to convert a 2D array into a single column array.
arr = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
def convert_to_single_column_array(arr): single_column_arr = [] for sub_arr in arr: for val in sub_arr: single_column_arr.append(val) return single_column_arr
[CS Wikipedia] Farní sbor Českobratrské církve evangelické v Praze 9 – Horní Počernice Farní sbor Českobratrské církve evangelické v Praze 9 - Horní Počernice je sborem Českobratrské církve evangelické v Praze. Sbor spadá pod Pražský seniorát. Sbor byl ustaven jako samostatný roku 1950. Duchovní sboru je farářka Alžbě...
null
null
null
null
Implement a web scraper in Python to extract all headlines from a web page.
import requests from bs4 import BeautifulSoup url = 'https://example.com/' response = requests.get(url) html = response.text soup = BeautifulSoup(html, 'html.parser') headlines = [] for tag in soup.find_all('h1', class_='headline'): headline = tag.string headlines.append(headline)
null
Explain the difference between <!DOCTYPE> and <meta> tags.
The HTML <!DOCTYPE> tag is used to indicate which version of HTML web page is based on. It allows a browser to know which type of document it is dealing with, so that it can determine how to render the document. The <meta> tag is used to provide information about the content of the web page, such as its title, author, ...
null
Create a Python class to represent a 3 x 3 matrix with variable values.
class Matrix: def __init__(self, a00=0, a01=0, a02=0, a10=0, a11=0, a12=0, a20=0, a21=0, a22=0): self.matrix = [[a00, a01, a02], [a10, a11, a12], [a20, a21, a22]] def __str__(self): return str(self.matrix)
null
Write a Python program to sort a list of strings by the length of each string.
def sort_by_length(strings): return sorted(strings, key=len)
null
Create a Dockerfile to build a container with python, flask, and gunicorn.
Not applicable
FROM python:3.7 RUN mkdir /usr/src/app WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt EXPOSE 5000 COPY . . CMD ["gunicorn", "--workers", "3", "-eventlet", "--bind", ":5000", "wsgi:app"]
null
Using JavaScript, create a program to check whether two given strings are an anagram or not.
// JavaScript Code function checkAnagrams(str1, str2) { const s1 = str1.split('').sort().join(''); const s2 = str2.split('').sort().join(''); return s1 === s2; }
null
Program a C# procedure to display the multiplication table of a given number.
void DisplayTable(int num) { for (int i = 1; i <= 10; i++) { Console.WriteLine($"{num} x {i} = {num * i}"); } }
null
Implement a Python parser to print return a list of words from a given string.
"Hello, World!"
def parse_words(string): words = [] for word in string.split(" "): words.append(word.strip("!,.? \n\t\r\"\'-")) return words result = parse_words("Hello, World!") print(result) ## Output: ['Hello', 'World']
null
Design a CSS grid container with 3 columns of equal size.
.container { display: grid; grid-template-columns: 1fr 1fr 1fr; }
null
Design a function in Python that takes two parameters, a list and a number, and returns a list where all elements are multiplied by the number.
[1,2,3], 4
def mul_list(input_list, number): return [x*number for x in input_list]
[HI Wikipedia] रायपुर रायपुर (Raipur) भारत के छत्तीसगढ़ राज्य में स्थित एक नगर है। यह राज्य की राजधानी है और रायपुर ज़िले का मुख्यालय है। रायपुर छत्तीसगढ़ राज्य का सबसे बड़ा शहर होने के साथ-साथ राज्य का एक महत्वपूर्ण औद्योगिक और व्यापारिक केन्द्र है। छत्तीसगढ़ के विभाजन के पूर्व रायपुर मध्य प्रदेश राज्य का अंग था। राय...
null
null
null
null
How would you create a website that provides users with their daily horoscopes?
The website should provide the users with an interface to select their star sign from a drop-down list. When the user selects their star sign, the website should display their daily horoscope. To achieve this, the website should connect to a database which contains the daily horoscopes for each of the star signs.
null
Create a Python script to scrape the title and link of news articles from a given page.
from bs4 import BeautifulSoup import requests def get_news_articles(url): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') articles = [] for article in soup.find_all('article'): link = article.find('a', class_="shop-now-option")['href'] title = article.find('h2...
null
Initialize a variable with a list containing numbers from 1-100.
list_numbers = [i for i in range(1,101)]
null
How could the following code be optimized?
def remove_duplicates(input_list): temp_list = [] for item in input_list: if item not in temp_list: temp_list.append(item) return temp_list
def remove_duplicates(input_list): return list(set(input_list)) #This is more efficient than iterating over the list to remove duplicate items.
null
Write Java code to generate random numbers between 0 and 10.
Random rand = new Random(); // Generate random integers in range 0 to 10 int rand_int1 = rand.nextInt(11);
null
Write an R function that determines the average value of an integer array.
average <- function(numbers) { sum <- 0 for (i in numbers) { sum <- sum + i } return(sum/length(numbers)) }
[EN Wikipedia] Pataua River The Pataua River is a tidal river of the Northland Region of New Zealand's North Island. It flows northeast from its origins east of Whangarei, reaching the Pacific Ocean at the southern end of Ngunguru Bay. At its mouth, the river is flanked by the settlements of Pataua North and Pataua So...
null
null
null
null
Write an Android app for creating and playing a quiz competition.
public class QuizApp extends Activity { private ArrayList<QuizQuestion> questions; public void onCreate(Bundle bundle) { questions = new ArrayList<QuizQuestion>(); // other code // such as setting the layout // and adding questions to the list } public void showQuestion() { // code to show new question // such as setti...
null
To test the installation of our library, run the `test_install` and `test_sdist` methods in the `TestInstallation` class. The `test_install` method installs the library using `python setup.py install` and checks that it can be used. The `test_sdist` method creates a source distribution tarball with `python setup.py sdi...
""" Tests installation of our library. """ import glob import os import shutil import sys import tarfile import threading import unittest import stem import stem.util.system import test.util from test.util import only_run_once INSTALL_MISMATCH_MSG = "Running 'python setup.py sdist' doesn't match our git contents i...
null
Write a Python function to randomize a given list of integers.
[1, 2, 3, 4, 5]
import random def randomize(arr): random.shuffle(arr) return arr
null
Create a predictive algorithm in Python to predict the price of a given stock.
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression def predict_stock_price(data): # clean and prepare the data data = data.dropna() # split the data into f...
null
Create a HTML page displaying 3 columns of data
Data: ["Name", "Age", "Gender"], ["Bob", 35, "Male"], ["John", 28, "Male"], ["Sarah", 39, "Female"]
<html> <head> <title>Data</title> </head> <body> <table> <thead> <th>Name</th> <th>Age</th> <th>Gender</th> </thead> <tbody> <tr> <td>Bob</td> <td>35</td> <td>Male</td> </tr> <tr> <td>John</td> <td>28</td> <td>Male</td> </tr> <tr> <td>Sarah</td> <td>39</td> <td>Female</td> </tr> </tbody> </table> </body> </html>
[DE Wikipedia] Luca Sanchez Luca Sanchez (* 18. März 1999 in Perpignan) ist ein französischer Tennisspieler. Karriere Sanchez spielte so gut wie gar nicht auf der ITF Junior Tour. In der Jugend-Rangliste kam er bis Platz 1184. Bei den Profis spielte Sanchez 2018 das erste Mal auf der drittklassigen ITF Future Tour. 20...
null
null
null
null
Convert this Java code sample to Python.
public int sumOfArray(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; }
def sum_of_array(array): sum = 0 for i in range(len(array)): sum += array[i] return sum
null
Write a Python program for finding the maximum of 3 numbers.
4, 7, 6
def max_of_three(a, b, c): if (a > b) and (a > c): greatest = a elif (b > a) and (b > c): greatest = b else: greatest = c return greatest print("Max is: ", max_of_three(4, 7, 6))
null
Given the following input, write a Python program to output the characteristics of the longest word.
laptop,computer,keyboard
def longest_word(list_words): longest_word = max(list_words, key=len) print("Length of longest word: " + str(len(longest_word))) print("Longest Word: " + longest_word) list_words = ["laptop", "computer", "keyboard"] longest_word(list_words)
null
Write SQL code to remove duplicates from a database table.
Table name: Items Columns: ID, Name
DELETE FROM Items WHERE ID NOT IN (SELECT MIN(Id) FROM Items GROUP BY Name)
[HI Wikipedia] सिन्धी भाषा सिंधी भारत के पश्चिमी हिस्से और मुख्य रूप से सिन्ध प्रान्त में बोली जाने वाली एक प्रमुख भाषा है। यह सिन्धी हिन्दू समुदाय(समाज) की मातृ-भाषा है। गुजरात के कच्छ जिले में सिन्धी बोली जाती है और वहाँ इस भाषा को 'कच्छी भाषा' कहते हैं। इसका सम्बन्ध भाषाई परिवार के स्तर पर आर्य भाषा परिवार से है जि...
null
null
null
null
Write a function to check whether two lists are equal.
list1=[1,2,3,4,5] list2=[1,2,3,4,5]
def equal(list1, list2): if len(list1) != len(list2): return False for i in range(len(list1)): if list1[i] != list2[i]: return False return True
[EN Wikipedia] 2009 A Lyga The Lithuanian A Lyga 2009 was the 20th season of top-tier football in Lithuania. The season started on 4 April 2009 and ended on 31 October 2009. Ekranas successfully defended their title. Promotion and relegation Šilutė were relegated to the I Lyga after finishing the 2008 season in last p...
null
null
null
[EN Wikipedia] Otematata River The Otematata River is a river in North Otago, New Zealand. It rises west of Kohurau and flows northward into Lake Aviemore east of Otematata township. See also List of rivers of New Zealand References Rivers of Otago Rivers of New Zealand
null
null
null
null
Design an algorithm in Python to search a number in an sorted array.
def search(arr, x): l = 0 r = len(arr) - 1 while l <= r: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return -1
null
Create an AI program that recognizes handwritten letters and digits using Python.
Not applicable
# imports import tensorflow as tf from tensorflow import keras # load the MNIST dataset mnist = keras.datasets.mnist # Split the dataset into training and testing sets (x_train, y_train), (x_test, y_test) = mnist.load_data() # Preprocess the data x_train, x_test = x_train / 255.0, x_test / 255.0 # create a model mode...
[EN Wikipedia] Croceibacter Croceibacter is a genus in the phylum Bacteroidota (Bacteria). Etymology The name Croceibacter derives from:Latin adjective croceus, saffron-colored; Neo-Latin masculine gender noun, a rodbacter, nominally meaning "a rod", but in effect meaning a bacterium, rod; Neo-Latin masculine gender n...
null
null
null
null
Write a code in Go that will reverse all the words in a sentence.
sentence: "GPT is a powerful tool"
package main func reverseWords(sentence string) string { words := strings.Split(sentence, " ") var reversedSentence string for i:=len(words)-1; i>=0; i-- { reversedSentence += words[i] + " " } return strings.TrimSpace(reversedSentence) }
null
How would you code a function in Python to rotate elements of an array?
def rotate_array(array, n): ''' This function takes in an array and an integer n and rotates the elements of the array by n positions. ''' return array[n:] + array[:n]
[EN Wikipedia] Thewa Thewa is a special art of jewelry making which involves fusing of intricately worked-out sheet gold on molten glass. It evolved in Pratapgarh district, Rajasthan India. Its origin dates back to the rajput era. Process Thewa is a traditional art of fusing 23K Gold with multicoloured glass. The glas...
null
null
null
null
Generate a code in Java for sorting an array using Mergesort.
public static void sortMerge (int [] array) { //Array must have more than one element if (array.length > 1) { int len = array.length; //Split vector into two halves int mid = len/2; int left [] = Arrays.copyOfRange (array, 0, mid); int right [] = Arrays.copyOfRange (array, mid, len); //Sort each half sortMerge (left); ...
null
Code a recursive solution for counting the number of characters in a given string.
example
def count_chars(string): if len(string) == 0: return 0 return 1 + count_chars(string[1:])
null
Compare the following two strings and print out which one is bigger.
str1="Hello" str2="World"
let str1="Hello"; let str2="World"; if(str1 > str2){ console.log(str1 + " is bigger than " + str2); } else{ console.log(str2 + " is bigger than " + str1); }
[DE Wikipedia] Central Cee Central Cee (* 4. Juni 1998 in Shepherd’s Bush, London, Vereinigtes Königreich; bürgerlich Oakley Neil Caesar-Su), auch bekannt als Cench, ist ein britischer Rapper aus Westlondon. Ende 2020 hatte er seinen nationalen Durchbruch mit dem Song Loading. Mit seinem Debütalbum Wild West war er im...
null
null
null
null
Given a string and an integer N, write a Python function to construct the Nth palindromic string.
def construct_palindrome(string, N): length = len(string) mid = length // 2 left = string[:mid] right = left[::-1] if length % 2 == 0: left = string[:mid - (N - 1)] right = left[::-1] else: left = string[:mid - N] right = string[mid + 1:(mid + 1) + N][::-1] return left + string[mid] + right
[EN Wikipedia] Tūtoko River The Tūtoko River is a river located in the Darran Mountains in New Zealand. Originating from the western flank of Mount Tūtoko it is a tributary of the Cleddau River. See also List of rivers of New Zealand References Rivers of Fiordland
null
null
null
null
Describe how a web server handles a request.
When a web server receives a request, it typically passes the request to a request handler. The request handler interprets the request and takes the appropriate action. Depending on the type of request, this could include accessing a file or a database, or running an application. After the request has been processed, t...
null
Write a Python script to print the current date in the following format: "Monday, October 5th, 2020".
import datetime date_info = datetime.datetime.today() day_name = date_info.strftime("%A") month_name = date_info.strftime("%B") date_num = date_info.strftime("%-d") year_num = date_info.strftime("%Y") print(f"{day_name}, {month_name} {date_num}th, {year_num}")
null
Edit the following code to generate a boolean array with True for odd numbers and False for even numbers
a = [1, 2, 3, 4, 5]
import numpy as np a = [1, 2, 3, 4, 5] b = np.array([i % 2 for i in a])
null
You need to write an HTML page with two forms, one for registering a new user and the other for logging in an existing user.
<h1>Welcome to the Sign Up/Login Page</h1> <h2>Sign Up</h2> <form action="signup.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required> <br> <label for="password">Password:</label> <input type="password" name="password" required> <br> <input type="submit" value="Sign Up...
null
How would you call a function 'process' in JavaScript?
The function 'process' can be called with the following syntax: process();