Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Creating a Smart Code Generator with React, Flask, and LangChain

Real time application of text splitting using langchain
Remove Blank Lines:

Python: lines = [line for line in text.splitlines() if line.strip()]
Enter fullscreen mode Exit fullscreen mode
Laravel: $lines = array_filter(explode("\n", $text), fn($line) => !empty(trim($line)));
Enter fullscreen mode Exit fullscreen mode

Replace Text:

Python: processed_text = text.replace(find_text, replace_text)
Enter fullscreen mode Exit fullscreen mode
Laravel: $processed_text = str_replace($find_text, $replace_text, $text);
Enter fullscreen mode Exit fullscreen mode

Trim Whitespace:

Python: processed_text = text.strip()
Enter fullscreen mode Exit fullscreen mode
Laravel: $processed_text = preg_split("/\n\n/", trim($text));
Enter fullscreen mode Exit fullscreen mode

Line Numbering:

Python: numbered_lines.append(f"{line_number}: {line.strip()}")
Enter fullscreen mode Exit fullscreen mode
Laravel: $numbered_lines[] = "$line_number: $line";
Enter fullscreen mode Exit fullscreen mode

Remove Duplicate Lines Sort:

Python: seen = set(); if line not in seen: unique_lines.append(line)
Enter fullscreen mode Exit fullscreen mode
Laravel: $lines = array_unique(explode("\n", $text));
Enter fullscreen mode Exit fullscreen mode

Remove Spaces Each Line:

Python: lines = [line.replace(" ", "") for line in text.splitlines()]
Enter fullscreen mode Exit fullscreen mode
Laravel: $lines = array_map(fn($line) => str_replace(' ', '', $line), explode("\n", $text));
Enter fullscreen mode Exit fullscreen mode

Replace Space with Dash:

Python: processed_lines = [line.replace(" ", "-") for line in lines]
Enter fullscreen mode Exit fullscreen mode
Laravel: $processed_lines = array_map(fn($line) => str_replace(' ', '-', $line), explode("\n", $text));
Enter fullscreen mode Exit fullscreen mode

ASCII Unicode Conversion:

Python: unicode_values = [f"{char}: {ord(char)}" for char in text]
Enter fullscreen mode Exit fullscreen mode
Laravel: $unicode_values = array_map(fn($char) => $char . ": " . ord($char), str_split($text));
Enter fullscreen mode Exit fullscreen mode

Count Words Characters:

Python: word_count = len(text.split()); char_count = len(text)
Enter fullscreen mode Exit fullscreen mode
Laravel: $word_count = str_word_count($text); $char_count = strlen($text);
Enter fullscreen mode Exit fullscreen mode

Reverse Lines Words:

Python: reversed_lines = [" ".join(line.split()[::-1]) for line in lines]
Enter fullscreen mode Exit fullscreen mode
Laravel: $reversed_lines = array_map(fn($line) => implode(' ', array_reverse(explode(' ', $line))), explode("\n", $text));
Enter fullscreen mode Exit fullscreen mode

Extract Information (Emails/URLs):

Python: emails = re.findall(email_pattern, text); urls = re.findall(url_pattern, text)
Enter fullscreen mode Exit fullscreen mode
Laravel: $emails = preg_match_all($email_pattern, $text, $matches); $urls = preg_match_all($url_pattern, $text, $matches);
Enter fullscreen mode Exit fullscreen mode

Split Text by Characters:

Python: split_text = [text[i:i + char_count] for i in range(0, len(text), char_count)]
Enter fullscreen mode Exit fullscreen mode
Laravel: $split_text = str_split($text, $char_count);
Enter fullscreen mode Exit fullscreen mode

Change Case:

Python: processed_text = [text.upper()] / processed_text = [text.lower()] / processed_text = [text.title()]
Enter fullscreen mode Exit fullscreen mode
Laravel: $processed_text = strtoupper($text); / $processed_text = strtolower($text); / $processed_text = ucwords($text);
Enter fullscreen mode Exit fullscreen mode

Change Case by Find:

Python: pattern = re.compile(re.escape(target_text), re.IGNORECASE); processed_text = pattern.sub(change_case_function, text)
Enter fullscreen mode Exit fullscreen mode
Laravel: $pattern = "/".preg_quote($target_text, '/')."/i"; $processed_text = preg_replace_callback($pattern, $change_case_function, $text);
Enter fullscreen mode Exit fullscreen mode

Count Words by Find:

Python: count = text.lower().count(target_text.lower())
Enter fullscreen mode Exit fullscreen mode
Laravel: $count = substr_count(strtolower($text), strtolower($target_text));
Enter fullscreen mode Exit fullscreen mode

Add Prefix/Suffix:

Python: lines = [f"{prefix}{line}{suffix}" for line in text.splitlines()]
Enter fullscreen mode Exit fullscreen mode
Laravel: $lines = array_map(fn($line) => $prefix . $line . $suffix, explode("\n", $text));
Enter fullscreen mode Exit fullscreen mode

Add Custom Prefix/Suffix:

Python: modified_line = f"{prefix}{line}{suffix}"; lines.append(modified_line)
Enter fullscreen mode Exit fullscreen mode
Laravel: $modified_line = $prefix . $line . $suffix; $lines[] = $modified_line;
Enter fullscreen mode Exit fullscreen mode

List Operations:
Python (List):
Append an element to a list:

my_list.append(element)
Enter fullscreen mode Exit fullscreen mode

Remove an element from a list:

my_list.remove(element)
Enter fullscreen mode Exit fullscreen mode

Sort a list:

my_list.sort()
Enter fullscreen mode Exit fullscreen mode

Filter a list:

filtered_list = [x for x in my_list if x > 5]
Enter fullscreen mode Exit fullscreen mode

Find the length of a list:

