text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Write a function in JavaScript to get the first 10 prime numbers.
function getFirstTenPrimeNumbers() { let primeNumbers = []; let num = 2; while (primeNumbers.length < 10) { if (isPrime(num)) { primeNumbers.push(num); } num++; } return primeNumbers; } function isPrime(num) { for(let i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; }
null
In the following code, identify the bug and suggest a fix.
def add_two_strings(string1, string2): return string1 + string2
def add_two_strings(string1, string2): """A function to add two strings together and return the concatenated result.""" if isinstance(string1, str) and isinstance(string2, str): return string1 + string2 else: raise TypeError("Both arguments must be strings")
null
Build a web scraper in Python that extracts the title, author, and publication date of articles published on a given website.
import requests from bs4 import BeautifulSoup # Get the html content url = "https://www.example.com/articles" r = requests.get(url) html_content = r.content # Parse the html content soup = BeautifulSoup(html_content, 'html.parser') # Extract the title, author and publication date titles = soup.find_all('h1', clas...
null
Write a python program to sort an array with n elements in ascending order.
arr = [7, 5, 2, 9, 6, 4, 1, 3, 8]
def sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # The last element has already been sorted 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...
null
Implement a function to calculate the total amount of money earned from a given array of stock prices.
arr = [5, 7, 15.5, 6, 10, 11]
def calculateTotalEarnings(arr): totalEarnings = 0 for i in range(1, len(arr)): totalEarnings += max(arr[i] - arr[i - 1], 0) return totalEarnings arr = [5, 7, 15.5, 6, 10, 11] totalEarnings = calculateTotalEarnings(arr) print("Total earnings: ", totalEarnings) # Output # Total earnings: 9.5
null
Construct a regex expression that will check if a email is valid.
^[A-Za-z0-9\.\'\+\-\_]+(\@)[A-Za-z0-9.-]+([\.][a-zA-Z]{2,4})+$
[HI Wikipedia] पोरबन्दर पोरबन्दर (Porbandar) भारत के गुजरात राज्य के पोरबन्दर ज़िले में स्थित एक नगर है। यह ज़िले का मुख्यालय भी है। यह महात्मा गाँधी और श्रीकृष्ण के मित्र, सुदामा, का जन्मस्थान है। विवरण पोरबन्दर बहुत ही पुराना बंदरगाह हुआ करता था। पोरबन्दर में गुजरात का सबसे अच्छा समुंद्र किनारा है। पोरबंदर गुजरात रा...
null
null
null
null
Construct a boolean check to detect if a given string contains the word "hello".
def contains_hello(input_string): return "hello" in input_string
null
How would you implement Skip-Gram model in TensorFlow?
To implement a Skip-Gram model in TensorFlow, you would need to define the model architecture. You would then need to define the training data, which can be done using tf.data packages. Finally, you would need to use an optimization algorithm such as the AdamOptimizer to train the model.
null
Write a Python class to define a fraction and include methods to add and subtract fractions.
class Fraction: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator def __str__(self): return f"{self.numerator}/{self.denominator}" def __add__(self, other): denom = self.denominator * other.denominator num1 = self...
null
Create a Python module for a spiral matrix with the following functions: createSpiralMatrix, printSpiralMatrix, and transposeSpiralMatrix.
Not applicable
def createSpiralMatrix(n): matrix = [[0] * n for i in range(n)] row = 0 col = -1 total = n * n spiral = 1 while total > 0: # move left -> right while col + 1 < n and matrix[row][col + 1] == 0: col += 1 matrix[row][col] = spiral total -= 1 spiral += 1 # move up -> down while row + 1 < n and matrix[row + ...
null
Describe the differences between np.array and a list.
Numpy arrays are more efficient than lists as they are homogeneous in nature. This means that all the items in a numpy array must be of the same data type, while a list can contain items of any data type. Additionally, numpy arrays can be multi-dimensional while lists are only one-dimensional. Numpy arrays can be index...
null
Write a function to sort a dictionary of dictionaries in descending order based on a given key.
d = {'dict1': {'name':'tom','age':20}, 'dict2': {'name':'jerry','age':25}, 'dict3': {'name':'bill','age':24}} key = 'age'
def sort_dict_of_dicts(d, key): sorted_dict = dict(sorted(d.items(), key = lambda kv:(kv[1][key], kv[0]),reverse=True)) return sorted_dict
null
Count the number of characters in a sentence that begin with a consonant.
def count_consonants(sentence): consonants = 'bcdfghjklmnpqrstvwxyz' count = 0 for ch in sentence: if ch.lower() in consonants: count += 1 return count
null
Create a web page that contains three input boxes for a user to input name, age, and gender.
<html> <head> <title>Input Form</title> </head> <body> <form> Name:<br> <input type="text" name="name"><br> Age:<br> <input type="number" name="age"><br> Gender:<br> <input type="radio" name="gender" value="male"> Male<br> <input type="radio" name="gender" value="female"> Female<br><br> <input type="submit"> </form> </...
null
Create a code that takes in a sentence and outputs counts of each word and its frequency (how often it occurred).
sentence = "This is an example sentence to test the word count code."
def count_words(sentence): word_count = {} for word in sentence.split(): if word in word_count: word_count[word] += 1 else: word_count[word] = 1 return word_count count_words(sentence)
[EN Wikipedia] 1935–36 Hovedserien season The 1935–36 GET-ligaen season was the second season of ice hockey in Norway. Eight teams participated in the league, and Grane won the championship. Regular season External links Norwegian Ice Hockey Federation Nor Eliteserien (ice hockey) seasons 1935–36 in Norwegian ice hock...
null
null
null
[CS Wikipedia] Seznam osobností Horní Libchavy Významné osobnosti Horní Libchavy, které se nějakým způsobem zapsaly do dějin obce, se objevují již na počátku 19. století. Rozsáhlé změny revolučních let 1848–1849 přinesly novou sociální vrstvu podnikatelů. Střední vrstvy tvořily v monarchii po celé 19. století významno...
null
null
null
[EN Wikipedia] Allocution An allocution, or allocutus, is a formal statement made to the court by the defendant who has been found guilty prior to being sentenced. It is part of the criminal procedure in some jurisdictions using common law. Concept An allocution allows the defendant to explain why the sentence should ...
null
null
null
null
Write a Python program to sort data from the largest to the smallest.
[44, 23, 11, 33, 5]
unsorted_list = [44, 23, 11, 33, 5] sorted_list = sorted(unsorted_list, reverse=True) print(sorted_list)
[HI Wikipedia] यो यो हनी सिंह हिरदेश सिंह (जन्म 15 मार्च 1983), जिन्हें पेशेवर तौर पर यो यो हनी सिंह या बस हनी सिंह के नाम से जाना जाता है, एक भारतीय संगीत निर्माता, रैपर, गायक, गीतकार हैं। और एक अभिनेता. उन्होंने 2003 में एक सत्र और रिकॉर्डिंग कलाकार के रूप में शुरुआत की, और एक भांगड़ा और हिप हॉप संगीत निर्माता बन गए...
null
null
null
null
Write a JavaScript code to add two numbers using a prompt.
let a = prompt('Enter the first number:'); let b = prompt('Enter the second number:'); let sum = parseInt(a) + parseInt(b); console.log(sum);
null
Create an API in node.js to get the details of a user using an ID
id = "12345"
var express = require("express"); var app = express(); // API to get user details app.get("/user/:id", function(req,res) { var id = req.params.id; var user = { name: "John Doe", age: 30 }; res.status(200).send(JSON.stringify(user)); }); app.listen(3000);
null
Write a JavaScript statement to extract the last four characters from the string
This is a sample string.
var lastFour = myString.slice(-4);
null
Create a mySQL script to create a table called "User" with columns user_id, name, and mobile_number?
CREATE TABLE User ( user_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(50) NOT NULL, mobile_number varchar(20) NOT NULL );
null
Create a web crawler to extract all the links within a given web page
url = "https://www.example.com"
import requests from bs4 import BeautifulSoup def get_links(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') links = [link.get('href') for link in soup.find_all('a')] return links if __name__ == '__main__': print(get_links(url))
[EN Wikipedia] WHHW WHHW (1130 AM) is a radio station broadcasting a Regional Mexican radio format. It is licensed to Hilton Head Island, South Carolina. The station is currently owned by Dick Broadcasting, through licensee Dick Broadcasting Company, Inc. of Tennessee. WHHW broadcasts at 1,000 watts by day. But becaus...
null
null
null
null
Develop a python program to find the maximum depth of a binary tree.
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def maxDepth(node): if node is None: return 0 else: leftDepth = maxDepth(node.left) rightDepth = maxDepth(node.right) if leftDepth > rightDepth: r...
[HI Wikipedia] मुफ़्त मुफ़्त या नि:शुल्क या बेदाम व्यापार में ऐसी सेवा या वस्तु को कहते हैं, जो ग्राहक को बिना किसी पैसे के दी जाए। व्यापारिक संस्थाएँ व दुकानदार ग्राहकों को भविष्य में किसी बड़ी ख़रीद के लिये आकर्षित करने की आशा में चीज़ें मुफ़्त देते हैं। उदाहरण के लिये उस्तरे बनाने वाली जिलॅट कम्पनी अपने उस्तरे मुफ़...
null
null
null
[DE Wikipedia] Sigismund von Lamberg Sigismund von Lamberg († 8. Juni 1488 in Laibach) war der erste Bischof von Laibach (Ljubljana), ernannt 1461, bestätigt 1463; das Bistum Laibach war ebenfalls 1461 gegründet worden. Er entstammte der im Mannesstamm erloschenen Lambergschen Linie auf Stain und Gutenberg in Oberkrai...
null
null
null
[CS Wikipedia] Intense (album, Armin van Buuren) Intense je pátým studiovým albem nizozemského trance DJe Armina van Buurena. První představenou písní (21. leden 2013), a zároveň druhým singlem na albu je "Waiting for the Night" je též ústřední melodií nizozemského filmu Loving Ibiza () a vznikl při spolupráci se zpěv...
null
null
null
[CS Wikipedia] Pablatnice tekalitská Pablatnice tekalitská (Borneophrys edwardinae) je jediný druh žabího rodu Borneophrys čeledi pablatnicovitých (Megophryidae), který se vyskytuje na jediném místě ostrova Borneo. O životě a biologii tohoto druhu nejsou zatím žádné bližší informace. synonymum: Megophrys edwardinae (d...
null
null
null
null
Generate a Python code snippet to compute the sum of the digits of a given number.
def sum_digits(num): summation = 0 while num > 0: summation += num % 10 num = num // 10 return summation
null
Create a React component for displaying a simple profile card with the properties of name and age.
const ProfileCard = (props) => { return ( <div> <h1>{props.name}</h1> <p>Age: {props.age}</p> </div> ); }
[EN Wikipedia] Robertas Antinis Robertas Antinis (born 9 June 1946 in Kaunas) is a Lithuanian Sculptor, performance artist and poet. He is a winner of the National Culture and Art Prize. Life He graduated from the Applied Arts School in Riga in 1965, and the Latvian State Art Academy in 1970. He worked as a teacher at...
null
null
null
null
About a given number n, can you write a JavaScript program to find the sum of all the numbers that are greater than 0 and less than n?
n = 5
var sum = 0; for (var i = 1; i < n; i++) { sum = sum + i; } console.log(sum)
null
Use features of the Python language to implement 3-way partitioning of a given array.
Array: [9,6,7,4,1,6,3]
""" Use features of the Python language to implement 3-way partitioning of a given array. """ def threeWayPartition(array, pivot): less = [] equal = [] greater = [] for i in array: if i < pivot: less.append(i) elif i == pivot: equal.append(i) else: greater.append(i) return less + equal + greater if __name__ == '__main_...
null
Using Python, reverse a given string "Hello World!".
"!dlroW olleH"
[EN Wikipedia] KJIA KJIA is a Christian radio station licensed to Spirit Lake, Iowa, broadcasting on 88.9 MHz FM. KJIA serves Northwest Iowa and Southwest Minnesota. The station is owned by Minn-Iowa Christian Broadcasting, Inc. References External links KJIA's official website JIA Radio stations established in 2002 2...
null
null
null
[EN Wikipedia] 1838 in Denmark Events from the year 1838 in Denmark. Incumbents Monarch – Frederick VI Prime minister – Otto Joachim Events 17 September – After almost four decades in Rome, Bertel Thorvaldsen, accompanied by his art collections and most of his own works, returns to Copenhagen. Undated Births JanuaryMa...
null
null
null
[HI Wikipedia] तिब्बत तिब्बत तिब्बत एक देश था। जिसकी सीमा भारतऔर चीनी जनवादी गणराज्य अफगानिस्तानवबर्मा से लगती है। दलाई लामा यहां के प्रसिद्ध धार्मिक नेता हैं। यह 1950 में चीन की साम्राज्यवादी नीति का शिकार हो गया। अब यह चीन का राष्ट्रीय स्वायत्त क्षेत्र है, और इसकी भूमि मुख्य रूप से पठारी है। इसे पारंपरिक रूप से बोड ...
null
null
null
null
Write a SQL statement to select the names and IDs of customers from the customers table that live in California.
SELECT name, id FROM customers WHERE state = 'California';
null
Create a function in Python to produce a ``new_list`` which contains substring elements from the given ``list``
list = ["apple","banana","orange","carrot"]
def produce_new_list(list): '''This function will return a new list containing substrings from the given list''' new_list = [] for item in list: for i in range(0, len(item)): new_list.append(item[0:i+1]) return new_list
null
Write an R program to check if an array is in ascending order.
x <- c(2, 4, 8, 10, 15)
is_ascending <- function(x) { sorted_x <- sort(x) if (sorted_x == x) { return TRUE } else { return FALSE } }
[HI Wikipedia] अंबानी परिवार अंबानी परिवार भारत का एक औद्योगिक घराना है। धीरूभाई अंबानी द्वारा छोटे स्तर पर शुरु किया गयी एक कंपनी भारत और एशिया के सबसे बड़े औद्योगिक घरानों में से है। तेल, टेलीकाम से ले कर बहुत से क्षेत्रों में इस परिवार का दबदबा है। आजकल धीरूभाई के बेटों अनिल अंबानी और मुकेश अंबानी में चल रहे पारिवा...
null
null
null
[DE Wikipedia] Sagen aus Uri Zwischen 1903 und 1925 sammelte Pfarrer Josef Müller im Kantonsspital Uri Erzählungen über eigenartige Begebenheiten und Geschichten von Berglern. Die etwa 1600 Sagen wurden als Sagen aus Uri in drei Bänden und einem Bildband veröffentlicht. Die Geschichten findet man zum Teil im ganzen Al...
null
null
null
null
Create a Python program which takes two parameters and outputs the difference between them.
21, 49
def diff(a, b): return abs(a - b) a = 21 b = 49 print(diff(a, b)) # Output 28
null
Given a list of strings, create a Python program to find the longest common substring
strings = ["cat","car","hat"]
def find_longest_common_substring(strings): if len(strings) == 0: return '' elif len(strings) == 1: return strings[0] else: # sort the strings strings.sort(key=len) # take the first string as longest longest = strings[0] for s in strings: ...
null
Write a VBA code to return the last row where a certain value appears
Table Name: Employees Column Name: State Value: New York
Sub FindLastRowNY() LastRow = Range("A1").End(xlDown).Row For i = LastRow To 1 Step -1 If Cells(i, 2).Value = "New York" Then MsgBox i Exit Sub End If Next i End Sub
null
Generate a list of 20 strings containing random characters of length 10.
['Kj9F7VAl1q', '28jVYbueph', 'f7VZRif5uP', '2jf5CHXyt7', '3qBtyKjDIY', 'hE5wrRmIP6', 'V7jQcfhIBz', 'UQy6gCwPa5', '6Ujpu7NfMk', 'Z6DFhBoK8e', 'DIFpjgrhT7', 'TzdGsvhRO2', '1Kv4RyZoF8', 'RKjUXviPca', 'yO2PCtEjx1', 'qchomMdP9X', '9ydNHCaTZX', 'TFrhYdgSjp', 'BYeH12I4th', '4XNgJfKCAd']
null
Develop a python program to add two arrays of the same size.
a = [2, 3, 4] b = [5, 6, 7]
def add_arrays(a, b): c = [] n = len(a) for i in range(n): c.append(a[i] + b[i]) return c a = [2, 3, 4] b = [5, 6, 7] result = add_arrays(a, b) print(result) # prints [7, 9, 11]
null
Create a Python script to filter a list of numbers by a given filter. The script should use a function that takes a list of numbers and a filter as arguments and returns the filtered list.
List: [1,2,5,6,-4,7,8] Filter: x > 0
def filterList(nums, filter): # Initialize a filtered list filtered_list = [] # Iterate over the list for num in nums: # Check if filter is true if eval(str(num)+filter): filtered_list.append(num) # Return the filtered list return filtered_list result = filterList([1,2,5,6,-4,7,8], '> 0') ...
null
Explain what is Closure in Python Programming?
In Python, a closure is a higher order function (a function that takes one or more functions as arguments or returns a function) that allows a function to remember or access the variables or arguments of the enclosing scope—even after the execution of the outer function has finished. A closure is created when a nested ...
[DE Wikipedia] Special Olympics Syrien Special Olympics Syrien (englisch Special Olympics Syria) ist der von Syrien gegründete Verband von Special Olympics International mit Sitz in Damaskus. Ziel des Verbandes ist es, das ganze Jahr über Sport für Kinder, Jugendliche und Erwachsene mit geistiger Beeinträchtigung und ...
null
null
null
null
Write a Java program to print the sum of all integers from 1 to given integer.
integer = 5
public class SumIntegers { public static void main(String[] args) { int n = 5; int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } System.out.println("Sum of integers from 1 to "+n+": "+sum); } } // Output: Sum of integers from 1 to 5: 15
null
Explain why the result of the following code is 4.
x = 2 x = x+x
The result of the code is 4 because in the second statement, the value of x is modified to equal twice its original value (2 + 2 = 4).
null
Write Python code to replace all the vowels with underscore.
string = "Hello World!"
string = "Hello World!" vowels = ["a", "e", "i", "o", "u"] def replace_vowels_with_underscore(string): result = "" for char in string: if char in vowels: result += "_" else: result += char return result print(replace_vowels_with_underscore(string)) # Output: "H_ll_ W_rld!"
null
Generate a random list of numbers ranging from 1 to 10 without duplicates in Python.
Not applicable
import random # Generate a list of numbers ranging from 1 to 10 without duplicates numbers = list(range(1,11)) random.shuffle(numbers) # Print shuffled numbers print(numbers)
[CS Wikipedia] Matthias Müller Matthias Müller (* 12. září 1982, Švýcarsko) je švýcarský reprezentant v orientačním běhu, jenž v současnosti žije ve švýcarském Winterthuru. Jeho největším úspěchem je mistrovský titul ze sprintu na Mistrovství světa v roce 2010 v Trondheimu. V současnosti běhá za švédský klub Södertälj...
null
null
null
null
Split a string by a number greater than the length of the string in Python.
string = "Hello World"
split_string = string[:11] print(split_string) # Output = "Hello World"
null
Generate a valid HTML tag that can be used to link to an external website.
<a href="http://example.com" target="_blank">Link to Website</a>
null
Create a function in Python that removes duplicates from a list of items.
[1, 2, 3, 2, 4, 1]
def remove_duplicates(items): no_duplicates = [] for item in items: if item not in no_duplicates: no_duplicates.append(item) return no_duplicates items = [1, 2, 3, 2, 4, 1] result = remove_duplicates(items) print(result) # [1, 2, 3, 4]
[EN Wikipedia] Gmina Trojanów Gmina Trojanów is a rural gmina (administrative district) in Garwolin County, Masovian Voivodeship, in east-central Poland. Its seat is the village of Trojanów, which lies approximately 27 kilometres (16 mi) south-east of Garwolin and 81 km (50 mi) south-east of Warsaw. The gmina covers a...
null
null
null
null
Create a loop that prints each letter in the given string one by one on a new line.
string str = "Hello World"
for i in str: print(i)
null
Create a HTTP GET request in Python to retreive an API request.
import requests url = "https://example.com" # Send Get request to the API response = requests.get(url) # Store the response text response_text = response.text
[DE Wikipedia] Helmut Wöstmann Helmut Wöstmann, auch Helmut Woestmann (* 1. Juli 1931 in Osnabrück) ist ein deutscher Schauspieler, Hörspiel- und Off-Sprecher. Leben und Wirken Wöstmann hatte nach seiner Schauspielausbildung sein Theaterdebüt 1953 in seiner Heimatstadt Osnabrück gegeben. Anschließend folgten Verpflich...
null
null
null
null
Use the given code to extract date information from sentences. The code includes helper functions to normalize annotations, split sentences, tag parts of speech, find key verbs, and extract date information using DBpedia. To use the code, call the main function with appropriate arguments.
from subprocess import * import re import treetaggerwrapper import sparqlQuerypy from bs4 import BeautifulSoup CONSTANTKEYVERBS="die, died, death, born, birth, sworn in" #Set of words that if present in the sentence, then don't discard the sentence, we are interested. tagger = treetaggerwrapper.TreeTagger(TAGLANG = 'e...
null
Create a class in Java that can store a list of students and the courses they are enrolled in.
public class StudentList { private ArrayList<Student> students; private ArrayList<String> courses; public StudentList() { this.students = new ArrayList<Student>(); this.courses = new ArrayList<String>(); } public void addStudent(Student student) { this.students.add(student); } public void addCourse(String course) { thi...
null
Create a function in Python that takes two list of strings as parameters and returns a third list of strings which are the elements common in both lists.
list1 = ["apple", "orange", "banana", "cherry"] list2 = ["apple", "grapes", "banana", "watermelon"]
def common(list1, list2): ans_list = [] for i in list1: for j in list2: if i == j: ans_list.append(i) return ans_list if __name__ == "__main__": list1 = ["apple", "orange", "banana", "cherry"] list2 = ["apple", "grapes", "banana", "watermelon"] print(common(list1, list2)) # ['apple', 'banana']
null
Create a program in Python to merge two dictionaries into a new one.
Dictionary 1 `{'name': 'John', 'age': 25}` Dictionary 2 `{'company': 'Google', 'city': 'New York'}`
# Dictionaries dict1 = {'name': 'John', 'age': 25} dict2 = {'company': 'Google', 'city': 'New York'} # Merge two dictionaries dict3 = {**dict1, **dict2} # Print the merged dictionary print(dict3) # Output: # {'name': 'John', 'age': 25, 'company': 'Google', 'city': 'New York'}
null
Remove all HTML tags from a string.
"<h1>Hello World</h1>"
function stripHTMLTags(str) { return str.replace(/<[^>]*>/g, ""); } // Usage stripHTMLTags("<h1>Hello World</h1>"); // result: "Hello World"
[CS Wikipedia] Eugen Michalski Eugen Michalski (, 21. ledna 1897 Letyčiv – 14. října 1937 Kyjev) byl ruský učitel a básník. Dílo Jeho původní díla jsou: La unua ondo Prologo Kantoj de L'amo kaj sopiro Du poemoj Fajro kuracas – má sociální a třídní obsah. Externí odkazy Esperantská literatura Narození v roce 1897 Úmrtí...
null
null
null
null
Write a while loop that adds 1 to the value of ‘var’ each time it is iterated until it reaches 5.
var = 0
while var < 5: var += 1
null
Using the JavaScript language, write a code snippet to display the current date.
var today = new Date() var date = today.getDate() + "/" + (today.getMonth()+1) + "/" + today.getFullYear() console.log(date)
[DE Wikipedia] Hugh Percy Wilkins Hugh Percy Wilkins (geboren am 4. Dezember 1896 in Carmarthen; gestorben am 23. Januar 1960 in Bexleyheath, London) war ein walisischer Ingenieur und Amateur-Astronom. Besonders bekannt wurde er durch seine großen, handgezeichneten Mondkarten. Leben Wilkins wurde in Carmarthen geboren...
null
null
null
null
Generate a random boolean value using JavaScript.
# Using JavaScript: let boolean = Math.random() >= 0.5; console.log(boolean);
null
Create a Python program to split a given string into two parts according to a given character.
Str = "apple-banana-orange" Char = "-"
def split_string(s, char): new_list = s.split(char) return new_list result = split_string("apple-banana-orange", "-") print(result)
null
Create a Node.js server which serves a static HTML page.
// Import the necessary modules const http = require('http'); const fs = require('fs'); // Create a simple server which serves a static HTML page http.createServer((req, res) => { fs.readFile('./index.html',(err, data) => { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); }).listen(300...
null
Write a shell script to perform a binary search of an array
[2, 3, 6, 8, 10], 8
#!/bin/bash arr=(2 3 6 8 10) target=8 function binary_search() { left=0 right=${#arr[@]}-1 while [ $left -le $right ] do mid=$(( ($left+$right)/2 )) if [ ${arr[$mid]} -eq $target ] then echo "Number found at position: $(($mid+1))" return elif [ ${arr[$mid]} -lt $target ] then left=$(($mid + 1)) else right=$(($mid - 1))...
null
Build a web service in Python that performs sentiment analysis on a passed string using the TextBlob library. The web service should return a JSON object containing the sentiment score between -1 and 1.
Not applicable
from flask import Flask, request, jsonify from textblob import TextBlob app = Flask(__name__) @app.route('/sentiment/analyze', methods=['POST']) def sentiment(): request_data = request.get_json() sentence = request_data['sentence'] blob = TextBlob(sentence) sentiment = blob.sentiment.polarity resp...
null
Develop a Python script that augments a given sentence with additional data from a given dictionary.
Sentence: "I went to the store." Dictionary: {"Noun": ["apple", "banana", "orange"], "Verb": ["bought"]}
sentence = "I went to the store." dictionary = {"Noun": ["apple", "banana", "orange"], "Verb": ["bought"]} words = sentence.split() for i, word in enumerate(words): if word in dictionary["Noun"]: words[i] += "s" if words[-1] == "store.": words[-2] = dictionary["Verb"][0] new_sentence = " ".join(words) print(ne...
null
What should this Python program do?
def is_palindrome(s): '''Write your code here.'''
def is_palindrome(s): '''This function returns True if the string s is a palindrome and False if it isn't.''' return s == s[::-1] # Checks if s is the same as its reverse.
null
Create a MySQL query to delete all the entries with the name "John" in the table "users".
DELETE FROM users WHERE name="John";
null
Create a Python script to scrape a website to extract the text from all the web-pages.
import requests from bs4 import BeautifulSoup def scrape_website(url): # sending get request and saving the response as response object r = requests.get(url) # extracting data in json format data = r.text soup = BeautifulSoup(data, 'html.parser') contents = soup.find_all('p') f...
null
Write a C++ program to generate Fibonacci numbers up to a maximum of n values.
n = 20
#include <iostream> int main() { int n = 20; int a = 0, b = 1, c; std::cout << a << " " << b << " "; for (int i = 2; i < n; ++i) { c = a + b; std::cout << c << " "; a = b; b = c; } return 0; }
[CS Wikipedia] Serie A 2014/2015 Soutěžní ročník Serie A 2014/15 byl 113. ročník nejvyšší italské fotbalové ligy a 83. ročník od založení Serie A. Soutěž začala 30. srpna 2014 a skončila 31. května 2015. Účastnilo se jí opět 20 týmů z toho 17 se kvalifikovalo z minulého ročníku. Poslední tři týmy předchozího ročníku, ...
null
null
null
null
Generate a list that has the all even numbers between 1 and 50, inclusive.
even_nums_list = [x for x in range(1,51) if x % 2 == 0]
null
Design a class in Python to store a student's name, age and subject of interest.
class Student: def __init__(self, name, age, subject): self.name = name self.age = age self.subject = subject
null
Write a code in Python to toggle all characters in a string.
The string is: "Hello World!"
s = "Hello World!" res = "" for char in s: if char.islower(): res += char.upper() elif char.isupper(): res += char.lower() print(res)
null
Create a Python function that checks whether a given list contains any repeated elements.
def has_duplicates(arr): # Create an empty set s = set() # Traverse through the list for item in arr: # If the element is present # in the set then it is a duplicate if item in s: return True else: s.add(item) # No duplicate element...
[CS Wikipedia] Jakub Bitman Jakub Bitman (* 22. července 1988) je český badmintonista, šestnáctinásobný mistr ČR v badmintonu, jeden z nejúspěšnějších českých hráčů v historii. Úspěchy 24násobný juniorský Mistr ČR šestinásobný mistr ČR smíšených družstev (2006, 2009, 2012, 2015, 2017, 2018) trojnásobný mistr ČR ve čty...
null
null
null
[EN Wikipedia] Sökündüzü, Ergani Sökündüzü is a neighbourhood in the municipality and district of Ergani, Diyarbakır Province in Turkey. Its population is 195 (2022). References Neighbourhoods in Ergani District
null
null
null
null
Create a python program that calculates the total cost of an item given the quantity and price.
Quantity: 5, Price: 10
def calcTotalCost(quantity, price): totalCost = quantity * price return totalCost result = calcTotalCost(5, 10) print(result)
null
Write a JavaScript function to print a specific pattern.
function printPattern(n) { for (var i = 1; i <= n; i++) { for (var j = 1; j <= i; j++) { document.write(j + " "); } document.write("<br>"); } } printPattern(7);
null
Create a program to find the frequency of characters in a given string in Python.
Example string: "abbccccdddde"
def find_character_frequency(string): freq = {} for i in string: if i in freq: freq[i] += 1 else: freq[i] = 1 return freq # example string = "abbccccdddde" print(find_character_frequency(string)) # Output: {'a': 1, 'b': 2, 'c': 4, 'd': 4, 'e': 1}
null
Optimize this code in Python to reduce the time complexity from O(n^2) to O(nlogn).
def maximum_two(arr): m1 = m2 = float('-inf') for n in arr: if n > m2: if n > m1: m1, m2 = n, m1 else: m2 = n return (m1, m2)
def maximum_two(arr): arr.sort(reverse=True) m1 = arr[0] m2 = arr[1] return (m1, m2)
null
Modify the following SQL query to list all the job titles that start with the letter "A".
SELECT * FROM jobs WHERE job_title LIKE 'A%';
null
Create a class in Python which contains three attributes and a method.
class MyClass: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def get_values(self): return self.x, self.y, self.z
null
Design an algorithm to swap two numbers in Python.
Swap 10 and 20
def swapNumbers(a, b): temp = a a = b b = temp print("After swapping: a =", a, " b =", b) # Driver program a = 10 b = 20 swapNumbers(a, b)
null
Create a CSS rule for making all text elements bold.
* { font-weight: bold; }