Code_ID,Code_Text,Label,Source_Type,Generation_Prompt,Language,normalized_code,original_line_count,normalized_line_count ,"def unique_list(l): return list(set(l)) # Example usage print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",1.0,PERPLEXITY,Write a Python function that takes a list and returns a new list with distinct elements from the first list.,python,"def unique_list(l): return list(set(l)) # Example usage print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))",5,5 ,"class LFUCache { public LFUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (!keyToVal.containsKey(key)) return -1; final int freq = keyToFreq.get(key); freqToLRUKeys.get(freq).remove(key); if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) { freqToLRUKeys.remove(freq); ++minFreq; } // Increase key's freq by 1 // Add this key to next freq's list putFreq(key, freq + 1); return keyToVal.get(key); } public void put(int key, int value) { if (capacity == 0) return; if (keyToVal.containsKey(key)) { keyToVal.put(key, value); get(key); // Update key's count return; } if (keyToVal.size() == capacity) { // Evict LRU key from the minFreq list final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next(); freqToLRUKeys.get(minFreq).remove(keyToEvict); keyToVal.remove(keyToEvict); } minFreq = 1; putFreq(key, minFreq); // Add new key and freq keyToVal.put(key, value); // Add new key and value } private int capacity; private int minFreq = 0; private Map keyToVal = new HashMap<>(); private Map keyToFreq = new HashMap<>(); private Map> freqToLRUKeys = new HashMap<>(); private void putFreq(int key, int freq) { keyToFreq.put(key, freq); freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>()); freqToLRUKeys.get(freq).add(key); } }",0.0,leetcode,,java,"class LFUCache { public LFUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (!keyToVal.containsKey(key)) return -1; final int freq = keyToFreq.get(key); freqToLRUKeys.get(freq).remove(key); if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) { freqToLRUKeys.remove(freq); ++minFreq; } // Increase key's freq by 1 // Add this key to next freq's list putFreq(key, freq + 1); return keyToVal.get(key); } public void put(int key, int value) { if (capacity == 0) return; if (keyToVal.containsKey(key)) { keyToVal.put(key, value); get(key); // Update key's count return; } if (keyToVal.size() == capacity) { // Evict LRU key from the minFreq list final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next(); freqToLRUKeys.get(minFreq).remove(keyToEvict); keyToVal.remove(keyToEvict); } minFreq = 1; putFreq(key, minFreq); // Add new key and freq keyToVal.put(key, value); // Add new key and value } private int capacity; private int minFreq = 0; private Map keyToVal = new HashMap<>(); private Map keyToFreq = new HashMap<>(); private Map> freqToLRUKeys = new HashMap<>(); private void putFreq(int key, int freq) { keyToFreq.put(key, freq); freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>()); freqToLRUKeys.get(freq).add(key); } }",55,55 ,"import json def convert_dict_to_sorted_json(data_dict): """""" Converts a dictionary to a JSON string sorted by keys with an indent of 4 spaces. """""" try: # sort_keys=True: Alphabetizes the keys # indent=4: Adds 4 spaces for nested members json_output = json.dumps(data_dict, sort_keys=True, indent=4) print(""Successfully converted to Sorted JSON:"") print(json_output) return json_output except (TypeError, ValueError) as e: print(f""Error converting object: {e}"") return None # Example dictionary with unsorted keys blog_post = { ""title"": ""Python JSON Guide"", ""author"": ""Jane Doe"", ""views"": 1500, ""tags"": [""python"", ""json"", ""tutorial""], ""published"": True, ""category"": ""Programming"" } # Execute conversion convert_dict_to_sorted_json(blog_post)",1.0,GEMINI,Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.,python,"import json def convert_dict_to_sorted_json(data_dict): """""" Converts a dictionary to a JSON string sorted by keys with an indent of 4 spaces. """""" try: # sort_keys=True: Alphabetizes the keys # indent=4: Adds 4 spaces for nested members json_output = json.dumps(data_dict, sort_keys=True, indent=4) print(""Successfully converted to Sorted JSON:"") print(json_output) return json_output except (TypeError, ValueError) as e: print(f""Error converting object: {e}"") return None # Example dictionary with unsorted keys blog_post = { ""title"": ""Python JSON Guide"", ""author"": ""Jane Doe"", ""views"": 1500, ""tags"": [""python"", ""json"", ""tutorial""], ""published"": True, ""category"": ""Programming"" } # Execute conversion convert_dict_to_sorted_json(blog_post)",32,32 ,"import numpy as np print(np.logaddexp(np.log(1e-50), np.log(2.5e-50))) print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50))) ",1.0,PERPLEXITY,"Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.",python,"import numpy as np print(np.logaddexp(np.log(1e-50), np.log(2.5e-50))) print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50)))",4,4 ,"interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println(""Drawing Circle""); } } class Rectangle implements Shape { public void draw() { System.out.println(""Drawing Rectangle""); } } public class ShapeFactory { public static Shape createShape(String type) { switch (type.toLowerCase()) { case ""circle"": return new Circle(); case ""rectangle"": return new Rectangle(); default: throw new IllegalArgumentException(""Unknown shape""); } } } ",1.0,PERPLEXITY,Create a Java factory method pattern to create different Shape objects based on string input,java,"interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println(""Drawing Circle""); } } class Rectangle implements Shape { public void draw() { System.out.println(""Drawing Rectangle""); } } public class ShapeFactory { public static Shape createShape(String type) { switch (type.toLowerCase()) { case ""circle"": return new Circle(); case ""rectangle"": return new Rectangle(); default: throw new IllegalArgumentException(""Unknown shape""); } } }",16,16 ,"// Define the Rectangle class public class Rectangle { // Private instance variables private double length; private double width; // Parameterized constructor public Rectangle(double length, double width) { // Initialize length with the provided parameter this.length = length; // Initialize width with the provided parameter this.width = width; } // Copy constructor public Rectangle(Rectangle rectangle) { // Initialize length with the length of the provided rectangle object this.length = rectangle.length; // Initialize width with the width of the provided rectangle object this.width = rectangle.width; } // Main method to test the Rectangle class public static void main(String[] args) { // Create a new Rectangle object using the parameterized constructor Rectangle rect1 = new Rectangle(12.5, 4.5); // Print the values of the instance variables for rect1 System.out.println(""Rectangle 1 Length: "" + rect1.length); System.out.println(""Rectangle 1 Width: "" + rect1.width); // Create a new Rectangle object using the copy constructor Rectangle rect2 = new Rectangle(rect1); // Print the values of the instance variables for rect2 System.out.println(""Rectangle 2 Length: "" + rect2.length); System.out.println(""Rectangle 2 Width: "" + rect2.width); } } ",0.0,WE3RESOURCE,,java,"// Define the Rectangle class public class Rectangle { // Private instance variables private double length; private double width; // Parameterized constructor public Rectangle(double length, double width) { // Initialize length with the provided parameter this.length = length; // Initialize width with the provided parameter this.width = width; } // Copy constructor public Rectangle(Rectangle rectangle) { // Initialize length with the length of the provided rectangle object this.length = rectangle.length; // Initialize width with the width of the provided rectangle object this.width = rectangle.width; } // Main method to test the Rectangle class public static void main(String[] args) { // Create a new Rectangle object using the parameterized constructor Rectangle rect1 = new Rectangle(12.5, 4.5); // Print the values of the instance variables for rect1 System.out.println(""Rectangle 1 Length: "" + rect1.length); System.out.println(""Rectangle 1 Width: "" + rect1.width); // Create a new Rectangle object using the copy constructor Rectangle rect2 = new Rectangle(rect1); // Print the values of the instance variables for rect2 System.out.println(""Rectangle 2 Length: "" + rect2.length); System.out.println(""Rectangle 2 Width: "" + rect2.width); } }",37,37 ,"def mergeTwoLists(l1, l2): dummy = curr = ListNode(0) while l1 and l2: if l1.val < l2.val: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next curr.next = l1 or l2 return dummy.next ",1.0,GPT,"Solve the problem ""Merge Two Sorted Linked Lists"". Given two sorted linked lists, merge them into one sorted list and return its head.",python,"def mergeTwoLists(l1, l2): dummy = curr = ListNode(0) while l1 and l2: if l1.val < l2.val: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next curr.next = l1 or l2 return dummy.next",14,14 ,"import java.util.Scanner; class MinMaxInArray { int getMax(int[]inputArray) { int maxValue=inputArray[0]; for(int i=1;imaxValue) { maxValue=inputArray[i]; } } return maxValue; } int getMin(int[]inputArray) { int minValue=inputArray[0]; for(int i=1;imaxValue) { maxValue=inputArray[i]; } } return maxValue; } int getMin(int[]inputArray) { int minValue=inputArray[0]; for(int i=1;i=0;i--) { revwords[j]=words[i]; System.out.print(revwords[j]+"" ""); j++; } } }",0.0,IPSGWALIOR.ORG,,java,"public class ReverseWord { public static void main(String[] args) { String input=""Welcome to Java Session""; String[] words=input.split("" ""); String[] revwords=new String[words.length]; int j=0; for(int i=words.length-1;i>=0;i--) { revwords[j]=words[i]; System.out.print(revwords[j]+"" ""); j++; } } }",17,17 ,""""""" Definition of Interval: class Interval(object): def __init__(self, start, end): self.start = start self.end = end """""" class Solution: def minMeetingRooms(self, intervals: List[Interval]) -> int: time = [] for i in intervals: time.append((i.start, 1)) time.append((i.end, -1)) time.sort(key=lambda x: (x[0], x[1])) res = count = 0 for t in time: count += t[1] res = max(res, count) return res",0.0,GFG,,python,""""""" Definition of Interval: class Interval(object): def __init__(self, start, end): self.start = start self.end = end """""" class Solution: def minMeetingRooms(self, intervals: List[Interval]) -> int: time = [] for i in intervals: time.append((i.start, 1)) time.append((i.end, -1)) time.sort(key=lambda x: (x[0], x[1])) res = count = 0 for t in time: count += t[1] res = max(res, count) return res",22,22 ,"import java.util.List; public class ParallelStreamExample { public static long sumSquaresParallel(List numbers) { return numbers.parallelStream() .mapToLong(n -> (long) n * n) .sum(); } } ",1.0,PERPLEXITY,Calculate sum of squares using parallel streams on a large list of numbers,java,"import java.util.List; public class ParallelStreamExample { public static long sumSquaresParallel(List numbers) { return numbers.parallelStream() .mapToLong(n -> (long) n * n) .sum(); } }",8,8 ,"from collections import Counter def checkInclusion(s1, s2): if len(s1) > len(s2): return False s1_count = Counter(s1) window = Counter(s2[:len(s1)]) if s1_count == window: return True for i in range(len(s1), len(s2)): window[s2[i]] += 1 window[s2[i - len(s1)]] -= 1 if window[s2[i - len(s1)]] == 0: del window[s2[i - len(s1)]] if window == s1_count: return True return False ",1.0,GPT,"Given two strings s1 and s2, return true if s2 contains a permutation of s1. Use a sliding window approach.",python,"from collections import Counter def checkInclusion(s1, s2): if len(s1) > len(s2): return False s1_count = Counter(s1) window = Counter(s2[:len(s1)]) if s1_count == window: return True for i in range(len(s1), len(s2)): window[s2[i]] += 1 window[s2[i - len(s1)]] -= 1 if window[s2[i - len(s1)]] == 0: del window[s2[i - len(s1)]] if window == s1_count: return True return False",21,21 ,"class Solution { public String[] findRestaurant(String[] list1, String[] list2) { int min = 10000; ArrayList arr = new ArrayList<>(); for (int i = 0; i < list1.length; i++) for (int j = 0; j < list2.length; j++) if (list1[i].equals(list2[j])) { if (i + j <= min) { if (i + j < min) { arr.clear(); min = i + j; } arr.add(list1[i]); } break; } return arr.toArray(new String[0]); } }",0.0,leetcode,,java,"class Solution { public String[] findRestaurant(String[] list1, String[] list2) { int min = 10000; ArrayList arr = new ArrayList<>(); for (int i = 0; i < list1.length; i++) for (int j = 0; j < list2.length; j++) if (list1[i].equals(list2[j])) { if (i + j <= min) { if (i + j < min) { arr.clear(); min = i + j; } arr.add(list1[i]); } break; } return arr.toArray(new String[0]); } }",19,19 ,"def factorial(n): if n == 0: return 1 return n * factorial(n - 1) # General usage print(factorial(6)) # Output: 720 ",1.0,PERPLEXITY,Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.,python,"def factorial(n): if n == 0: return 1 return n * factorial(n - 1) # General usage print(factorial(6)) # Output: 720",7,7 ,"static List anagrams(String s,String p){ int[] c=new int[26]; for(char x:p.toCharArray()) c[x-'a']++; int l=0,r=0,cnt=p.length(); List res=new ArrayList<>(); while(r0) cnt--; if(cnt==0) res.add(l); if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++; } return res; } ",1.0,GPT,Find all start indices of p's anagrams in s.,java,"static List anagrams(String s,String p){ int[] c=new int[26]; for(char x:p.toCharArray()) c[x-'a']++; int l=0,r=0,cnt=p.length(); List res=new ArrayList<>(); while(r0) cnt--; if(cnt==0) res.add(l); if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++; } return res; }",12,12 ,"# Importing the NumPy library import numpy as np # Creating an array from 0 to 9 x = np.arange(10) # Displaying the original array print(""Original array:"") print(x) # Performing element-wise division of the array by 3 using true_divide function print(""Division of the array inputs, element-wise:"") print(np.true_divide(x, 3)) ",0.0,W3RESOURCE,,python,"# Importing the NumPy library import numpy as np # Creating an array from 0 to 9 x = np.arange(10) # Displaying the original array print(""Original array:"") print(x) # Performing element-wise division of the array by 3 using true_divide function print(""Division of the array inputs, element-wise:"") print(np.true_divide(x, 3)) ",13,13 ,"class Solution { public List findDisappearedNumbers(int[] nums) { Set numSet = new HashSet<>(); for (int num : nums) { numSet.add(num); } List result = new ArrayList<>(); for (int i = 1; i <= nums.length; i++) { if (!numSet.contains(i)) { result.add(i); } } return result; } }",0.0,leetcode,,java,"class Solution { public List findDisappearedNumbers(int[] nums) { Set numSet = new HashSet<>(); for (int num : nums) { numSet.add(num); } List result = new ArrayList<>(); for (int i = 1; i <= nums.length; i++) { if (!numSet.contains(i)) { result.add(i); } } return result; } }",17,17 ,"import java.util.Scanner; class LinearSearch { public static void main(String args[]) { int i, num, searchval, array[]; Scanner in = new Scanner(System.in); System.out.println(""Enter number of elements""); num = in.nextInt(); array = new int[num]; System.out.println(""Enter "" + num + "" integers""); for (i = 0; i < num; i++) array[i] = in.nextInt(); System.out.println(""Enter the search value:""); searchval = in.nextInt(); in.close(); for (i = 0; i < num; i++) { if (array[i] == searchval) { System.out.println(searchval + "" is present at location "" + (i + 1)); break; } } if (i == num) System.out.println(searchval + "" is not exist in array.""); } ",0.0,IPSGWALIOR.ORG,,java,"import java.util.Scanner; class LinearSearch { public static void main(String args[]) { int i, num, searchval, array[]; Scanner in = new Scanner(System.in); System.out.println(""Enter number of elements""); num = in.nextInt(); array = new int[num]; System.out.println(""Enter "" + num + "" integers""); for (i = 0; i < num; i++) array[i] = in.nextInt(); System.out.println(""Enter the search value:""); searchval = in.nextInt(); in.close(); for (i = 0; i < num; i++) { if (array[i] == searchval) { System.out.println(searchval + "" is present at location "" + (i + 1)); break; } } if (i == num) System.out.println(searchval + "" is not exist in array.""); }",28,28 ,"from bs4 import BeautifulSoup import requests import random def get_imd_movies(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') movies = soup.find_all(""td"", class_=""titleColumn"") random.shuffle(movies) return movies def get_imd_summary(url): movie_page = requests.get(url) soup = BeautifulSoup(movie_page.text, 'html.parser') return soup.find(""div"", class_=""summary_text"").contents[0].strip() def get_imd_movie_info(movie): movie_title = movie.a.contents[0] movie_year = movie.span.contents[0] movie_url = 'http://www.imdb.com' + movie.a['href'] return movie_title, movie_year, movie_url def imd_movie_picker(): ctr=0 print(""--------------------------------------------"") for movie in get_imd_movies('http://www.imdb.com/chart/top'): movie_title, movie_year, movie_url = get_imd_movie_info(movie) movie_summary = get_imd_summary(movie_url) print(movie_title, movie_year) print(movie_summary) print(""--------------------------------------------"") ctr=ctr+1 if (ctr==10): break; if __name__ == '__main__': imd_movie_picker() ",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup import requests import random def get_imd_movies(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') movies = soup.find_all(""td"", class_=""titleColumn"") random.shuffle(movies) return movies def get_imd_summary(url): movie_page = requests.get(url) soup = BeautifulSoup(movie_page.text, 'html.parser') return soup.find(""div"", class_=""summary_text"").contents[0].strip() def get_imd_movie_info(movie): movie_title = movie.a.contents[0] movie_year = movie.span.contents[0] movie_url = 'http://www.imdb.com' + movie.a['href'] return movie_title, movie_year, movie_url def imd_movie_picker(): ctr=0 print(""--------------------------------------------"") for movie in get_imd_movies('http://www.imdb.com/chart/top'): movie_title, movie_year, movie_url = get_imd_movie_info(movie) movie_summary = get_imd_summary(movie_url) print(movie_title, movie_year) print(movie_summary) print(""--------------------------------------------"") ctr=ctr+1 if (ctr==10): break; if __name__ == '__main__': imd_movie_picker()",34,34 ,"# Define a function named 'sum' that takes a list of numbers as input def sum(numbers): # Initialize a variable 'total' to store the sum of numbers, starting at 0 total = 0 # Iterate through each element 'x' in the 'numbers' list for x in numbers: # Add the current element 'x' to the 'total' total += x # Return the final sum stored in the 'total' variable return total # Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7) print(sum((8, 2, 3, 0, 7))) ",0.0,,,python,"# Define a function named 'sum' that takes a list of numbers as input def sum(numbers): # Initialize a variable 'total' to store the sum of numbers, starting at 0 total = 0 # Iterate through each element 'x' in the 'numbers' list for x in numbers: # Add the current element 'x' to the 'total' total += x # Return the final sum stored in the 'total' variable return total # Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7) print(sum((8, 2, 3, 0, 7))) ",15,15 ,"def isInterleave(s1, s2, s3): if len(s1) + len(s2) != len(s3): return False dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)] dp[0][0] = True for i in range(len(s1) + 1): for j in range(len(s2) + 1): if i > 0: dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1] if j > 0: dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1] return dp[-1][-1] ",1.0,GPT,"Solve the problem ""Interleaving String"". Given strings s1, s2, and s3, determine if s3 is formed by interleaving s1 and s2.",python,"def isInterleave(s1, s2, s3): if len(s1) + len(s2) != len(s3): return False dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)] dp[0][0] = True for i in range(len(s1) + 1): for j in range(len(s2) + 1): if i > 0: dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1] if j > 0: dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1] return dp[-1][-1]",15,15 ,"#https://bit.ly/2NyxdAG from bs4 import BeautifulSoup import requests import re # Download IMDB's Top 250 data url = 'http://www.imdb.com/chart/top' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') movies = soup.select('td.titleColumn') links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')] crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')] ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')] votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')] imdb = [] # Store each item into dictionary (data), then put those into a list (imdb) for index in range(0, len(movies)): # Seperate movie into: 'place', 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\((.*?)\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {""movie_title"": movie_title, ""year"": year, ""place"": place, ""star_cast"": crew[index], ""rating"": ratings[index], ""vote"": votes[index], ""link"": links[index]} imdb.append(data) for item in imdb: print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast']) ",0.0,WERESOURCE,,python,"#https://bit.ly/2NyxdAG from bs4 import BeautifulSoup import requests import re # Download IMDB's Top 250 data url = 'http://www.imdb.com/chart/top' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') movies = soup.select('td.titleColumn') links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')] crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')] ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')] votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')] imdb = [] # Store each item into dictionary (data), then put those into a list (imdb) for index in range(0, len(movies)): # Seperate movie into: 'place', 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\((.*?)\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {""movie_title"": movie_title, ""year"": year, ""place"": place, ""star_cast"": crew[index], ""rating"": ratings[index], ""vote"": votes[index], ""link"": links[index]} imdb.append(data) for item in imdb: print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast'])",37,37 ,"// Define the Car class public class Car { // Private instance variables private String make; private String model; private int year; // Parameterized constructor with default values public Car(String make, String model, int year) { // Initialize make with the provided parameter or a default value this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make; // Initialize model with the provided parameter or a default value this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model; // Initialize year with the provided parameter or a default value this.year = (year <= 0) ? 2000 : year; } // Main method to test the Car class public static void main(String[] args) { // Create a new Car object with valid data Car car1 = new Car(""Toyota"", ""Corolla"", 2021); // Print the values of the instance variables for car1 System.out.println(""Car 1 Make: "" + car1.make); System.out.println(""Car 1 Model: "" + car1.model); System.out.println(""Car 1 Year: "" + car1.year); // Create a new Car object with some invalid data Car car2 = new Car("""", """", -1); // Print the values of the instance variables for car2 System.out.println(""Car 2 Make: "" + car2.make); System.out.println(""Car 2 Model: "" + car2.model); System.out.println(""Car 2 Year: "" + car2.year); } } ",0.0,WERESOURCE,,java,"// Define the Car class public class Car { // Private instance variables private String make; private String model; private int year; // Parameterized constructor with default values public Car(String make, String model, int year) { // Initialize make with the provided parameter or a default value this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make; // Initialize model with the provided parameter or a default value this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model; // Initialize year with the provided parameter or a default value this.year = (year <= 0) ? 2000 : year; } // Main method to test the Car class public static void main(String[] args) { // Create a new Car object with valid data Car car1 = new Car(""Toyota"", ""Corolla"", 2021); // Print the values of the instance variables for car1 System.out.println(""Car 1 Make: "" + car1.make); System.out.println(""Car 1 Model: "" + car1.model); System.out.println(""Car 1 Year: "" + car1.year); // Create a new Car object with some invalid data Car car2 = new Car("""", """", -1); // Print the values of the instance variables for car2 System.out.println(""Car 2 Make: "" + car2.make); System.out.println(""Car 2 Model: "" + car2.model); System.out.println(""Car 2 Year: "" + car2.year); } }",34,34 ,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers def is_even_num(l): # Create an empty list 'enum' to store even numbers enum = [] # Iterate through each number 'n' in the input list 'l' for n in l: # Check if the number 'n' is even (divisible by 2 without a remainder) if n % 2 == 0: # If 'n' is even, append it to the 'enum' list enum.append(n) # Return the list 'enum' containing even numbers return enum # Print the result of calling the 'is_even_num' function with a list of numbers print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",0.0,W3RESOURCE,,python,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers def is_even_num(l): # Create an empty list 'enum' to store even numbers enum = [] # Iterate through each number 'n' in the input list 'l' for n in l: # Check if the number 'n' is even (divisible by 2 without a remainder) if n % 2 == 0: # If 'n' is even, append it to the 'enum' list enum.append(n) # Return the list 'enum' containing even numbers return enum # Print the result of calling the 'is_even_num' function with a list of numbers print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",17,17 ,"import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor from urllib.parse import urljoin def fetch(url): try: return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"") except: return None def scrape(urls, workers=10): with ThreadPoolExecutor(workers) as t: return [s for s in t.map(fetch, urls) if s] start = ""https://example.com"" soup = fetch(start) links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")} pages = scrape(links) for p in pages: print(p.title.string if p.title else ""No title"") ",1.0,GPT,give me the python3 code for multithread webscrapper in an more efficient way with shorter lines of code to implement ,python,"import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor from urllib.parse import urljoin def fetch(url): try: return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"") except: return None def scrape(urls, workers=10): with ThreadPoolExecutor(workers) as t: return [s for s in t.map(fetch, urls) if s] start = ""https://example.com"" soup = fetch(start) links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")} pages = scrape(links) for p in pages: print(p.title.string if p.title else ""No title"")",23,23 ,"class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: dp = defaultdict(int) dp[0] = 1 for num in nums: next_dp = defaultdict(int) for total, count in dp.items(): next_dp[total + num] += count next_dp[total - num] += count dp = next_dp return dp[target]",0.0,GFG,,python,"class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: dp = defaultdict(int) dp[0] = 1 for num in nums: next_dp = defaultdict(int) for total, count in dp.items(): next_dp[total + num] += count next_dp[total - num] += count dp = next_dp return dp[target]",13,13 ,"# Define a function that returns the maximum of two numbers def max_of_two(x, y): # Check if x is greater than y if x > y: # If x is greater, return x return x # If y is greater or equal to x, return y return y # Define a function that returns the maximum of three numbers def max_of_three(x, y, z): # Call max_of_two function to find the maximum of y and z, # then compare it with x to find the overall maximum return max_of_two(x, max_of_two(y, z)) # Print the result of calling max_of_three function with arguments 3, 6, and -5 print(max_of_three(3, 6, -5)) ",0.0,W3RESOURCE,,python,"# Define a function that returns the maximum of two numbers def max_of_two(x, y): # Check if x is greater than y if x > y: # If x is greater, return x return x # If y is greater or equal to x, return y return y # Define a function that returns the maximum of three numbers def max_of_three(x, y, z): # Call max_of_two function to find the maximum of y and z, # then compare it with x to find the overall maximum return max_of_two(x, max_of_two(y, z)) # Print the result of calling max_of_three function with arguments 3, 6, and -5 print(max_of_three(3, 6, -5)) ",17,17 ,"import java.util.*; import java.util.stream.Collectors; public class GroupingExample { public static Map> groupByDept(List employees) { return employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); } } class Employee { private String department; public String getDepartment() { return department; } } ",1.0,PERPLEXITY,Use Java Collectors.groupingBy to group list of employees by department,java,"import java.util.*; import java.util.stream.Collectors; public class GroupingExample { public static Map> groupByDept(List employees) { return employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); } } class Employee { private String department; public String getDepartment() { return department; } }",9,9 ,"class NullMatrix { public static void main(String args[]) { int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} }; boolean setValue = true; abc: for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { if(a[i][j] != 0) { setValue = false; break abc; } } } System.out.println(""The Given Matrix Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } if(setValue == true) { System.out.println(""The Given Matrix is a Null Matrix""); } else { System.out.println(""The Given Matrix is not a Null Matrix""); } } } ",0.0,IPSGWALIOR.ORG,,java,"class NullMatrix { public static void main(String args[]) { int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} }; boolean setValue = true; abc: for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { if(a[i][j] != 0) { setValue = false; break abc; } } } System.out.println(""The Given Matrix Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } if(setValue == true) { System.out.println(""The Given Matrix is a Null Matrix""); } else { System.out.println(""The Given Matrix is not a Null Matrix""); } } }",37,37 ,"class Solution: def canJump(self, nums: List[int]) -> bool: goal = len(nums) - 1 for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= goal: goal = i return goal == 0",0.0,GFG,,python,"class Solution: def canJump(self, nums: List[int]) -> bool: goal = len(nums) - 1 for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= goal: goal = i return goal == 0",8,8 ,"public void deadlock() { String r1 = ""r1"", r2 = ""r2""; new Thread(() -> { synchronized(r1) { synchronized(r2) {} } }).start(); new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start(); }",1.0,GEMINI,Write a Java program that results in a deadlock.,java,"public void deadlock() { String r1 = ""r1"", r2 = ""r2""; new Thread(() -> { synchronized(r1) { synchronized(r2) {} } }).start(); new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start(); }",5,5 ,"# Define a function named 'string_reverse' that takes a string 'str1' as input def string_reverse(str1): # Initialize an empty string 'rstr1' to store the reversed string rstr1 = '' # Calculate the length of the input string 'str1' index = len(str1) # Execute a while loop until 'index' becomes 0 while index > 0: # Concatenate the character at index - 1 of 'str1' to 'rstr1' rstr1 += str1[index - 1] # Decrement the 'index' by 1 for the next iteration index = index - 1 # Return the reversed string stored in 'rstr1' return rstr1 # Print the result of calling the 'string_reverse' function with the input string '1234abcd' print(string_reverse('1234abcd'))",0.0,W3RESOURCE,,python,"# Define a function named 'string_reverse' that takes a string 'str1' as input def string_reverse(str1): # Initialize an empty string 'rstr1' to store the reversed string rstr1 = '' # Calculate the length of the input string 'str1' index = len(str1) # Execute a while loop until 'index' becomes 0 while index > 0: # Concatenate the character at index - 1 of 'str1' to 'rstr1' rstr1 += str1[index - 1] # Decrement the 'index' by 1 for the next iteration index = index - 1 # Return the reversed string stored in 'rstr1' return rstr1 # Print the result of calling the 'string_reverse' function with the input string '1234abcd' print(string_reverse('1234abcd'))",21,21 ,"import java.util.HashMap; public class Fibonacci { private static HashMap memo = new HashMap<>(); public static long fib(int n) { if (n <= 1) return n; if (memo.containsKey(n)) return memo.get(n); long result = fib(n - 1) + fib(n - 2); memo.put(n, result); return result; } } ",1.0,PERPLEXITY,Write a Java Fibonacci function using recursion with HashMap memoization for efficiency,java,"import java.util.HashMap; public class Fibonacci { private static HashMap memo = new HashMap<>(); public static long fib(int n) { if (n <= 1) return n; if (memo.containsKey(n)) return memo.get(n); long result = fib(n - 1) + fib(n - 2); memo.put(n, result); return result; } }",11,11 ,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') temp = requests.get('https://twitter.com/'+handle) bs = BeautifulSoup(temp.text,'lxml') try: follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'}) followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'}) print(""Number of followers: {} "".format(followers.get('data-count'))) except: print('Account name not found...') ",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') temp = requests.get('https://twitter.com/'+handle) bs = BeautifulSoup(temp.text,'lxml') try: follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'}) followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'}) print(""Number of followers: {} "".format(followers.get('data-count'))) except: print('Account name not found...')",11,11 ,"def combinationSum(candidates, target): res = [] def backtrack(i, total, cur): if total == target: res.append(cur[:]) return if i >= len(candidates) or total > target: return cur.append(candidates[i]) backtrack(i, total + candidates[i], cur) cur.pop() backtrack(i + 1, total, cur) backtrack(0, 0, []) return res ",1.0,GPT,"Solve the problem ""Combination Sum"". Given an array of distinct integers candidates and a target, return all unique combinations where candidates sum to target. Each number may be used unlimited times.",python,"def combinationSum(candidates, target): res = [] def backtrack(i, total, cur): if total == target: res.append(cur[:]) return if i >= len(candidates) or total > target: return cur.append(candidates[i]) backtrack(i, total + candidates[i], cur) cur.pop() backtrack(i + 1, total, cur) backtrack(0, 0, []) return res",17,17 ,"public class VowelswithStar { public static void main(String[] args) { String string = ""Welcome to Candid Java Programming""; //Input String System.out.println(""Input String : ""+string); //Displaying Input String string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star System.out.println(string); //Display the word after replacement } } ",0.0,IPSGWALIOR.ORG,,java,"public class VowelswithStar { public static void main(String[] args) { String string = ""Welcome to Candid Java Programming""; //Input String System.out.println(""Input String : ""+string); //Displaying Input String string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star System.out.println(string); //Display the word after replacement } }",11,11 ,"def is_even_num(l): return [n for n in l if n % 2 == 0] # Example usage print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",1.0,PERPLEXITY,Write a Python program to print the even numbers from a given list.,python,"def is_even_num(l): return [n for n in l if n % 2 == 0] # Example usage print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))",5,5 ,"import tweepy # Replace with your actual bearer token from X Developer Portal BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE' # Initialize the client with bearer token (sufficient for read access) client = tweepy.Client(bearer_token=BEARER_TOKEN) # Input for Twitter username (without @) username = input(""Enter Twitter username: "") try: # Get the user by username with public_metrics user = client.get_user(username=username, user_fields=['public_metrics']) if user.data: # Access public_metrics.following count public_metrics = user.data.public_metrics following_count = public_metrics['following'] print(f""@{username} is following {following_count:,} accounts."") else: print(""User not found."") except tweepy.TweepyException as e: print(f""Error: {e}"") ",1.0,PERPLEXITY,Write a Python program to get the number of following on a Twitter account.,python,"import tweepy # Replace with your actual bearer token from X Developer Portal BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE' # Initialize the client with bearer token (sufficient for read access) client = tweepy.Client(bearer_token=BEARER_TOKEN) # Input for Twitter username (without @) username = input(""Enter Twitter username: "") try: # Get the user by username with public_metrics user = client.get_user(username=username, user_fields=['public_metrics']) if user.data: # Access public_metrics.following count public_metrics = user.data.public_metrics following_count = public_metrics['following'] print(f""@{username} is following {following_count:,} accounts."") else: print(""User not found."") except tweepy.TweepyException as e: print(f""Error: {e}"")",26,26 ,"public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] numbers = new int[10]; for (int i = 0; i 0) cows++; numbers[s] ++; numbers[g] --; } } return bulls + ""A"" + cows + ""B""; }",0.0,leetcode,,java,"public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] numbers = new int[10]; for (int i = 0; i 0) cows++; numbers[s] ++; numbers[g] --; } } return bulls + ""A"" + cows + ""B""; }",17,17 ,"from collections import Counter def topKFrequent(nums, k): count = Counter(nums) buckets = [[] for _ in range(len(nums) + 1)] for num, freq in count.items(): buckets[freq].append(num) res = [] for i in range(len(buckets) - 1, 0, -1): for num in buckets[i]: res.append(num) if len(res) == k: return res ",1.0,GPT,"Given an integer array nums and an integer k, return the k most frequent elements. The solution must be better than O(n log n). Provide: - Optimal approach - Python code using efficient data structures",python,"from collections import Counter def topKFrequent(nums, k): count = Counter(nums) buckets = [[] for _ in range(len(nums) + 1)] for num, freq in count.items(): buckets[freq].append(num) res = [] for i in range(len(buckets) - 1, 0, -1): for num in buckets[i]: res.append(num) if len(res) == k: return res",15,15 ,"# Import the asyncio library for asynchronous programming import asyncio # Import nest_asyncio to handle nested event loops import nest_asyncio # Apply nest_asyncio to allow nested event loops nest_asyncio.apply() # Define the TaskScheduler class class TaskScheduler: def __init__(self): # Initialize an empty list to store tasks self.tasks = [] def schedule(self, coro, *args): """"""Schedule a coroutine with given arguments."""""" # Append the coroutine with its arguments to the tasks list self.tasks.append(coro(*args)) async def run(self): """"""Run all scheduled tasks concurrently."""""" # Use asyncio.gather to run all tasks concurrently await asyncio.gather(*self.tasks) # Define an example coroutine that simulates a task async def example_task(name, duration): """"""An example coroutine that simulates a task."""""" # Print a message when the task starts print(f""Task {name} started, will take {duration} seconds."") # Simulate a delay using asyncio.sleep await asyncio.sleep(duration) # Print a message when the task finishes print(f""Task {name} finished."") # Define the main coroutine for example usage async def main(): # Create an instance of TaskScheduler scheduler = TaskScheduler() # Schedule example tasks with different durations scheduler.schedule(example_task, ""A"", 2) scheduler.schedule(example_task, ""B"", 3) scheduler.schedule(example_task, ""C"", 1) # Run all scheduled tasks concurrently await scheduler.run() # Run the main function using asyncio's event loop asyncio.run(main())",0.0,W3RESOURCE,,python,"# Import the asyncio library for asynchronous programming import asyncio # Import nest_asyncio to handle nested event loops import nest_asyncio # Apply nest_asyncio to allow nested event loops nest_asyncio.apply() # Define the TaskScheduler class class TaskScheduler: def __init__(self): # Initialize an empty list to store tasks self.tasks = [] def schedule(self, coro, *args): """"""Schedule a coroutine with given arguments."""""" # Append the coroutine with its arguments to the tasks list self.tasks.append(coro(*args)) async def run(self): """"""Run all scheduled tasks concurrently."""""" # Use asyncio.gather to run all tasks concurrently await asyncio.gather(*self.tasks) # Define an example coroutine that simulates a task async def example_task(name, duration): """"""An example coroutine that simulates a task."""""" # Print a message when the task starts print(f""Task {name} started, will take {duration} seconds."") # Simulate a delay using asyncio.sleep await asyncio.sleep(duration) # Print a message when the task finishes print(f""Task {name} finished."") # Define the main coroutine for example usage async def main(): # Create an instance of TaskScheduler scheduler = TaskScheduler() # Schedule example tasks with different durations scheduler.schedule(example_task, ""A"", 2) scheduler.schedule(example_task, ""B"", 3) scheduler.schedule(example_task, ""C"", 1) # Run all scheduled tasks concurrently await scheduler.run() # Run the main function using asyncio's event loop asyncio.run(main())",50,50 ,"from collections import OrderedDict class LRUCache: def __init__(self, cap): self.cap, self.d = cap, OrderedDict() def get(self, k): if k not in self.d: return -1 self.d.move_to_end(k) return self.d[k] def put(self, k, v): if k in self.d: self.d.move_to_end(k) self.d[k] = v if len(self.d) > self.cap: self.d.popitem(last=False) ",1.0,GPT,Write a Python program to create a caching system with support for LRU eviction policy TO PASS ALL THE TEST CASES,python,"from collections import OrderedDict class LRUCache: def __init__(self, cap): self.cap, self.d = cap, OrderedDict() def get(self, k): if k not in self.d: return -1 self.d.move_to_end(k) return self.d[k] def put(self, k, v): if k in self.d: self.d.move_to_end(k) self.d[k] = v if len(self.d) > self.cap: self.d.popitem(last=False)",16,16 ,"//IncrementThread.java public class IncrementThread extends Thread { private Counter counter; private int incrementsPerThread; public IncrementThread(Counter counter, int incrementsPerThread) { this.counter = counter; this.incrementsPerThread = incrementsPerThread; } @Override public void run() { for (int i = 0; i < incrementsPerThread; i++) { counter.increment(); } } } ",0.0,WE3RESOURCE,,java,"//IncrementThread.java public class IncrementThread extends Thread { private Counter counter; private int incrementsPerThread; public IncrementThread(Counter counter, int incrementsPerThread) { this.counter = counter; this.incrementsPerThread = incrementsPerThread; } @Override public void run() { for (int i = 0; i < incrementsPerThread; i++) { counter.increment(); } } }",15,15 ,"class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 l, r = 0, len(height) - 1 leftMax, rightMax = height[l], height[r] res = 0 while l < r: if leftMax < rightMax: l += 1 leftMax = max(leftMax, height[l]) res += leftMax - height[l] else: r -= 1 rightMax = max(rightMax, height[r]) res += rightMax - height[r] return res",0.0,GFG,,python,"class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 l, r = 0, len(height) - 1 leftMax, rightMax = height[l], height[r] res = 0 while l < r: if leftMax < rightMax: l += 1 leftMax = max(leftMax, height[l]) res += leftMax - height[l] else: r -= 1 rightMax = max(rightMax, height[r]) res += rightMax - height[r] return res",18,18 ,"class Solution { public int findShortestSubArray(int[] nums) { HashMap count = new HashMap<>(); HashMap first = new HashMap<>(); HashMap last = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; count.put(num, count.getOrDefault(num, 0) + 1); if (!first.containsKey(num)) { first.put(num, i); } last.put(num, i); } int degree = 0; for (int val : count.values()) { degree = Math.max(degree, val); } int ans = nums.length; for (int key : count.keySet()) { if (count.get(key) == degree) { ans = Math.min(ans, last.get(key) - first.get(key) + 1); } } return ans; } }",0.0,leetcode,,java,"class Solution { public int findShortestSubArray(int[] nums) { HashMap count = new HashMap<>(); HashMap first = new HashMap<>(); HashMap last = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; count.put(num, count.getOrDefault(num, 0) + 1); if (!first.containsKey(num)) { first.put(num, i); } last.put(num, i); } int degree = 0; for (int val : count.values()) { degree = Math.max(degree, val); } int ans = nums.length; for (int key : count.keySet()) { if (count.get(key) == degree) { ans = Math.min(ans, last.get(key) - first.get(key) + 1); } } return ans; } }",33,33 ,"class Solution { public List partitionLabels(String s) { Map lastOccurrence = new HashMap<>(); for (int i = 0; i < s.length(); i++) { lastOccurrence.put(s.charAt(i), i); } List result = new ArrayList<>(); int start = 0, end = 0; for (int i = 0; i < s.length(); i++) { end = Math.max(end, lastOccurrence.get(s.charAt(i))); if (i == end) { result.add(end - start + 1); start = i + 1; } } return result; } }",0.0,leetcode,,java,"class Solution { public List partitionLabels(String s) { Map lastOccurrence = new HashMap<>(); for (int i = 0; i < s.length(); i++) { lastOccurrence.put(s.charAt(i), i); } List result = new ArrayList<>(); int start = 0, end = 0; for (int i = 0; i < s.length(); i++) { end = Math.max(end, lastOccurrence.get(s.charAt(i))); if (i == end) { result.add(end - start + 1); start = i + 1; } } return result; } }",21,21 ,"import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExercise { public static void main(String[] args) { ConcurrentHashMap < String, Integer > map = new ConcurrentHashMap < > (); // Create and start the writer threads Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1)); Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2)); writerThread1.start(); writerThread2.start(); // Create and start the reader threads Thread readerThread1 = new Thread(new Reader(map, ""Thread-1"")); Thread readerThread2 = new Thread(new Reader(map, ""Thread-2"")); readerThread1.start(); readerThread2.start(); } static class Writer implements Runnable { private ConcurrentHashMap < String, Integer > map; private String threadName; private int value; public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) { this.map = map; this.threadName = threadName; this.value = value; } public void run() { for (int i = 0; i < 5; i++) { map.put(threadName, value); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Reader implements Runnable { private ConcurrentHashMap < String, Integer > map; private String threadName; public Reader(ConcurrentHashMap < String, Integer > map, String threadName) { this.map = map; this.threadName = threadName; } public void run() { for (int i = 0; i < 5; i++) { Integer value = map.get(threadName); System.out.println(""Thread "" + threadName + "" read value: "" + value); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExercise { public static void main(String[] args) { ConcurrentHashMap < String, Integer > map = new ConcurrentHashMap < > (); // Create and start the writer threads Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1)); Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2)); writerThread1.start(); writerThread2.start(); // Create and start the reader threads Thread readerThread1 = new Thread(new Reader(map, ""Thread-1"")); Thread readerThread2 = new Thread(new Reader(map, ""Thread-2"")); readerThread1.start(); readerThread2.start(); } static class Writer implements Runnable { private ConcurrentHashMap < String, Integer > map; private String threadName; private int value; public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) { this.map = map; this.threadName = threadName; this.value = value; } public void run() { for (int i = 0; i < 5; i++) { map.put(threadName, value); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Reader implements Runnable { private ConcurrentHashMap < String, Integer > map; private String threadName; public Reader(ConcurrentHashMap < String, Integer > map, String threadName) { this.map = map; this.threadName = threadName; } public void run() { for (int i = 0; i < 5; i++) { Integer value = map.get(threadName); System.out.println(""Thread "" + threadName + "" read value: "" + value); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }",64,64 ,"import heapq def findKthLargest(nums, k): return heapq.nlargest(k, nums)[-1] ",1.0,GPT,"Solve the problem ""Kth Largest Element in an Array"". Given an integer array nums and an integer k, return the kth largest element. Do not sort the entire array.",python,"import heapq def findKthLargest(nums, k): return heapq.nlargest(k, nums)[-1]",4,4 ,"class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } class Employee extends Person { String dept; double salary; Employee(String n, int a, String d, double s) { super(n, a); dept = d; salary = s; } } ",1.0,PERPLEXITY,"Define Java classes Person and Employee with inheritance, constructor chaining, and fields name, age, dept, salary",java,"class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } class Employee extends Person { String dept; double salary; Employee(String n, int a, String d, double s) { super(n, a); dept = d; salary = s; } }",10,10 ,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: dummy = node = ListNode() while list1 and list2: if list1.val < list2.val: node.next = list1 list1 = list1.next else: node.next = list2 list2 = list2.next node = node.next node.next = list1 or list2 return dummy.next",0.0,GFG,,python,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: dummy = node = ListNode() while list1 and list2: if list1.val < list2.val: node.next = list1 list1 = list1.next else: node.next = list2 list2 = list2.next node = node.next node.next = list1 or list2 return dummy.next",22,22 ,"class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class LinkedListOps { public ListNode reverse(ListNode head) { ListNode prev = null, curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } } ",1.0,PERPLEXITY,"Write Java code to reverse a singly linked list given a ListNode head, using iterative approach",java,"class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class LinkedListOps { public ListNode reverse(ListNode head) { ListNode prev = null, curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } }",15,15 ,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements def unique_list(l): # Create an empty list 'x' to store unique elements x = [] # Iterate through each element 'a' in the input list 'l' for a in l: # Check if the element 'a' is not already present in the list 'x' if a not in x: # If 'a' is not in 'x', add it to the list 'x' x.append(a) # Return the list 'x' containing unique elements return x # Print the result of calling the 'unique_list' function with a list containing duplicate elements print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",0.0,W3RESOURCE,,python,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements def unique_list(l): # Create an empty list 'x' to store unique elements x = [] # Iterate through each element 'a' in the input list 'l' for a in l: # Check if the element 'a' is not already present in the list 'x' if a not in x: # If 'a' is not in 'x', add it to the list 'x' x.append(a) # Return the list 'x' containing unique elements return x # Print the result of calling the 'unique_list' function with a list containing duplicate elements print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",17,17 ,"static int decodeWays(String s){ if(s.charAt(0)=='0') return 0; int a=1,b=1; for(int i=1;i=10&&x<=26) c+=a; a=b; b=c; } return b; } ",1.0,GPT,"You are given a string s containing only digits ('0'–'9') that represents an encoded message where: 'A' → ""1"" 'B' → ""2"" ... 'Z' → ""26"" Write a java function to determine how many different ways the string can be decoded into letters.",java,"static int decodeWays(String s){ if(s.charAt(0)=='0') return 0; int a=1,b=1; for(int i=1;i=10&&x<=26) c+=a; a=b; b=c; } return b; }",11,11 ,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') ctr = int(input('Input number of tweets to scrape: ')) res=requests.get('https://twitter.com/'+ handle) bs=BeautifulSoup(res.content,'lxml') all_tweets = bs.find_all('div',{'class':'tweet'}) if all_tweets: for tweet in all_tweets[:ctr]: context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip() content = tweet.find('div',{'class':'content'}) header = content.find('div',{'class':'stream-item-header'}) user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip() time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip() message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip() footer = content.find('div',{'class':'stream-item-footer'}) stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip() if context: print(context) print(user,time) print(message) print(stat) print() else: print(""List is empty/account name not found."") ",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') ctr = int(input('Input number of tweets to scrape: ')) res=requests.get('https://twitter.com/'+ handle) bs=BeautifulSoup(res.content,'lxml') all_tweets = bs.find_all('div',{'class':'tweet'}) if all_tweets: for tweet in all_tweets[:ctr]: context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip() content = tweet.find('div',{'class':'content'}) header = content.find('div',{'class':'stream-item-header'}) user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip() time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip() message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip() footer = content.find('div',{'class':'stream-item-footer'}) stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip() if context: print(context) print(user,time) print(message) print(stat) print() else: print(""List is empty/account name not found."")",25,25 ,"def Ordered_binary_Search(olist, item): if len(olist) == 0: return False else: midpoint = len(olist) // 2 if olist[midpoint] == item: return True else: if item < olist[midpoint]: return binarySearch(olist[:midpoint], item) else: return binarySearch(olist[midpoint+1:], item) def binarySearch(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return found print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3)) print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",0.0,W3RESOURCE,,python,"def Ordered_binary_Search(olist, item): if len(olist) == 0: return False else: midpoint = len(olist) // 2 if olist[midpoint] == item: return True else: if item < olist[midpoint]: return binarySearch(olist[:midpoint], item) else: return binarySearch(olist[midpoint+1:], item) def binarySearch(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return found print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3)) print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",34,34 ,"def isSubtree(root, subRoot): def isSame(a, b): if not a and not b: return True if not a or not b or a.val != b.val: return False return isSame(a.left, b.left) and isSame(a.right, b.right) if not root: return False if isSame(root, subRoot): return True return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot) ",1.0,GPT,"Solve the problem ""Subtree of Another Tree"". Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and values as subRoot. Provide Python solution. ",python,"def isSubtree(root, subRoot): def isSame(a, b): if not a and not b: return True if not a or not b or a.val != b.val: return False return isSame(a.left, b.left) and isSame(a.right, b.right) if not root: return False if isSame(root, subRoot): return True return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)",13,13 ,"import java.sql.*; import java.util.*; public class JdbcPool { private List pool = new ArrayList<>(); private int maxSize; public JdbcPool(int maxSize) { this.maxSize = maxSize; } public Connection getConnection() throws SQLException { if (pool.isEmpty()) { return DriverManager.getConnection(""jdbc:h2:mem:test""); } return pool.remove(0); } public void returnConnection(Connection conn) { pool.add(conn); } } ",1.0,PERPLEXITY,Implement a simple JDBC connection pool manager in Java.,java,"import java.sql.*; import java.util.*; public class JdbcPool { private List pool = new ArrayList<>(); private int maxSize; public JdbcPool(int maxSize) { this.maxSize = maxSize; } public Connection getConnection() throws SQLException { if (pool.isEmpty()) { return DriverManager.getConnection(""jdbc:h2:mem:test""); } return pool.remove(0); } public void returnConnection(Connection conn) { pool.add(conn); } }",19,19 ,"class Solution { public int findLUSlength(String[] strs) { int n = strs.length; int len = -1; HashSet set = new HashSet<>(); for(int i =0;i set = new HashSet<>(); for(int i =0;i 0; while (true) { slow = next(nums, slow); if ((nums[slow] > 0) != forward) break; fast = next(nums, fast); if ((nums[fast] > 0) != forward) break; fast = next(nums, fast); if ((nums[fast] > 0) != forward) break; if (slow == fast) { if (slow == next(nums, slow)) break; return true; } } } return false; } private int next(int[] nums, int i) { int n = nums.length; int next = (i + nums[i]) % n; if (next < 0) next += n; return next; } }",0.0,leetcode,,java,"class Solution { public boolean circularArrayLoop(int[] nums) { int n = nums.length; for (int i = 0; i < n; i++) { int slow = i, fast = i; boolean forward = nums[i] > 0; while (true) { slow = next(nums, slow); if ((nums[slow] > 0) != forward) break; fast = next(nums, fast); if ((nums[fast] > 0) != forward) break; fast = next(nums, fast); if ((nums[fast] > 0) != forward) break; if (slow == fast) { if (slow == next(nums, slow)) break; return true; } } } return false; } private int next(int[] nums, int i) { int n = nums.length; int next = (i + nums[i]) % n; if (next < 0) next += n; return next; } }",34,34 ,"import java.util.ArrayList; import java.util.List; public class Subject { private List observers = new ArrayList<>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyObservers(); } public void attach(Observer observer) { observers.add(observer); } public void notifyObservers() { for (Observer o : observers) o.update(); } } interface Observer { void update(); } ",1.0,PERPLEXITY,Implement observer pattern in Java with Subject and Observer interfaces,java,"import java.util.ArrayList; import java.util.List; public class Subject { private List observers = new ArrayList<>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyObservers(); } public void attach(Observer observer) { observers.add(observer); } public void notifyObservers() { for (Observer o : observers) o.update(); } } interface Observer { void update(); }",16,16 ,"class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0: return 0 q = deque([0]) seen = [False] * (amount + 1) seen[0] = True res = 0 while q: res += 1 for _ in range(len(q)): cur = q.popleft() for coin in coins: nxt = cur + coin if nxt == amount: return res if nxt > amount or seen[nxt]: continue seen[nxt] = True q.append(nxt) return -1",0.0,GFG,,python,"class Solution: def coinChange(self, coins: List[int], amount: int) -> int: if amount == 0: return 0 q = deque([0]) seen = [False] * (amount + 1) seen[0] = True res = 0 while q: res += 1 for _ in range(len(q)): cur = q.popleft() for coin in coins: nxt = cur + coin if nxt == amount: return res if nxt > amount or seen[nxt]: continue seen[nxt] = True q.append(nxt) return -1",24,24 ,"import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorExercise { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // Schedule a task to run after a delay of 2 seconds executor.schedule(new Task(), 2, TimeUnit.SECONDS); // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds executor.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS); // Wait for scheduled tasks to complete try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); } static class Task implements Runnable { @Override public void run() { System.out.println(""Task executed at: "" + new Date()); } } } ",0.0,WE3RESOURCE,,java,"import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorExercise { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // Schedule a task to run after a delay of 2 seconds executor.schedule(new Task(), 2, TimeUnit.SECONDS); // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds executor.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS); // Wait for scheduled tasks to complete try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); } static class Task implements Runnable { @Override public void run() { System.out.println(""Task executed at: "" + new Date()); } } }",34,34 ,"import numpy as np print(""Add:"", np.add(1.0, 4.0)) print(""Subtract:"", np.subtract(1.0, 4.0)) print(""Multiply:"", np.multiply(1.0, 4.0)) print(""Divide:"", np.divide(1.0, 4.0)) ",1.0,PERPLEXITY,"Write a NumPy program to add, subtract, multiply, divide arguments element-wise.",python,"import numpy as np print(""Add:"", np.add(1.0, 4.0)) print(""Subtract:"", np.subtract(1.0, 4.0)) print(""Multiply:"", np.multiply(1.0, 4.0)) print(""Divide:"", np.divide(1.0, 4.0))",6,6 ,"class Solution { public List majorityElement(int[] nums) { // Create a frequency map to store the count of each element Map elementCountMap = new HashMap<>(); // Iterate through the input array to count element occurrences for (int i = 0; i < nums.length; i++) { elementCountMap.put(nums[i], elementCountMap.getOrDefault(nums[i], 0) + 1); } List majorityElements = new ArrayList<>(); int threshold = nums.length / 3; // Iterate through the frequency map to identify majority elements for (Map.Entry entry : elementCountMap.entrySet()) { int element = entry.getKey(); int count = entry.getValue(); // Check if the element count is greater than the threshold if (count > threshold) { majorityElements.add(element); } } return majorityElements; } }",0.0,leetcode,,java,"class Solution { public List majorityElement(int[] nums) { // Create a frequency map to store the count of each element Map elementCountMap = new HashMap<>(); // Iterate through the input array to count element occurrences for (int i = 0; i < nums.length; i++) { elementCountMap.put(nums[i], elementCountMap.getOrDefault(nums[i], 0) + 1); } List majorityElements = new ArrayList<>(); int threshold = nums.length / 3; // Iterate through the frequency map to identify majority elements for (Map.Entry entry : elementCountMap.entrySet()) { int element = entry.getKey(); int count = entry.getValue(); // Check if the element count is greater than the threshold if (count > threshold) { majorityElements.add(element); } } return majorityElements; } }",27,27 ,"import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.params.SetParams; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class RedisDistributedLock implements Lock { private final JedisPool jedisPool; private final String lockKey; private final String lockValue; private final long leaseTimeMillis; private final long waitTimeMillis; private final ScheduledExecutorService renewalExecutor; private final ThreadLocal locked = ThreadLocal.withInitial(() -> false); private final ThreadLocal lockCount = ThreadLocal.withInitial(() -> 0); private final ConcurrentHashMap renewalTasks; private final ReentrantLock internalLock = new ReentrantLock(); private final Condition lockReleased = internalLock.newCondition(); public RedisDistributedLock(JedisPool jedisPool, String lockKey, long leaseTimeMillis, long waitTimeMillis) { this.jedisPool = jedisPool; this.lockKey = lockKey; this.lockValue = UUID.randomUUID().toString(); this.leaseTimeMillis = leaseTimeMillis; this.waitTimeMillis = waitTimeMillis; this.renewalExecutor = Executors.newSingleThreadScheduledExecutor(); this.renewalTasks = new ConcurrentHashMap<>(); } @Override public void lock() { try { if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) { throw new RuntimeException(""Failed to acquire lock within timeout""); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(""Interrupted while acquiring lock"", e); } } @Override public void lockInterruptibly() throws InterruptedException { if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) { throw new RuntimeException(""Failed to acquire lock within timeout""); } } @Override public boolean tryLock() { return tryAcquireLock(); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long waitUntil = System.currentTimeMillis() + unit.toMillis(time); while (System.currentTimeMillis() < waitUntil) { if (tryAcquireLock()) { return true; } synchronized (this) { long remaining = waitUntil - System.currentTimeMillis(); if (remaining > 0) { wait(100); // Wait and retry } } if (Thread.interrupted()) { throw new InterruptedException(); } } return false; } private boolean tryAcquireLock() { if (locked.get()) { // Reentrant lock lockCount.set(lockCount.get() + 1); return true; } try (Jedis jedis = jedisPool.getResource()) { SetParams params = SetParams.setParams() .nx() .px(leaseTimeMillis); String result = jedis.set(lockKey, lockValue, params); if (""OK"".equals(result)) { locked.set(true); lockCount.set(1); startLockRenewal(); return true; } } return false; } private void startLockRenewal() { LockRenewalTask task = new LockRenewalTask(lockKey, lockValue, leaseTimeMillis); renewalTasks.put(lockValue, task); // Schedule renewal at half the lease time renewalExecutor.scheduleAtFixedRate( task, leaseTimeMillis / 2, leaseTimeMillis / 2, TimeUnit.MILLISECONDS ); } @Override public void unlock() { if (!locked.get()) { throw new IllegalMonitorStateException(""Lock not held by current thread""); } int count = lockCount.get() - 1; lockCount.set(count); if (count == 0) { locked.set(false); releaseLock(); } } private void releaseLock() { LockRenewalTask task = renewalTasks.remove(lockValue); if (task != null) { task.cancel(); } try (Jedis jedis = jedisPool.getResource()) { // Use Lua script for atomic release String luaScript = ""if redis.call('get', KEYS[1]) == ARGV[1] then "" + "" return redis.call('del', KEYS[1]) "" + ""else "" + "" return 0 "" + ""end""; jedis.eval(luaScript, 1, lockKey, lockValue); } internalLock.lock(); try { lockReleased.signalAll(); } finally { internalLock.unlock(); } } @Override public Condition newCondition() { throw new UnsupportedOperationException(""Conditions not supported""); } private static class LockRenewalTask implements Runnable { private final String lockKey; private final String lockValue; private final long leaseTimeMillis; private volatile boolean cancelled; LockRenewalTask(String lockKey, String lockValue, long leaseTimeMillis) { this.lockKey = lockKey; this.lockValue = lockValue; this.leaseTimeMillis = leaseTimeMillis; this.cancelled = false; } @Override public void run() { if (cancelled) { return; } try (Jedis jedis = new Jedis(""localhost"")) { String luaScript = ""if redis.call('get', KEYS[1]) == ARGV[1] then "" + "" return redis.call('pexpire', KEYS[1], ARGV[2]) "" + ""else "" + "" return 0 "" + ""end""; Long result = (Long) jedis.eval( luaScript, 1, lockKey, lockValue, String.valueOf(leaseTimeMillis) ); if (result == 0) { // Lock was released or stolen cancel(); } } catch (Exception e) { // Log error but don't throw System.err.println(""Failed to renew lock: "" + e.getMessage()); } } void cancel() { this.cancelled = true; } } public void shutdown() { renewalExecutor.shutdown(); try { if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) { renewalExecutor.shutdownNow(); } } catch (InterruptedException e) { renewalExecutor.shutdownNow(); Thread.currentThread().interrupt(); } } }",1.0,DEEPSEEK,Create a distributed lock using Redis with lease time and automatic renewal.,java,"import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.params.SetParams; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class RedisDistributedLock implements Lock { private final JedisPool jedisPool; private final String lockKey; private final String lockValue; private final long leaseTimeMillis; private final long waitTimeMillis; private final ScheduledExecutorService renewalExecutor; private final ThreadLocal locked = ThreadLocal.withInitial(() -> false); private final ThreadLocal lockCount = ThreadLocal.withInitial(() -> 0); private final ConcurrentHashMap renewalTasks; private final ReentrantLock internalLock = new ReentrantLock(); private final Condition lockReleased = internalLock.newCondition(); public RedisDistributedLock(JedisPool jedisPool, String lockKey, long leaseTimeMillis, long waitTimeMillis) { this.jedisPool = jedisPool; this.lockKey = lockKey; this.lockValue = UUID.randomUUID().toString(); this.leaseTimeMillis = leaseTimeMillis; this.waitTimeMillis = waitTimeMillis; this.renewalExecutor = Executors.newSingleThreadScheduledExecutor(); this.renewalTasks = new ConcurrentHashMap<>(); } @Override public void lock() { try { if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) { throw new RuntimeException(""Failed to acquire lock within timeout""); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(""Interrupted while acquiring lock"", e); } } ... truncated ... this.leaseTimeMillis = leaseTimeMillis; this.cancelled = false; } @Override public void run() { if (cancelled) { return; } try (Jedis jedis = new Jedis(""localhost"")) { String luaScript = ""if redis.call('get', KEYS[1]) == ARGV[1] then "" + "" return redis.call('pexpire', KEYS[1], ARGV[2]) "" + ""else "" + "" return 0 "" + ""end""; Long result = (Long) jedis.eval( luaScript, 1, lockKey, lockValue, String.valueOf(leaseTimeMillis) ); if (result == 0) { // Lock was released or stolen cancel(); } } catch (Exception e) { // Log error but don't throw System.err.println(""Failed to renew lock: "" + e.getMessage()); } } void cancel() { this.cancelled = true; } } public void shutdown() { renewalExecutor.shutdown(); try { if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) { renewalExecutor.shutdownNow(); } } catch (InterruptedException e) { renewalExecutor.shutdownNow(); Thread.currentThread().interrupt(); } } }",230,101 ,"def abc(): x = 1 y = 2 str1 = ""w3resource"" print(""Python Exercises"") print(abc.__code__.co_nlocals) # Output: 3 ",1.0,PERPLEXITY,Write a Python program to detect the number of local variables declared in a function.,python,"def abc(): x = 1 y = 2 str1 = ""w3resource"" print(""Python Exercises"") print(abc.__code__.co_nlocals) # Output: 3",7,7 ,"static String minWin(String s,String t){ int[] c=new int[128]; for(char x:t.toCharArray()) c[x]++; int l=0,start=0,min=Integer.MAX_VALUE,need=t.length(); for(int r=0;r0) need--; while(need==0){ if(r-l+10) need--; while(need==0){ if(r-l+1 taskQueue; private final WorkerThread[] workers; private volatile boolean isShutdown; private final ReentrantLock mainLock = new ReentrantLock(); private final Condition termination = mainLock.newCondition(); private final AtomicInteger activeWorkers = new AtomicInteger(0); private final ThreadFactory threadFactory; private class WorkerThread extends Thread { private volatile Runnable currentTask; private volatile boolean stopped; public WorkerThread(String name) { super(name); } @Override public void run() { activeWorkers.incrementAndGet(); try { while (!stopped && !isShutdown) { try { // Poll with timeout to allow graceful shutdown Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS); if (task != null) { currentTask = task; try { task.run(); } catch (RuntimeException e) { System.err.println(""Task execution failed: "" + e.getMessage()); } finally { currentTask = null; } } } catch (InterruptedException e) { // Thread interrupted, check if we should exit if (stopped || isShutdown) { break; } } } } finally { activeWorkers.decrementAndGet(); signalIfTerminated(); } } public void stopWorker() { this.stopped = true; this.interrupt(); } public Runnable getCurrentTask() { return currentTask; } } public CustomThreadPool(int poolSize) { this(poolSize, Executors.defaultThreadFactory()); } public CustomThreadPool(int poolSize, ThreadFactory threadFactory) { if (poolSize <= 0) { throw new IllegalArgumentException(""Pool size must be positive""); } this.taskQueue = new LinkedBlockingQueue<>(); this.workers = new WorkerThread[poolSize]; this.threadFactory = threadFactory; this.isShutdown = false; // Initialize workers for (int i = 0; i < poolSize; i++) { WorkerThread worker = new WorkerThread(""CustomPool-Worker-"" + i); workers[i] = worker; worker.start(); } } public void execute(Runnable task) { if (task == null) throw new NullPointerException(); if (isShutdown) throw new RejectedExecutionException(""Thread pool is shutdown""); try { taskQueue.put(task); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RejectedExecutionException(""Interrupted while submitting task"", e); } } public Future submit(Runnable task) { FutureTask future = new FutureTask<>(task, null); execute(future); return future; } public Future submit(Callable task) { FutureTask future = new FutureTask<>(task); execute(future); return future; } public void shutdown() { mainLock.lock(); try { isShutdown = true; } finally { mainLock.unlock(); } } public void shutdownNow() { mainLock.lock(); try { isShutdown = true; // Clear task queue taskQueue.clear(); // Interrupt all workers for (WorkerThread worker : workers) { if (worker != null) { worker.stopWorker(); } } } finally { mainLock.unlock(); } } public boolean isShutdown() { return isShutdown; } public boolean isTerminated() { return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); mainLock.lock(); try { while (!isTerminated()) { if (nanos <= 0) { return false; } nanos = termination.awaitNanos(nanos); } return true; } finally { mainLock.unlock(); } } public int getActiveCount() { return activeWorkers.get(); } public int getPoolSize() { return workers.length; } public long getTaskCount() { return taskQueue.size(); } private void signalIfTerminated() { mainLock.lock(); try { if (isTerminated()) { termination.signalAll(); } } finally { mainLock.unlock(); } } }",1.0,DEEPSEEK,"Implement a custom thread pool executor with fixed thread count, task queue, and shutdown capabilities.",java,"import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class CustomThreadPool { private final BlockingQueue taskQueue; private final WorkerThread[] workers; private volatile boolean isShutdown; private final ReentrantLock mainLock = new ReentrantLock(); private final Condition termination = mainLock.newCondition(); private final AtomicInteger activeWorkers = new AtomicInteger(0); private final ThreadFactory threadFactory; private class WorkerThread extends Thread { private volatile Runnable currentTask; private volatile boolean stopped; public WorkerThread(String name) { super(name); } @Override public void run() { activeWorkers.incrementAndGet(); try { while (!stopped && !isShutdown) { try { // Poll with timeout to allow graceful shutdown Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS); if (task != null) { currentTask = task; try { task.run(); } catch (RuntimeException e) { System.err.println(""Task execution failed: "" + e.getMessage()); } finally { currentTask = null; } } } catch (InterruptedException e) { // Thread interrupted, check if we should exit if (stopped || isShutdown) { break; } } } } finally { ... truncated ... } public boolean isShutdown() { return isShutdown; } public boolean isTerminated() { return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); mainLock.lock(); try { while (!isTerminated()) { if (nanos <= 0) { return false; } nanos = termination.awaitNanos(nanos); } return true; } finally { mainLock.unlock(); } } public int getActiveCount() { return activeWorkers.get(); } public int getPoolSize() { return workers.length; } public long getTaskCount() { return taskQueue.size(); } private void signalIfTerminated() { mainLock.lock(); try { if (isTerminated()) { termination.signalAll(); } } finally { mainLock.unlock(); } } }",187,101 ,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: dummy = ListNode(0, head) groupPrev = dummy while True: kth = self.getKth(groupPrev, k) if not kth: break groupNext = kth.next prev, curr = kth.next, groupPrev.next while curr != groupNext: tmp = curr.next curr.next = prev prev = curr curr = tmp tmp = groupPrev.next groupPrev.next = kth groupPrev = tmp return dummy.next def getKth(self, curr, k): while curr and k > 0: curr = curr.next k -= 1 return curr",0.0,GFG,,python,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: dummy = ListNode(0, head) groupPrev = dummy while True: kth = self.getKth(groupPrev, k) if not kth: break groupNext = kth.next prev, curr = kth.next, groupPrev.next while curr != groupNext: tmp = curr.next curr.next = prev prev = curr curr = tmp tmp = groupPrev.next groupPrev.next = kth groupPrev = tmp return dummy.next def getKth(self, curr, k): while curr and k > 0: curr = curr.next k -= 1 return curr",34,34 ,"import json python_dict = {""name"": ""David"", ""age"": 6, ""class"":""I""} python_list = [""Red"", ""Green"", ""Black""] python_str = ""Python Json"" python_int = (1234) python_float = (21.34) python_T = (True) python_F = (False) python_N = (None) json_dict = json.dumps(python_dict) json_list = json.dumps(python_list) json_str = json.dumps(python_str) json_num1 = json.dumps(python_int) json_num2 = json.dumps(python_float) json_t = json.dumps(python_T) json_f = json.dumps(python_F) json_n = json.dumps(python_N) print(""json dict : "", json_dict) print(""jason list : "", json_list) print(""json string : "", json_str) print(""json number1 : "", json_num1) print(""json number2 : "", json_num2) print(""json true : "", json_t) print(""json false : "", json_f) print(""json null ; "", json_n) ",0.0,WE3RESOURCE,,python,"import json python_dict = {""name"": ""David"", ""age"": 6, ""class"":""I""} python_list = [""Red"", ""Green"", ""Black""] python_str = ""Python Json"" python_int = (1234) python_float = (21.34) python_T = (True) python_F = (False) python_N = (None) json_dict = json.dumps(python_dict) json_list = json.dumps(python_list) json_str = json.dumps(python_str) json_num1 = json.dumps(python_int) json_num2 = json.dumps(python_float) json_t = json.dumps(python_T) json_f = json.dumps(python_F) json_n = json.dumps(python_N) print(""json dict : "", json_dict) print(""jason list : "", json_list) print(""json string : "", json_str) print(""json number1 : "", json_num1) print(""json number2 : "", json_num2) print(""json true : "", json_t) print(""json false : "", json_f) print(""json null ; "", json_n)",27,27 ,"import heapq def lastStoneWeight(stones): stones = [-s for s in stones] heapq.heapify(stones) while len(stones) > 1: a = -heapq.heappop(stones) b = -heapq.heappop(stones) if a != b: heapq.heappush(stones, -(a - b)) return -stones[0] if stones else 0 ",1.0,GPT,"Solve the problem ""Last Stone Weight"". Given a list of stones, repeatedly smash the two heaviest stones. Return the weight of the remaining stone or 0. Provide Python solution using heap. ",python,"import heapq def lastStoneWeight(stones): stones = [-s for s in stones] heapq.heapify(stones) while len(stones) > 1: a = -heapq.heappop(stones) b = -heapq.heappop(stones) if a != b: heapq.heappush(stones, -(a - b)) return -stones[0] if stones else 0",13,13 ,"# Define a function named 'factorial' that calculates the factorial of a number 'n' def factorial(n): # Check if the number 'n' is 0 if n == 0: # If 'n' is 0, return 1 (factorial of 0 is 1) return 1 else: # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n' return n * factorial(n - 1) # Ask the user to input a number to compute its factorial and store it in variable 'n' n = int(input(""Input a number to compute the factorial: "")) # Print the factorial of the number entered by the user by calling the 'factorial' function print(factorial(n))",0.0,W3RESOURCE,,python,"# Define a function named 'factorial' that calculates the factorial of a number 'n' def factorial(n): # Check if the number 'n' is 0 if n == 0: # If 'n' is 0, return 1 (factorial of 0 is 1) return 1 else: # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n' return n * factorial(n - 1) # Ask the user to input a number to compute its factorial and store it in variable 'n' n = int(input(""Input a number to compute the factorial: "")) # Print the factorial of the number entered by the user by calling the 'factorial' function print(factorial(n))",15,15