len(my_list)
Enter fullscreen mode Exit fullscreen mode

Laravel (Array):
Append an element to an array:

array_push($my_array, $element);
Enter fullscreen mode Exit fullscreen mode

Remove an element from an array:

if(($key = array_search($element, $my_array)) !== false) { unset($my_array[$key]); }
Enter fullscreen mode Exit fullscreen mode

Sort an array:

sort($my_array);
Enter fullscreen mode Exit fullscreen mode

Filter an array:

$filtered_array = array_filter($my_array, fn($x) => $x > 5);
Enter fullscreen mode Exit fullscreen mode

Find the length of an array:

count($my_array);
Enter fullscreen mode Exit fullscreen mode
  1. Dictionary (Python) / Associative Arrays (Laravel): Python (Dictionary): Create a dictionary:
my_dict = {'key': 'value'}
Enter fullscreen mode Exit fullscreen mode

Access a value in the dictionary:

my_dict['key']
Enter fullscreen mode Exit fullscreen mode

Add a key-value pair:

my_dict['new_key'] = 'new_value'
Enter fullscreen mode Exit fullscreen mode

Remove a key-value pair:

del my_dict['key']
Enter fullscreen mode Exit fullscreen mode

Check if a key exists:

'key' in my_dict
Enter fullscreen mode Exit fullscreen mode

Laravel (Associative Array):
Create an associative array:

$my_array = ['key' => 'value'];
Enter fullscreen mode Exit fullscreen mode

Access a value in the array:
$my_array['key'];
Add a key-value pair:

$my_array['new_key'] = 'new_value';
Enter fullscreen mode Exit fullscreen mode

Remove a key-value pair:

unset($my_array['key']);
Enter fullscreen mode Exit fullscreen mode

Check if a key exists:

array_key_exists('key', $my_array);
Enter fullscreen mode Exit fullscreen mode
  1. Pandas (Python) / Laravel Equivalent (PHP): Python (Pandas): Create a DataFrame:
import pandas as pd<br>
df = pd.DataFrame(data)
Enter fullscreen mode Exit fullscreen mode

Access a column in the DataFrame:

df['column_name']
Enter fullscreen mode Exit fullscreen mode

Select rows based on a condition:

df[df['column_name'] > 5]
Enter fullscreen mode Exit fullscreen mode

Sort a DataFrame by a column:

df.sort_values('column_name')
Enter fullscreen mode Exit fullscreen mode

Group by a column:

df.groupby('column_name').sum()
Enter fullscreen mode Exit fullscreen mode

Sum a column:

df['column_name'].sum()
Enter fullscreen mode Exit fullscreen mode

Laravel (Array/Collection):
Create a collection:

$collection = collect($data);
Enter fullscreen mode Exit fullscreen mode

Access a column in the collection:

$collection->pluck('column_name');
Enter fullscreen mode Exit fullscreen mode

Select rows based on a condition:

$collection->where('column_name', '>', 5);
Enter fullscreen mode Exit fullscreen mode

Sort a collection by a key:

$collection->sortBy('column_name');
Enter fullscreen mode Exit fullscreen mode

Group by a column:

$collection->groupBy('column_name')->map(fn($group) => $group->sum('value_column'));
Enter fullscreen mode Exit fullscreen mode

Sum a column:

$collection->sum('column_name');
Enter fullscreen mode Exit fullscreen mode
  1. Numpy (Python) / Laravel Equivalent (PHP): Python (Numpy): Create a numpy array:
import numpy as np<br>
arr = np.array([1, 2, 3, 4, 5])
Enter fullscreen mode Exit fullscreen mode

Element-wise addition:

arr + 2
Enter fullscreen mode Exit fullscreen mode

Element-wise multiplication:

arr * 2
Enter fullscreen mode Exit fullscreen mode

Array slicing:
arr[1:4]
Sum of array:

arr.sum()
Enter fullscreen mode Exit fullscreen mode

Mean of array:

arr.mean()
Enter fullscreen mode Exit fullscreen mode

Laravel (PHP Arrays / Collections):
Create an array:

$arr = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Element-wise addition:

$arr = array_map(fn($x) => $x + 2, $arr);
Enter fullscreen mode Exit fullscreen mode

Element-wise multiplication:

$arr = array_map(fn($x) => $x * 2, $arr);
Enter fullscreen mode Exit fullscreen mode

Array slicing:

$arr = array_slice($arr, 1, 3);
Enter fullscreen mode Exit fullscreen mode

Sum of array:

array_sum($arr);
Enter fullscreen mode Exit fullscreen mode

Mean of array:

array_sum($arr) / count($arr);
Enter fullscreen mode Exit fullscreen mode
  1. String Operations: Python (String): Concatenate two strings:
result = str1 + str2
Enter fullscreen mode Exit fullscreen mode

Check if a string contains a substring:

substring in str
Enter fullscreen mode Exit fullscreen mode

Replace a substring:

str.replace('old', 'new')
Enter fullscreen mode Exit fullscreen mode

Convert to uppercase:

str.upper()
Enter fullscreen mode Exit fullscreen mode

Split a string:

str.split(' ')
Enter fullscreen mode Exit fullscreen mode

Laravel (PHP String):
Concatenate two strings:

$result = $str1 . $str2;
Enter fullscreen mode Exit fullscreen mode

Check if a string contains a substring:

strpos($str, 'substring') !== false;
Enter fullscreen mode Exit fullscreen mode

Replace a substring:

str_replace('old', 'new', $str);
Enter fullscreen mode Exit fullscreen mode

Convert to uppercase:

strtoupper($str);
Split a string:
explode(' ', $str);
Enter fullscreen mode Exit fullscreen mode
  1. Map/Filter Functions: Python (Map/Filter): Map (apply a function to each element):
result = list(map(lambda x: x + 2, my_list))
Filter (filter elements based on a condition):
result = list(filter(lambda x: x > 5, my_list))
Enter fullscreen mode Exit fullscreen mode

Laravel (Array/Collection Map/Filter):
Map (apply a function to each element):

$result = $my_array->map(fn($x) => $x + 2);
Enter fullscreen mode Exit fullscreen mode

Filter (filter elements based on a condition):

$result = $my_array->filter(fn($x) => $x > 5);
Enter fullscreen mode Exit fullscreen mode
  1. Find Max/Min in List/Array: Python (List): Find maximum value:
max_value = max(my_list)
Enter fullscreen mode Exit fullscreen mode

Find minimum value:

min_value = min(my_list)
Enter fullscreen mode Exit fullscreen mode

Laravel (Array/Collection):
Find maximum value:

$max_value = max($my_array);
Enter fullscreen mode Exit fullscreen mode

Find minimum value:

$min_value = min($my_array);
Enter fullscreen mode Exit fullscreen mode

List Operations:

Python (List):

my_list.append(item) – Add an item to the end of the list.
my_list.extend(another_list) – Add elements of another list to the current list.
my_list.insert(index, item) – Insert an item at a specific index.
my_list.remove(item) – Remove the first occurrence of the item.
my_list.pop(index) – Remove the item at a specific index and return it.
my_list.clear() – Remove all items from the list.
my_list.index(item) – Find the index of the first occurrence of an item.
my_list.count(item) – Count the occurrences of an item.
my_list.sort() – Sort the list in ascending order.
my_list.sort(reverse=True) – Sort the list in descending order.
sorted(my_list) – Return a sorted copy of the list.
my_list.reverse() – Reverse the order of items in the list.
my_list.copy() – Return a shallow copy of the list.
my_list[2:5] – Slice the list from index 2 to 5.
my_list[-1] – Access the last item of the list.
my_list[::2] – Slice the list to get every second item.
len(my_list) – Get the number of items in the list.
sum(my_list) – Sum the elements of the list.
max(my_list) – Find the maximum item in the list.
min(my_list) – Find the minimum item in the list.
any(my_list) – Return True if any item is true.
all(my_list) – Return True if all items are true.
my_list = [x for x in my_list if x != item] – Remove all occurrences of an item.
my_list = [x + 2 for x in my_list] – Apply a function to each element.
my_list.sort(key=len) – Sort the list by the length of the elements.
my_list.insert(0, item) – Insert item at the start of the list.
my_list.clear() – Clear all elements in the list.
my_list == another_list – Check if two lists are equal.
my_list * 2 – Repeat the list twice.
my_list[::] – Copy the entire list.
Enter fullscreen mode Exit fullscreen mode

Laravel (Array/Collection):

array_push($my_array, $item); – Add an item to the end of the array.
$my_array = array_merge($my_array, $another_array); – Merge two arrays.
array_splice($my_array, $index, 0, $item); – Insert an item at a specific index.
unset($my_array[$index]); – Remove an item at a specific index.
$item = array_pop($my_array); – Remove and return the last item.
$my_array = []; – Remove all items from the array.
array_search($item, $my_array); – Find the index of an item.
array_count_values($my_array); – Count the occurrences of each value.
sort($my_array); – Sort the array in ascending order.
rsort($my_array); – Sort the array in descending order.
array_slice($my_array, 0, 3); – Slice the array from index 0 to 3.
array_reverse($my_array); – Reverse the array.
$my_array_copy = $my_array; – Create a copy of the array.
$my_array[2] – Access the item at index 2.
array_slice($my_array, 1, null, true); – Get elements with a step.
count($my_array); – Get the number of elements in the array.
array_sum($my_array); – Sum the elements in the array.
max($my_array); – Find the maximum value.
min($my_array); – Find the minimum value.
array_filter($my_array, fn($x) => $x); – Filter elements.
array_map(fn($x) => $x + 2, $my_array); – Apply a function to each element.
array_multisort($my_array, SORT_ASC); – Sort the array in ascending order.
array_unshift($my_array, $item); – Insert at the start of the array.
array_diff($my_array, $another_array); – Find the difference between arrays.
$my_array == $another_array; – Compare two arrays.
$my_array = array_merge($my_array, $another_array); – Merge arrays.
array_fill(0, 5, 'value'); – Create an array filled with a value.
array_key_exists('key', $my_array); – Check if a key exists.
array_walk($my_array, fn(&$item) => $item * 2); – Modify array elements by reference.
collect($my_array)->sort(); – Sort using Laravel Collections.
Enter fullscreen mode Exit fullscreen mode
  1. Dictionary Operations: Python (Dictionary):
my_dict = {'key': 'value'} – Create a dictionary.
my_dict['key'] – Access a value.
my_dict['new_key'] = 'new_value' – Add a new key-value pair.
del my_dict['key'] – Remove a key-value pair.
'key' in my_dict – Check if a key exists.
my_dict.get('key') – Access a value with a default None.
my_dict.keys() – Get all the keys.
my_dict.values() – Get all the values.
my_dict.items() – Get key-value pairs.
len(my_dict) – Get the number of key-value pairs.
my_dict.update(new_dict) – Update dictionary with another dictionary.
my_dict.pop('key') – Remove a key-value pair and return the value.
my_dict.setdefault('key', 'default') – Set default value if key doesn't exist.
my_dict.copy() – Create a copy of the dictionary.
dict(zip(keys, values)) – Create a dictionary from two lists.
{k: v for k, v in my_dict.items() if v > 5} – Filter dictionary based on value.
my_dict.popitem() – Remove and return the last item.
my_dict.clear() – Clear the dictionary.
sorted(my_dict.items(), key=lambda x: x[1]) – Sort dictionary by value.
my_dict.fromkeys(keys, default_value) – Create dictionary with keys and default value.
my_dict.get('key', 'default_value') – Access key with a fallback value.
dict([(k, v) for k, v in my_dict.items() if v > 10]) – Filter with conditions.
my_dict.update({'key': 'new_value'}) – Update key-value.
my_dict = dict([(x, x**2) for x in range(5)]) – Dictionary comprehension.
my_dict = dict.fromkeys(range(5)) – Create dictionary from range.
my_dict = {'key': 'value'}; my_dict.setdefault('key2', 'value2') – Add only if the key doesn't exist.
my_dict = {key: value for key, value in my_dict.items() if key != 'key_to_remove'} – Remove a key.
my_dict = dict(zip(range(3), ['a', 'b', 'c'])) – Create dictionary from lists.
my_dict = dict(a=1, b=2) – Create dictionary with named arguments.
my_dict['key'] = my_dict.get('key', 0) + 1 – Increment the value of an existing key.
Enter fullscreen mode Exit fullscreen mode

Laravel (Associative Arrays):

$my_array = ['key' => 'value']; – Create an associative array.
$my_array['key']; – Access a value.
$my_array['new_key'] = 'new_value'; – Add a new key-value pair.
unset($my_array['key']); – Remove a key-value pair.
array_key_exists('key', $my_array); – Check if a key exists.
$my_array['key'] ?? null; – Access with default null.
array_keys($my_array); – Get all keys.
array_values($my_array); – Get all values.
foreach ($my_array as $key => $value) – Iterate through the dictionary.
count($my_array); – Get the number of elements.
$my_array = array_merge($my_array, $new_array); – Merge two arrays.
$my_array['key'] = 'new_value'; – Update a value for a key.
array_shift($my_array); – Remove the first element.
array_map(fn($key, $value) => $value * 2, $my_array); – Apply function to values.
array_splice($my_array, 1, 0, ['new_key' => 'new_value']); – Insert element at specific index.
array_filter($my_array, fn($x) => $x > 5); – Filter elements based on condition.
$my_array = array_flip($my_array); – Swap keys with values.
array_merge_recursive($my_array, $new_array); – Merge recursively.
array_column($my_array, 'column'); – Extract a column from a multi-dimensional array.
array_unshift($my_array, 'new_element'); – Add to the beginning of the array.
array_intersect($my_array, $other_array); – Get common elements.
$my_array['key'] = $my_array['key'] ?? 'default_value'; – Set default if key does not exist.
collect($my_array)->map(fn($item) => $item * 2); – Map function for collection.
collect($my_array)->pluck('key'); – Get values by key.
collect($my_array)->filter(fn($item) => $item > 10); – Filter collection.
array_unique($my_array); – Remove duplicates.
collect($my_array)->sort(); – Sort collection.
collect($my_array)->each(fn($item) => print($item)); – Iterate through collection.
array_replace($my_array, ['key' => 'new_value']); – Replace elements.
collect($my_array)->toArray(); – Convert collection to an array.
Enter fullscreen mode Exit fullscreen mode

Pandas (Python) / Laravel Equivalent (PHP)
Python (Pandas):

import pandas as pd
df = pd.DataFrame(data) – Create a DataFrame.
df.head() – Display the first few rows.
df.tail() – Display the last few rows.
df['column_name'] – Access a column in the DataFrame.
df.shape – Get the number of rows and columns.
df.info() – Display DataFrame information.
df.describe() – Generate descriptive statistics.
df['column'].sum() – Sum of a column.
df['column'].mean() – Mean of a column.
df['column'].median() – Median of a column.
df['column'].std() – Standard deviation of a column.
df.groupby('column').sum() – Group by column and compute sum.
df.drop('column_name', axis=1) – Drop a column.
df.dropna() – Drop rows with missing values.
df.fillna(value) – Fill missing values.
df.isnull().sum() – Count missing values in each column.
df.rename(columns={'old': 'new'}) – Rename columns.
df['new_column'] = df['column'] * 2 – Create a new column.
df.sort_values('column') – Sort DataFrame by a column.
df['column'].unique() – Get unique values from a column.
df['column'].value_counts() – Get value counts for a column.
df.apply(lambda x: x + 2) – Apply a function across DataFrame.
df.loc[condition] – Select rows based on a condition.
df.iloc[0:5] – Select rows by index positions.
df.merge(other_df, on='column') – Merge two DataFrames.
df.pivot(index='col1', columns='col2', values='col3') – Pivot a DataFrame.
df.to_csv('file.csv') – Export DataFrame to CSV.
df = pd.concat([df1, df2]) – Concatenate DataFrames.
df['column'].apply(np.sqrt) – Apply a function to a column.
Enter fullscreen mode Exit fullscreen mode

Laravel (PHP):

use Illuminate\Support\Collection;
$df = collect($data); – Create a Collection.
$df->take(5) – Get the first few items.
$df->take(-5) – Get the last few items.
$df->pluck('column_name') – Access a column.
$df->count() – Get the number of rows.
$df->info() – Get Collection information.
$df->sum('column') – Sum of a column.
$df->avg('column') – Mean of a column.
$df->median('column') – Median of a column.
$df->std('column') – Standard deviation (implement manually).
$df->groupBy('column')->sum('column') – Group by a column and compute sum.
$df->forget('column_name') – Drop a column.
$df->filter(fn($item) => !is_null($item['column_name'])) – Drop rows with missing values.
$df->map(fn($item) => $item['column'] ?? 0) – Fill missing values.
$df->map(fn($item) => is_null($item['column_name']) ? 'default' : $item) – Conditional fill.
$df->filter(fn($item) => is_null($item['column_name']))->count() – Count missing values.
$df->mapWithKeys(fn($item) => [$item['old'] => $item['new']]) – Rename columns.
$df->map(fn($item) => $item['column'] * 2) – Create a new column.
$df->sortBy('column') – Sort by a column.
$df->pluck('column_name')->unique() – Get unique values from a column.
$df->pluck('column_name')->countBy() – Count values in a column.
$df->map(fn($item) => $item['column'] + 2) – Apply a function to the collection.
$df->where('column', '>', 5) – Select rows based on a condition.
$df->slice(0, 5) – Slice the collection.
$df->merge($other_df) – Merge collections.
$df->groupBy('column') – Group by column.
$df->each(fn($item) => $item->save()) – Apply an action to each item.
$df->toCsv() – Export collection to CSV.
$df->pluck('column')->map(fn($x) => sqrt($x)) – Apply a function to a column.
Enter fullscreen mode Exit fullscreen mode
  1. Numpy (Python) / Laravel Equivalent (PHP) Python (Numpy):
import numpy as np
arr = np.array([1, 2, 3, 4]) – Create an array.
arr + 2 – Element-wise addition.
arr * 2 – Element-wise multiplication.
arr[2:5] – Array slicing.
arr.sum() – Sum of array elements.
arr.mean() – Mean of array elements.
arr.std() – Standard deviation of array elements.
arr.max() – Maximum element in the array.
arr.min() – Minimum element in the array.
np.dot(arr1, arr2) – Dot product of two arrays.
np.cross(arr1, arr2) – Cross product of two arrays.
arr.reshape(2, 2) – Reshape an array.
arr.flatten() – Flatten a multidimensional array.
np.concatenate([arr1, arr2]) – Concatenate arrays.
np.vstack([arr1, arr2]) – Stack arrays vertically.
np.hstack([arr1, arr2]) – Stack arrays horizontally.
np.arange(0, 10, 2) – Create an array with a step.
np.zeros((2, 3)) – Create an array of zeros.
np.ones((2, 3)) – Create an array of ones.
np.eye(3) – Create an identity matrix.
np.random.rand(3, 3) – Create a matrix with random values.
np.random.randint(1, 10, size=(3, 3)) – Random integers in a matrix.
arr.transpose() – Transpose the array.
np.linalg.inv(arr) – Inverse of a matrix.
np.linalg.det(arr) – Determinant of a matrix.
np.linalg.eig(arr) – Eigenvalues and eigenvectors.
np.append(arr, [5, 6]) – Append elements to an array.
np.delete(arr, [1, 2]) – Delete elements from an array.
np.unique(arr) – Find unique elements in an array.
Enter fullscreen mode Exit fullscreen mode

Laravel (PHP Arrays / Collections):

use Illuminate\Support\Collection;
$arr = [1, 2, 3, 4]; – Create an array.
$arr = array_map(fn($x) => $x + 2, $arr); – Element-wise addition.
$arr = array_map(fn($x) => $x * 2, $arr); – Element-wise multiplication.
$arr = array_slice($arr, 2, 3); – Array slicing.
array_sum($arr); – Sum of array elements.
array_map(fn($x) => $x, $arr); – Mean of array elements (implement manually).
array_map(fn($x) => ($x - $mean) ** 2, $arr); – Standard deviation (implement manually).
max($arr); – Maximum element in the array.
min($arr); – Minimum element in the array.
array_map(fn($x, $y) => $x * $y, $arr1, $arr2); – Dot product.
array_map(fn($x, $y) => [$x, $y], $arr1, $arr2); – Cross product (manual calculation).
array_chunk($arr, 2); – Reshape array (in chunks).
array_merge(...array_map(fn($x) => $x, $arr)); – Flatten an array.
$arr = array_merge($arr1, $arr2); – Concatenate arrays.
$arr = array_map(fn($x) => [$x, 0], $arr); – Stack arrays vertically.
$arr = array_map(fn($x) => [0, $x], $arr); – Stack arrays horizontally.
range(0, 10, 2); – Create an array with a step.
array_fill(0, 2, 3); – Create an array of zeros.
array_fill(0, 2, 1); – Create an array of ones.
eye(3); – Identity matrix (implement manually).
array_map(fn($x) => rand(), range(0, 2)); – Random matrix.
array_map(fn($x) => rand(1, 10), range(0, 9)); – Random integers in a matrix.
array_map(fn($x) => $x + 1, $arr); – Transpose-like behavior.
array_map(fn($x) => $x ** -1, $arr); – Inverse (implement manually).
array_map(fn($x) => $x ** 2, $arr); – Determinant (implement manually).
array_map(fn($x) => sqrt($x), $arr); – Eigenvalues (implement manually).
array_push($arr, 5, 6); – Append elements.
array_splice($arr, 1, 2); – Delete elements.
array_unique($arr); – Get unique elements in an array.
Enter fullscreen mode Exit fullscreen mode
  1. String Operations: Python (String):
str.upper() – Convert to uppercase.
str.lower() – Convert to lowercase.
str.capitalize() – Capitalize the first letter.
str.title() – Capitalize the first letter of each word.
str.strip() – Remove leading and trailing spaces.
str.split() – Split a string into a list.
str.replace('old', 'new') – Replace a substring.
str.find('substring') – Find a substring’s index.
str.count('substring') – Count occurrences of a substring.
str.startswith('prefix') – Check if string starts with a substring.
str.endswith('suffix') – Check if string ends with a substring.
str.isalpha() – Check if string contains only alphabets.
str.isdigit() – Check if string contains only digits.
str.islower() – Check if string is in lowercase.
str.isupper() – Check if string is in uppercase.
str.splitlines() – Split a string into lines.
str.join(list) – Join a list into a string.
str.format() – String interpolation.
str.zfill(width) – Pad string with zeros.
str.ljust(width) – Left justify the string.
str.rjust(width) – Right justify the string.
str.strip() – Remove whitespace from both ends.
str.partition('separator') – Split string into a 3-part tuple.
str.encode() – Encode the string into bytes.
str.decode() – Decode bytes into string.
str.maketrans('old', 'new') – Map characters.
str.translate() – Apply a translation table.
str.rfind('substring') – Find the last occurrence of a substring.
str.lstrip() – Remove leading spaces.
str.rstrip() – Remove trailing spaces.
Enter fullscreen mode Exit fullscreen mode

Laravel (PHP String):

strtoupper($str); – Convert to uppercase.
strtolower($str); – Convert to lowercase.
ucfirst($str); – Capitalize the first letter.
ucwords($str); – Capitalize the first letter of each word.
trim($str); – Remove leading and trailing spaces.
explode(' ', $str); – Split a string into an array.
str_replace('old', 'new', $str); – Replace a substring.
strpos($str, 'substring'); – Find the index of a substring.
substr_count($str, 'substring'); – Count occurrences of a substring.
str_starts_with($str, 'prefix'); – Check if string starts with a substring.
str_ends_with($str, 'suffix'); – Check if string ends with a substring.
ctype_alpha($str); – Check if string contains only alphabets.
ctype_digit($str); – Check if string contains only digits.
str_islower($str); – Check if string is in lowercase.
str_isupper($str); – Check if string is in uppercase.
explode("\n", $str); – Split a string into lines.
implode(' ', $array); – Join a list into a string.
sprintf($str, $variable); – String interpolation.
str_pad($str, $width, '0', STR_PAD_LEFT); – Pad string with zeros.
str_pad($str, $width, ' ', STR_PAD_LEFT); – Left justify the string.
str_pad($str, $width, ' ', STR_PAD_RIGHT); – Right justify the string.
trim($str); – Remove whitespace from both ends.
strtok($str, 'separator'); – Split string into a 3-part tuple.
utf8_encode($str); – Encode the string into bytes.
utf8_decode($str); – Decode bytes into string.
strtr($str, 'old', 'new'); – Map characters.
strtr($str, ['old' => 'new']); – Apply a translation table.
strrpos($str, 'substring'); – Find the last occurrence of a substring.
ltrim($str); – Remove leading spaces.
rtrim($str); – Remove trailing spaces.
Enter fullscreen mode Exit fullscreen mode
  1. Map/Filter Functions: Python (Map/Filter):
map(lambda x: x + 1, my_list) – Apply a function to each element.
filter(lambda x: x > 5, my_list) – Filter elements based on condition.
map(str, my_list) – Convert all elements to strings.
filter(None, my_list) – Filter out falsy values.
map(len, my_list) – Apply len() to each element.
filter(lambda x: isinstance(x, int), my_list) – Filter only integers.
map(lambda x: x * 2, my_list) – Multiply each element by 2.
filter(lambda x: x % 2 == 0, my_list) – Filter even numbers.
map(lambda x: x ** 2, my_list) – Square each element.
filter(lambda x: 'a' in x, my_list) – Filter strings containing 'a'.
map(lambda x: f'Item {x}', my_list) – Add prefix to each element.
filter(lambda x: x != 0, my_list) – Remove zeros.
map(str.upper, my_list) – Convert to uppercase.
map(lambda x: x.strip(), my_list) – Trim whitespace.
filter(lambda x: len(x) > 3, my_list) – Filter strings longer than 3 characters.
map(lambda x: x[::-1], my_list) – Reverse each string.
filter(lambda x: x % 2 != 0, my_list) – Filter odd numbers.
map(lambda x: x + '!', my_list) – Add exclamation mark to each string.
filter(lambda x: x > 0, my_list) – Filter positive numbers.
map(lambda x: x + 2, my_list) – Add 2 to each number.
filter(lambda x: isinstance(x, str), my_list) – Filter only strings.
map(lambda x: f"Number {x}", my_list) – Add a prefix to each element.
filter(lambda x: isinstance(x, float), my_list) – Filter floats.
map(lambda x: abs(x), my_list) – Take the absolute value of each number.
filter(lambda x: x % 5 == 0, my_list) – Filter multiples of 5.
map(lambda x: x.lower(), my_list) – Convert to lowercase.
filter(lambda x: len(x) == 5, my_list) – Filter strings with 5 characters.
map(lambda x: f'{x}kg', my_list) – Add unit to each element.
filter(lambda x: x != '', my_list) – Remove empty strings.
map(lambda x: str(x), my_list) – Convert each element to a string.
Enter fullscreen mode Exit fullscreen mode

==================================================================

PROMPT METHODS

PROMPT= list of 30 command code syntax used to handle data preprocessing technique to handle missing values, outliers, data types in machine learning
Dataset Analysis: A prompt to analyze the dataset
missing values, outliers, data types
Hyperparameter Tuning
classification, regression
identify columns with missing values
encoding techniques for categorical features
suitable scaling or normalization methods
feature selection techniques
cross-validation strategy
class imbalance (e.g., class weighting, oversampling, undersampling)
Random Forest model applied to the dataset: {dataset} and task: {task_type}, recommend which hyperparameters should be tuned and their possible value ranges

=====================================================
Dataset Analysis: A prompt to analyze the dataset for structured data in machine learning
missing values, outliers, data types for structured data in machine learning
Hyperparameter Tuning for structured data in machine learning
classification, regression for structured data in machine learning
identify columns with missing values for structured data in machine learning
encoding techniques for categorical features for structured data in machine learning
suitable scaling or normalization methods for structured data in machine learning
feature selection techniques for structured data in machine learning
cross-validation strategy for structured data in machine learning
class imbalance (e.g., class weighting, oversampling, undersampling) for structured data in machine learning
Random Forest model applied to the dataset: {dataset} and task: {task_type}, recommend which hyperparameters should be tuned and their possible value ranges for structured data in machine learning

preprocessing steps like normalization, resizing, tokenization for unstructured data in deeplearning
Hyperparameter Tuning Suggestions model architecture in Keras (such as number of layers, activation functions, dropout, optimizer) and recommend hyperparameters (e.g., number of epochs, batch size, learning rate) to improve the accuracy."
epochs, batch size, learning rate, and any other
preprocessing techniques (e.g., resizing, normalization, augmentation, tokenization, etc.).")
Add Layers,Configure Model,Model Summary,Train Model,Evaluate Model,Make Predictions:
Handling Imbalanced Dataset for Classification to address class imbalance (e.g., class weighting, oversampling, undersampling) to improve model accuracy."
Data Augmentation for Image Classification==recommend data augmentation techniques (e.g., flipping, rotating, scaling for images or text augmentation for NLP tasks) to improve model performance."
)
Optimizer and Learning Rate Scheduling for Model Training recommend an optimizer (e.g., Adam, SGD) and a learning rate schedule (e.g., ReduceLROnPlateau, Cyclical Learning Rates)
Transfer Learning for Improved Model Performance==transfer learning approach using pre-trained models (e.g., ResNet, VGG) to improve model accuracy.
suggest regularization techniques (e.g., dropout, L2 regularization, batch normalization) to improve model accuracy and prevent overfitting."
Early Stopping to Prevent Overfitting
Ensemble Methods to Boost Accuracy to e.g., bagging, boosting, stacking) to combine multiple models and improve accuracy.

PROMPT=======python list operation or dictionary operation to be used Data Augmentation for Image Classification==recommend data augmentation techniques (e.g., flipping, rotating, scaling for images or text augmentation for NLP tasks) for unstructured data

PROMPT=========python numpy operation or pandas operation to be used Data Augmentation for Image Classification==recommend data augmentation techniques (e.g., flipping, rotating, scaling for images or text augmentation for NLP tasks) for unstructured data

PROMPT=========python map or filter operation to be used in for preprocessing techinique to handle missing values, outliers, categorical data,encoding technique ,scaling technique

Task

========================
PROMPT-1
Creating a Smart Code Generator with React, Flask, and LangChain in frontend create dropdown for programming langauage then another dropdown no of task Flatten a multidimensional array. in backend template iask coreesponding language in request and corresponding task generate one line command and also generate full code for explanation through one real function,classs or object full code oopsconcept according abovr parallel chain

PROMPT-2
Creating a Smart Code Generator with React, Flask, and LangChain in frontend create multiselct checkbox dropdown for programming langauage then another dropdown also create multiselct checkbox dropdown no of task Flatten a multidimensional array. in backend template iask coreesponding language in request and corresponding task generate one line command and also generate full code for explanation through one real function,classs or object full code oopsconcept according above parallel chain

code for PROMPT-1

import React, { useState } from "react";
import axios from "axios";

const CodeGenerator = () => {
  const [language, setLanguage] = useState("");
  const [task, setTask] = useState("");
  const [oneLiner, setOneLiner] = useState("");
  const [fullCode, setFullCode] = useState("");

  const languages = ["Python", "JavaScript", "Java"];
  const tasks = ["Flatten a multidimensional array", "Element-wise addition", "Dot product"];

  const handleGenerateCode = async () => {
    try {
      const response = await axios.post("http://localhost:5000/generate", {
        language,
        task,
      });
      setOneLiner(response.data.command);
      setFullCode(response.data.fullCode);
    } catch (error) {
      console.error("Error generating code:", error);
    }
  };

  return (
    <div>
      <h1>Smart Code Generator</h1>

      {/* Dropdown for programming language */}
      <select value={language} onChange={(e) => setLanguage(e.target.value)}>
        <option value="">Select Programming Language</option>
        {languages.map((lang) => (
          <option key={lang} value={lang}>
            {lang}
          </option>
        ))}
      </select>

      {/* Dropdown for task */}
      <select value={task} onChange={(e) => setTask(e.target.value)}>
        <option value="">Select Task</option>
        {tasks.map((t) => (
          <option key={t} value={t}>
            {t}
          </option>
        ))}
      </select>

      {/* Button to generate code */}
      <button onClick={handleGenerateCode}>Generate Code</button>

      {/* Display the one-liner and full code */}
      <h2>Generated Command</h2>
      <pre>{oneLiner}</pre>

      <h2>Full Code</h2>
      <pre>{fullCode}</pre>
    </div>
  );
};

export default CodeGenerator;
Enter fullscreen mode Exit fullscreen mode

backend

from flask import Flask, request, jsonify
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
from langchain.chains import RunnableParallel

app = Flask(__name__)

# Initialize LangChain LLM (OpenAI for this example)
llm = OpenAI(temperature=0.5)

@app.route("/generate", methods=["POST"])
def generate_code():
    print("Received request for code generation.")

    try:
        # Extract incoming JSON data
        data = request.get_json()
        print(f"Received data: {data}")

        query = data.get("task")
        language = data.get("language")

        if not query or not language:
            return jsonify({"error": "Both 'task' and 'language' are required"}), 400

        # General dynamic prompt template
        general_prompt_template = """
        Given the task '{query}' and the programming language '{language}', generate both a one-liner and full code.
        The one-liner should be concise, and the full code should include a function or class with an explanation of the logic.
        Ensure the code is syntactically correct for the specified language, and includes necessary comments explaining the implementation.
        """

        # Generate prompt dynamically based on task and language
        prompt = general_prompt_template.format(query=query, language=language)

        # Create the prompt template for the dynamic task and language
        prompt_template = PromptTemplate(input_variables=["query", "language"], template=prompt)

        # Validate LLM instance
        if llm is None:
            return jsonify({"error": "LLM is not available"}), 500

        # Prepare the chains for parallel execution (one-liner and full code)
        chains = {
            "one_liner": prompt_template | llm,
            "full_code": prompt_template | llm
        }

        # Execute the chains in parallel using RunnableParallel
        parallel_chain = RunnableParallel(**chains)
        print("Executing code generation chains...")
        results = parallel_chain.invoke({"query": query, "language": language})

        # Process results for serialization
        result = []
        for key, value in results.items():
            content = value.content if hasattr(value, "content") else str(value)
            result.append({key: content})

        return jsonify({"results": result})

    except Exception as e:
        print(f"Error: {str(e)}")
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Updated Frontend Code (React):

import React, { useState } from "react";
import axios from "axios";
import Select from "react-select";

const CodeGenerator = () => {
  const [languages, setLanguages] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [generatedCode, setGeneratedCode] = useState([]);

  const availableLanguages = [
    { value: "Python", label: "Python" },
    { value: "JavaScript", label: "JavaScript" },
    { value: "Java", label: "Java" },
  ];

  const availableTasks = [
    { value: "Flatten a multidimensional array", label: "Flatten a multidimensional array" },
    { value: "Element-wise addition", label: "Element-wise addition" },
    { value: "Dot product", label: "Dot product" },
  ];

  const handleGenerateCode = async () => {
    try {
      const response = await axios.post("http://localhost:5000/generate", {
        languages: languages.map((lang) => lang.value),
        tasks: tasks.map((task) => task.value),
      });
      setGeneratedCode(response.data.results);
    } catch (error) {
      console.error("Error generating code:", error);
    }
  };

  return (
    <div>
      <h1>Smart Code Generator</h1>

      {/* Multi-select for Programming Languages */}
      <Select
        isMulti
        options={availableLanguages}
        value={languages}
        onChange={setLanguages}
        placeholder="Select Programming Languages"
      />

      {/* Multi-select for Tasks */}
      <Select
        isMulti
        options={availableTasks}
        value={tasks}
        onChange={setTasks}
        placeholder="Select Tasks"
      />

      {/* Button to generate code */}
      <button onClick={handleGenerateCode}>Generate Code</button>

      {/* Display the generated code */}
      {generatedCode.length > 0 && (
        <div>
          {generatedCode.map((item, index) => (
            <div key={index}>
              <h3>Generated for {item.language} - {item.task}</h3>
              <h4>One-liner:</h4>
              <pre>{item.one_liner}</pre>
              <h4>Full Code:</h4>
              <pre>{item.full_code}</pre>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default CodeGenerator;
Enter fullscreen mode Exit fullscreen mode

Explanation of the Frontend Changes:
Multi-Select for Languages and Tasks:
We use react-select for multi-select dropdowns for both languages and tasks. Users can select multiple languages and multiple tasks at once.
Request Handling:
The selected languages and tasks are sent to the backend when the "Generate Code" button is clicked. The selected languages and tasks are sent as arrays.
Rendering Results:
The generated results (both one-liner and full code) for each language-task combination are displayed.
Backend (Flask + LangChain)
Now, let's adjust the backend to handle the multi-select inputs and generate corresponding code for each language-task combination.

Updated Backend Code (Flask + LangChain):

from flask import Flask, request, jsonify
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
from langchain.chains import RunnableParallel

app = Flask(__name__)

# Initialize LangChain LLM (OpenAI for this example)
llm = OpenAI(temperature=0.5)

@app.route("/generate", methods=["POST"])
def generate_code():
    print("Received request for code generation.")

    try:
        # Extract incoming JSON data
        data = request.get_json()
        print(f"Received data: {data}")

        languages = data.get("languages", [])
        tasks = data.get("tasks", [])

        if not languages or not tasks:
            return jsonify({"error": "Both 'languages' and 'tasks' are required"}), 400

        # General dynamic prompt template
        general_prompt_template = """
        Given the task '{task}' and the programming language '{language}', generate both a one-liner and full code.
        The one-liner should be concise, and the full code should include a function or class with an explanation of the logic.
        Ensure the code is syntactically correct for the specified language, and includes necessary comments explaining the implementation.
        """

        results = []

        # Prepare the chains for parallel execution (one-liner and full code) for each language-task combination
        for language in languages:
            for task in tasks:
                # Generate prompt dynamically based on task and language
                prompt = general_prompt_template.format(task=task, language=language)

                # Create the prompt template for the dynamic task and language
                prompt_template = PromptTemplate(input_variables=["task", "language"], template=prompt)

                # Validate LLM instance
                if llm is None:
                    return jsonify({"error": "LLM is not available"}), 500

                # Prepare the chains for parallel execution (one-liner and full code)
                chains = {
                    "one_liner": prompt_template | llm,
                    "full_code": prompt_template | llm
                }

                # Execute the chains in parallel using RunnableParallel
                parallel_chain = RunnableParallel(**chains)
                print(f"Executing code generation chains for {task} and {language}...")
                generated_code = parallel_chain.invoke({"task": task, "language": language})

                # Process results for serialization
                one_liner = generated_code["one_liner"].content if "one_liner" in generated_code else "Error"
                full_code = generated_code["full_code"].content if "full_code" in generated_code else "Error"

                results.append({
                    "task": task,
                    "language": language,
                    "one_liner": one_liner,
                    "full_code": full_code
                })

        return jsonify({"results": results})

    except Exception as e:
        print(f"Error: {str(e)}")
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Real time application of text splitting using langchain

Image description

efficient-log-splitting-and-filtering-for-devops-sres

efficient-log-splitting-filtering-and-processing-for-api-devlopers

Top comments (0)