diff --git a/local-test.py b/local-test.py new file mode 100644 index 00000000..ba8232e3 --- /dev/null +++ b/local-test.py @@ -0,0 +1,24 @@ +def merge_sort(arr): + """ + Merge sorts an array of integers. + + Parameters: + - arr (list): The array to be sorted. + + Returns: + - sorted_arr (list): The sorted array. + """ + if len(arr) <= 1: + return arr + + # Split the array into two halves + mid = len(arr) // 2 + left = arr[:mid] + right = arr[mid:] + + # Recursively sort the left and right halves + left_sorted = merge_sort(left) + right_sorted = merge_sort(right) + + # Merge the sorted halves into a single sorted array + merged = merge(left_sorted, right_sorted) diff --git a/my-vulnerable-code.php b/my-vulnerable-code.php new file mode 100644 index 00000000..0d82d363 --- /dev/null +++ b/my-vulnerable-code.php @@ -0,0 +1,31 @@ +connect_error) { + die("Connection failed: " . $conn->connect_error); +} + +// Construct the SQL query +$sql = "SELECT * FROM users WHERE id = $user_id"; + +// Execute the query +$result = $conn->query($sql); + +// Check if the query was successful +if ($result->num_rows > 0) { + // Output data of each row + while($row = $result->fetch_assoc()) { + echo "id: " . $row["id"]. " - Name: " . $row["name"]. "
"; + } +} else { + echo "0 results"; +} + +// Close the connection +$conn->close(); +?> \ No newline at end of file diff --git a/script/copilot_written.py b/script/copilot_written.py new file mode 100644 index 00000000..58e60792 --- /dev/null +++ b/script/copilot_written.py @@ -0,0 +1,29 @@ +def max_product_subarray(nums): + if not nums: + return [] + + max_product = nums[0] + min_product = nums[0] + result = nums[0] + start = end = s = 0 + + for i in range(1, len(nums)): + if nums[i] < 0: + max_product, min_product = min_product, max_product + + max_product = max(nums[i], max_product * nums[i]) + min_product = min(nums[i], min_product * nums[i]) + + if max_product > result: + result = max_product + start = s + end = i + + if max_product == nums[i]: + s = i + + return nums[start:end + 1] + +# Example usage: +nums = [2, 3, -2, 4] +print(max_product_subarray(nums)) # Output: [2, 3] diff --git a/script/my_code.py b/script/my_code.py new file mode 100644 index 00000000..133b2ebd --- /dev/null +++ b/script/my_code.py @@ -0,0 +1,31 @@ +class Solution: + def check_prime(self, x: int) -> bool: + for i in range(2, int(x**0.5) + 1): + if x % i == 0: + return False + return True + + def primeSubOperation(self, nums: List[int]) -> bool: + for i in range(len(nums)): + # In case of first index, we need to find the largest prime less than nums[0]. + if i == 0: + bound = nums[0] + else: + # Otherwise, we need to find the largest prime, that makes the current element + # closest to the previous element. + bound = nums[i] - nums[i - 1] + + # If the bound is less than or equal to 0, then the array cannot be made strictly increasing. + if bound <= 0: + return False + + # Find the largest prime less than bound. + largest_prime = 0 + for j in range(bound - 1, 1, -1): + if self.check_prime(j): + largest_prime = j + break + + # Subtract this value from nums[i]. + nums[i] = nums[i] - largest_prime + return True \ No newline at end of file diff --git a/script/not_user_writt.py b/script/not_user_writt.py new file mode 100644 index 00000000..94647e60 --- /dev/null +++ b/script/not_user_writt.py @@ -0,0 +1,16 @@ +def max_product_subarray(nums): + if not nums: + return 0 + + max_product = min_product = result = nums[0] + + for num in nums[1:]: + if num < 0: + max_product, min_product = min_product, max_product + + max_product = max(num, max_product * num) + min_product = min(num, min_product * num) + + result = max(result, max_product) + + return result \ No newline at end of file diff --git a/script/python-sc.py b/script/python-sc.py new file mode 100644 index 00000000..133b2ebd --- /dev/null +++ b/script/python-sc.py @@ -0,0 +1,31 @@ +class Solution: + def check_prime(self, x: int) -> bool: + for i in range(2, int(x**0.5) + 1): + if x % i == 0: + return False + return True + + def primeSubOperation(self, nums: List[int]) -> bool: + for i in range(len(nums)): + # In case of first index, we need to find the largest prime less than nums[0]. + if i == 0: + bound = nums[0] + else: + # Otherwise, we need to find the largest prime, that makes the current element + # closest to the previous element. + bound = nums[i] - nums[i - 1] + + # If the bound is less than or equal to 0, then the array cannot be made strictly increasing. + if bound <= 0: + return False + + # Find the largest prime less than bound. + largest_prime = 0 + for j in range(bound - 1, 1, -1): + if self.check_prime(j): + largest_prime = j + break + + # Subtract this value from nums[i]. + nums[i] = nums[i] - largest_prime + return True \ No newline at end of file diff --git a/src/IPC/IssueIPC.ts b/src/IPC/IssueIPC.ts index 7519aab4..47404c8f 100644 --- a/src/IPC/IssueIPC.ts +++ b/src/IPC/IssueIPC.ts @@ -1,6 +1,6 @@ -import {BrowserWindow, ipcRenderer} from 'electron'; +import { BrowserWindow, ipcRenderer } from 'electron'; -enum Channels { +enum Channels2 { // issue reloadIssues = 'IssueIPC:reloadIssues', selectNextIssue = 'IssueIPC:selectNextIssue', @@ -9,14 +9,11 @@ enum Channels { selectPrevUnreadIssue = 'IssueIPC:selectPrevUnreadIssue', toggleRead = 'IssueIPC:toggleRead', toggleMark = 'IssueIPC:toggleMark', - toggleArchive = 'IssueIPC:toggleArchive', - filterToggleUnread = 'IssueIPC:filterToggleUnread', - filterToggleOpen = 'IssueIPC:filterToggleOpen', - filterToggleMark = 'IssueIPC:filterToggleMark', - filterToggleAuthor = 'IssueIPC:filterToggleAuthor', filterToggleAssignee = 'IssueIPC:filterToggleAssignee', - focusFilter = 'IssueIPC:focusFilter', - clearFilter = 'IssueIPC:clearFilter', + filterToggleAuthor = 'IssueIPC:filterToggleAuthor', + filterToggleMark = 'IssueIPC:filterToggleMark', + filterToggleOpen = 'IssueIPC:filterToggleOpen', + filterToggleUnread = 'IssueIPC:filterToggleUnread' } class _IssueIPC { @@ -26,140 +23,197 @@ class _IssueIPC { this.window = window; } + private sendMessage(channel: Channels) { + this.window.webContents.send(channel); + } + + private onMessage(channel: Channels, handler: () => void) { + ipcRenderer.on(channel, handler); + } + // reload issues reloadIssues() { - this.window.webContents.send(Channels.reloadIssues); + this.sendMessage(Channels.reloadIssues); } onReloadIssues(handler: () => void) { - ipcRenderer.on(Channels.reloadIssues, handler); + this.onMessage(Channels.reloadIssues, handler); } // select next issue selectNextIssue() { - this.window.webContents.send(Channels.selectNextIssue); + this.sendMessage(Channels.selectNextIssue); } onSelectNextIssue(handler: () => void) { - ipcRenderer.on(Channels.selectNextIssue, handler); + this.onMessage(Channels.selectNextIssue, handler); } // select next unread issue selectNextUnreadIssue() { - this.window.webContents.send(Channels.selectNextUnreadIssue); + this.sendMessage(Channels.selectNextUnreadIssue); } onSelectNextUnreadIssue(handler: () => void) { - ipcRenderer.on(Channels.selectNextUnreadIssue, handler); + this.onMessage(Channels.selectNextUnreadIssue, handler); } // select prev issue selectPrevIssue() { - this.window.webContents.send(Channels.selectPrevIssue); + this.sendMessage(Channels.selectPrevIssue); } onSelectPrevIssue(handler: () => void) { - ipcRenderer.on(Channels.selectPrevIssue, handler); + this.onMessage(Channels.selectPrevIssue, handler); } // select prev unread issue selectPrevUnreadIssue() { - this.window.webContents.send(Channels.selectPrevUnreadIssue); + this.sendMessage(Channels.selectPrevUnreadIssue); } onSelectPrevUnreadIssue(handler: () => void) { - ipcRenderer.on(Channels.selectPrevUnreadIssue, handler); + this.onMessage(Channels.selectPrevUnreadIssue, handler); } // toggle read toggleRead() { - this.window.webContents.send(Channels.toggleRead); + this.sendMessage(Channels.toggleRead); } onToggleRead(handler: () => void) { - ipcRenderer.on(Channels.toggleRead, handler); + this.onMessage(Channels.toggleRead, handler); } // toggle mark toggleMark() { - this.window.webContents.send(Channels.toggleMark); + this.sendMessage(Channels.toggleMark); } onToggleMark(handler: () => void) { - ipcRenderer.on(Channels.toggleMark, handler); + this.onMessage(Channels.toggleMark, handler); } // toggle archive toggleArchive() { - this.window.webContents.send(Channels.toggleArchive); + this.sendMessage(Channels.toggleArchive); } onToggleArchive(handler: () => void) { - ipcRenderer.on(Channels.toggleArchive, handler); + this.onMessage(Channels.toggleArchive, handler); } // filter toggle unread filterToggleUnread() { - this.window.webContents.send(Channels.filterToggleUnread); + this.sendMessage(Channels.filterToggleUnread); } onFilterToggleUnread(handler: () => void) { - ipcRenderer.on(Channels.filterToggleUnread, handler); + this.onMessage(Channels.filterToggleUnread, handler); } // filter toggle open filterToggleOpen() { - this.window.webContents.send(Channels.filterToggleOpen); + this.sendMessage(Channels.filterToggleOpen); } onFilterToggleOpen(handler: () => void) { - ipcRenderer.on(Channels.filterToggleOpen, handler); + this.onMessage(Channels.filterToggleOpen, handler); } // filter toggle mark filterToggleMark() { - this.window.webContents.send(Channels.filterToggleMark); + this.sendMessage(Channels.filterToggleMark); } onFilterToggleMark(handler: () => void) { - ipcRenderer.on(Channels.filterToggleMark, handler); + this.onMessage(Channels.filterToggleMark, handler); } // filter toggle author filterToggleAuthor() { - this.window.webContents.send(Channels.filterToggleAuthor); + this.sendMessage(Channels.filterToggleAuthor); } onFilterToggleAuthor(handler: () => void) { - ipcRenderer.on(Channels.filterToggleAuthor, handler); + this.onMessage(Channels.filterToggleAuthor, handler); } // filter toggle assignee filterToggleAssignee() { - this.window.webContents.send(Channels.filterToggleAssignee); + this.sendMessage(Channels.filterToggleAssignee); } onFilterToggleAssignee(handler: () => void) { - ipcRenderer.on(Channels.filterToggleAssignee, handler); + this.onMessage(Channels.filterToggleAssignee, handler); } // focus filter focusFilter() { - this.window.webContents.send(Channels.focusFilter); + this.sendMessage(Channels.focusFilter); } onFocusFilter(handler: () => void) { - ipcRenderer.on(Channels.focusFilter, handler); + this.onMessage(Channels.focusFilter, handler); } // clear filter clearFilter() { - this.window.webContents.send(Channels.clearFilter); + this.sendMessage(Channels.clearFilter); } onClearFilter(handler: () => void) { - ipcRenderer.on(Channels.clearFilter, handler); + this.onMessage(Channels.clearFilter, handler); } } export const IssueIPC = new _IssueIPC(); + + +import { BrowserWindow, ipcRenderer } from 'electron'; + +enum Channels { + // issue + reloadIssues = 'IssueIPC:reloadIssues', + selectNextIssue = 'IssueIPC:selectNextIssue', + selectNextUnreadIssue = 'IssueIPC:selectNextUnreadIssue', + selectPrevIssue = 'IssueIPC:selectPrevIssue', + selectPrevUnreadIssue = 'IssueIPC:selectPrevUnreadIssue', + toggleRead = 'IssueIPC:toggleRead', + toggleMark = 'IssueIPC:toggleMark', + toggleArchive = 'IssueIPC:toggleArchive', + filterToggleUnread = 'IssueIPC:filterToggleUnread', + filterToggleOpen = 'IssueIPC:filterToggleOpen', + filterToggleMark = 'IssueIPC:filterToggleMark', + filterToggleAuthor = 'IssueIPC:filterToggleAuthor', + filterToggleAssignee = 'IssueIPC:filterToggleAssignee', + focusFilter = 'IssueIPC:focusFilter', + clearFilter = 'IssueIPC:clearFilter', +} + +class _IssueIPC { + private window: BrowserWindow; + + initWindow(window: BrowserWindow) { + this.window = window; + } + + private sendMessage(channel: Channels) { + this.window.webContents.send(channel); + } + + private onMessage(channel: Channels, handler: () => void) { + ipcRenderer.on(channel, handler); + } + + // reload issues + reloadIssues() { + this.sendMessage(Channels.reloadIssues); + } + + onReloadIssues(handler: () => void) { + this.onMessage(Channels.reloadIssues, handler); + } + + // Add other methods similarly using sendMessage and onMessage +} \ No newline at end of file diff --git a/src/IPC/SQLiteIPC.ts b/src/IPC/SQLiteIPC.ts index 497d76ed..696cc8f8 100644 --- a/src/IPC/SQLiteIPC.ts +++ b/src/IPC/SQLiteIPC.ts @@ -1,4 +1,4 @@ -import {ipcMain, ipcRenderer} from 'electron'; +import { ipcMain, ipcRenderer } from 'electron'; enum ChannelNames { exec = 'DBIPC:exec', @@ -10,7 +10,7 @@ enum ChannelNames { type SQLParams = { sql: string; - params: Array; + params: Array; } type SQLRunReturn = { @@ -29,52 +29,57 @@ type SQLRowReturn = { }; class _SQLiteIPC { + private async invoke(channel: ChannelNames, params?: any): Promise { + return await ipcRenderer.invoke(channel, params); + } + + private handle(channel: ChannelNames, handler: (...args: any[]) => Promise) { + ipcMain.handle(channel, handler); + } + // exec async exec(sql: SQLParams['sql'], params?: SQLParams['params']): Promise { - const p: SQLParams = {sql, params}; - return await ipcRenderer.invoke(ChannelNames.exec, p); + return this.invoke(ChannelNames.exec, { sql, params }); } onExec(handler: (_ev, params: SQLParams) => Promise) { - ipcMain.handle(ChannelNames.exec, handler); + this.handle(ChannelNames.exec, handler); } // select async select(sql: SQLParams['sql'], params?: SQLParams['params']): Promise> { - const p: SQLParams = {sql, params}; - return await ipcRenderer.invoke(ChannelNames.select, p); + return this.invoke>(ChannelNames.select, { sql, params }); } onSelect(handler: (_ev, params: SQLParams) => Promise>) { - ipcMain.handle(ChannelNames.select, handler); + this.handle(ChannelNames.select, handler); } // selectSingle async selectSingle(sql: SQLParams['sql'], params?: SQLParams['params']): Promise> { - const p: SQLParams = {sql, params}; - return await ipcRenderer.invoke(ChannelNames.selectSingle, p); + return this.invoke>(ChannelNames.selectSingle, { sql, params }); } onSelectSingle(handler: (_ev, params: SQLParams) => Promise>) { - ipcMain.handle(ChannelNames.selectSingle, handler); + this.handle(ChannelNames.selectSingle, handler); } // init - async init(dbPath: string): Promise<{error?: Error}> { - return ipcRenderer.invoke(ChannelNames.init, dbPath); + async init(dbPath: string): Promise<{ error?: Error }> { + return this.invoke<{ error?: Error }>(ChannelNames.init, dbPath); } - onInit(handler: (_ev, dbPath: string) => Promise<{error?: Error}>) { - ipcMain.handle(ChannelNames.init, handler); + onInit(handler: (_ev, dbPath: string) => Promise<{ error?: Error }>) { + this.handle(ChannelNames.init, handler); } // delete db file async deleteDBFile(): Promise { - return ipcRenderer.invoke(ChannelNames.deleteDBFile); + return this.invoke(ChannelNames.deleteDBFile); } onDeleteDBFile(handler: () => Promise) { - ipcMain.handle(ChannelNames.deleteDBFile, handler); + this.handle(ChannelNames.deleteDBFile, handler); } } diff --git a/src/IPC/StreamIPC.ts b/src/IPC/StreamIPC.ts index 04ccdce7..6cd9be42 100644 --- a/src/IPC/StreamIPC.ts +++ b/src/IPC/StreamIPC.ts @@ -1,5 +1,5 @@ -import {BrowserWindow, ipcMain, ipcRenderer} from 'electron'; -import {StreamEntity} from '../Renderer/Library/Type/StreamEntity'; +import { BrowserWindow, ipcMain, ipcRenderer } from 'electron'; +import { StreamEntity } from '../Renderer/Library/Type/StreamEntity'; enum Channels { stopAllStreams = 'StreamIPC:stopAllStream', @@ -34,8 +34,8 @@ class _StreamIPC { this.window.webContents.send(Channels.stopAllStreams); } - async onStopAllStreams(handler: () => void) { - ipcRenderer.on(Channels.stopAllStreams, handler); + onStopAllStreams(handler: () => void) { + ipcMain.on(Channels.stopAllStreams, handler); } // restart all streams @@ -43,8 +43,8 @@ class _StreamIPC { this.window.webContents.send(Channels.restartAllStreams); } - async onRestartAllStreams(handler: () => void) { - ipcRenderer.on(Channels.restartAllStreams, handler); + onRestartAllStreams(handler: () => void) { + ipcMain.on(Channels.restartAllStreams, handler); } // set unread count @@ -52,18 +52,18 @@ class _StreamIPC { ipcRenderer.send(Channels.unreadCount, unreadCount, badge); } - onSetUnreadCount(handler: (_ev, unreadCount: number, badge: boolean) => void) { + onSetUnreadCount(handler: (_ev: Electron.IpcMainEvent, unreadCount: number, badge: boolean) => void) { ipcMain.on(Channels.unreadCount, handler); } // export streams - async exportStreams(streams: StreamEntity[]) { + async exportStreams(streams: StreamEntity[]): Promise { return ipcRenderer.invoke(Channels.exportStreams, streams); } - onExportStreams(handler: (_ev, streams: StreamEntity[]) => Promise) { + onExportStreams(handler: (_ev: Electron.IpcMainInvokeEvent, streams: StreamEntity[]) => Promise) { ipcMain.handle(Channels.exportStreams, handler); - }; + } // import streams async importStreams(): Promise { @@ -72,7 +72,7 @@ class _StreamIPC { onImportStreams(handler: () => Promise) { ipcMain.handle(Channels.importStreams, handler); - }; + } // select next stream selectNextStream() { @@ -183,4 +183,42 @@ class _StreamIPC { } } + +function mergeSort(arr: number[]): number[] { + if (arr.length <= 1) { + return arr; + } + + const mid = Math.floor(arr.length / 2); + const left = arr.slice(0, mid); + const right = arr.slice(mid); + + return merge(mergeSort(left), mergeSort(right)); +} + +function merge(left: number[], right: number[]): number[] { + let result: number[] = []; + let leftIndex = 0; + let rightIndex = 0; + + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + result.push(left[leftIndex]); + leftIndex++; + } else { + result.push(right[rightIndex]); + rightIndex++; + } + } + + // Concatenate the remaining elements + return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); +} + +// Example usage: +const array = [38, 27, 43, 3, 9, 82, 10]; +const sortedArray = mergeSort(array); +console.log(sortedArray); // Output: [3, 9, 10, 27, 38, 43, 82] + + export const StreamIPC = new _StreamIPC(); diff --git a/src/IPC/UserPrefIPC.ts b/src/IPC/UserPrefIPC.ts index 3a35074d..11ef9784 100644 --- a/src/IPC/UserPrefIPC.ts +++ b/src/IPC/UserPrefIPC.ts @@ -1,4 +1,4 @@ -import {ipcMain, ipcRenderer} from 'electron'; +import { ipcMain, ipcRenderer } from 'electron'; enum Channels { read = 'UserPrefIPC:read', @@ -9,50 +9,41 @@ enum Channels { } class _UserPrefIPC { - // read - async read(): Promise { - return ipcRenderer.invoke(Channels.read); + private async invoke(channel: Channels, ...args: any[]): Promise { + return ipcRenderer.invoke(channel, ...args); } - onRead(handler: () => Promise) { - ipcMain.handle(Channels.read, handler); + private handle(channel: Channels, handler: (...args: any[]) => Promise) { + ipcMain.handle(channel, (_ev, ...args) => handler(...args)); } - // write - async write(text: string): Promise { - return ipcRenderer.invoke(Channels.write, text); + // Generic method to create IPC methods + private createIpcMethod(channel: Channels) { + return { + invoke: (...args: any[]) => this.invoke(channel, ...args), + handle: (handler: (...args: any[]) => Promise) => this.handle(channel, handler), + }; } - onWrite(handler: (text: string) => Promise) { - ipcMain.handle(Channels.write, (_ev, text) => handler(text)); - } + // read + read = this.createIpcMethod(Channels.read).invoke; + onRead = this.createIpcMethod(Channels.read).handle; - // delete relative file - async deleteRelativeFile(relativeFilePath: string): Promise { - return ipcRenderer.invoke(Channels.deleteRelativeFile, relativeFilePath); - } + // write + write = this.createIpcMethod(Channels.write).invoke; + onWrite = this.createIpcMethod(Channels.write).handle; - onDeleteRelativeFile(handler: (relativeFilePath: string) => Promise) { - ipcMain.handle(Channels.deleteRelativeFile, (_ev, relativeFilePath) => handler(relativeFilePath)); - } + // delete relative file + deleteRelativeFile = this.createIpcMethod(Channels.deleteRelativeFile).invoke; + onDeleteRelativeFile = this.createIpcMethod(Channels.deleteRelativeFile).handle; // absolute file - async getAbsoluteFilePath(relativeFilePath: string): Promise { - return ipcRenderer.invoke(Channels.absoluteFilePath, relativeFilePath); - } - - onGetAbsoluteFilePath(handler: (relativeFilePath: string) => Promise) { - ipcMain.handle(Channels.absoluteFilePath, (_ev, relativeFilePath) => handler(relativeFilePath)); - } + getAbsoluteFilePath = this.createIpcMethod(Channels.absoluteFilePath).invoke; + onGetAbsoluteFilePath = this.createIpcMethod(Channels.absoluteFilePath).handle; // each paths - async getEachPaths(): Promise<{userDataPath: string; userPrefPath: string}> { - return ipcRenderer.invoke(Channels.eachPaths); - } - - onGetEachPaths(handler: () => Promise<{userDataPath: string; userPrefPath: string}>) { - ipcMain.handle(Channels.eachPaths, (_ev) => handler()); - } + getEachPaths = this.createIpcMethod<{ userDataPath: string; userPrefPath: string }>(Channels.eachPaths).invoke; + onGetEachPaths = this.createIpcMethod<{ userDataPath: string; userPrefPath: string }>(Channels.eachPaths).handle; } export const UserPrefIPC = new _UserPrefIPC(); diff --git a/src/Main/Bind/BrowserViewBind.ts b/src/Main/Bind/BrowserViewBind.ts index cb42b004..dbaf1b47 100644 --- a/src/Main/Bind/BrowserViewBind.ts +++ b/src/Main/Bind/BrowserViewBind.ts @@ -61,15 +61,35 @@ class _BrowserViewBind { BrowserViewIPC.onStopFindInPage((_ev, action) => this.active.browserView.webContents.stopFindInPage(action)); BrowserViewIPC.onSetRect((x, y, width, height) => this.setRect(x, y, width, height)); BrowserViewIPC.onSetBackgroundColor(color => this.active.browserView.setBackgroundColor(color)); + BrowserViewIPC.onSetZoomFactor(factor => this.setZoomFactor(factor)); + BrowserViewIPC.onScroll((amount, behavior) => this.scroll(amount, behavior)); + BrowserViewIPC.onOpenIssueWindow((_ev, url) => this.openIssueWindow(url)); + BrowserViewIPC.onCloseIssueWindow(() => this.closeIssueWindow()); + BrowserViewIPC.onGetWebContents(() => this.getWebContents()); + BrowserViewIPC.onSetDevTools((_ev, flag) => { + if (flag) { + this.active.window.webContents.openDevTools(); + } else { + this.active.window.webContents.closeDevTools(); + } + }); + [this.main.browserView.webContents, this.issue.browserView.webContents].forEach(webContents => { webContents.addListener('console-message', (_ev, level, message) => BrowserViewIPC.eventConsoleMessage(level, message)); webContents.addListener('dom-ready', () => BrowserViewIPC.eventDOMReady()); webContents.addListener('did-start-navigation', (_ev, url, inPage) => BrowserViewIPC.eventDidStartNavigation(url, inPage)); webContents.addListener('did-navigate', () => BrowserViewIPC.eventDidNavigate()); + webContents.addListener('did-finish-load', () => BrowserViewIPC.eventDidFinishLoad()); + webContents.addListener('did-fail-load', (_ev, errorCode, errorDescription, validatedURL, isMainFrame) => BrowserViewIPC.eventDidFailLoad(errorCode, errorDescription, validated webContents.addListener('did-navigate-in-page', () => BrowserViewIPC.eventDidNavigateInPage()); webContents.addListener('before-input-event', (_ev, input) => BrowserViewIPC.eventBeforeInput(input)); webContents.addListener('found-in-page', (_ev, result) => BrowserViewIPC.eventFoundInPage(result)); + webContents.addListener('context-menu', (_ev, params) => BrowserViewIPC.eventContextMenu(params)); + webContents.addListener('new-window', (_ev, url) => BrowserViewIPC.eventNewWindow(url)); + webContents.addListener('will-navigate', (_ev, url) => BrowserViewIPC.eventWillNavigate(url)); + webContents.addListener('will-prevent-unload', (_ev, prevent) => BrowserViewIPC.eventWillPreventUnload(prevent)); + webContents.addListener('will-redirect', (_ev, url) => BrowserViewIPC.eventWillRedirect(url)); webContents.session.on('will-download', () => BrowserViewIPC.eventWillDownload()); }); } @@ -130,6 +150,14 @@ class _BrowserViewBind { webContents.addListener('dom-ready', () => { const jsFilePath = path.resolve(__dirname, '../asset/js/context-menu.js'); const js = fs.readFileSync(jsFilePath).toString(); + webContents.executeJavaScript(js); + const cssFilePath = path.resolve(__dirname, '../asset/css/context-menu.css'); + const css = fs.readFileSync(cssFilePath).toString(); + webContents.insertCSS(css); + const cssFilePath2 = path.resolve(__dirname, '../asset/css/context-menu2.css'); + const css2 = fs.readFileSync(cssFilePath2).toString(); + webContents.insertCSS(css2); + const js = fs.readFileSync(jsFilePath).toString(); target.browserView.webContents.executeJavaScript(js); }); diff --git a/src/Main/Bind/SQLiteBind.ts b/src/Main/Bind/SQLiteBind.ts index aec90b4b..a684cd48 100644 --- a/src/Main/Bind/SQLiteBind.ts +++ b/src/Main/Bind/SQLiteBind.ts @@ -64,6 +64,13 @@ class _SQLiteBind { }); } + private async delete() { + await this.close(); + fs.unlinkSync(this.dbPath); + this.sqlite = null; + this.dbPath = null; + } + private async deleteDBFile() { await this.close(); fs.renameSync(this.dbPath, `${this.dbPath}.deleted-${Date.now()}.db`); diff --git a/src/Main/Bind/UserPrefBind.ts b/src/Main/Bind/UserPrefBind.ts index 91b6a170..a976e422 100644 --- a/src/Main/Bind/UserPrefBind.ts +++ b/src/Main/Bind/UserPrefBind.ts @@ -12,10 +12,23 @@ class _UserPrefBind { UserPrefIPC.onRead(async () => this.read()); UserPrefIPC.onWrite(async (text) => this.write(text)); UserPrefIPC.onDeleteRelativeFile(async (relativeFilePath) => this.deleteRelativeFile(relativeFilePath)); + UserPrefIPC.onDelete(async () => this.delete()); + UserPrefBindIPC.onDeleteAllData(async () => this.deleteAllData()); + UserPrefBindIPC.onCleanup(async () => this.cleanup()); + UserPrefBindIPC.onGetAbsoluteFilePath(async (relativeFilePath) => this.getAbsoluteFilePath(relativeFilePath)); + UserPrefBindIPC.onGetEachPaths(async () => this.getEachPaths()); + UserPrefBindIPC.onGetPrefDirPath(async () => this.getPrefDirPath()); + UserPrefBindIPC.onGetPrefPath(async () => this.getPrefPath()); + UserPrefBindIPC.onGetUserDataPath(async () => this.getUserDataPath()); + UserPrefIPC.onDeleteAllData(async () => this.deleteAll + UserPrefIPC.onCleanup(async () => this.cleanup()); + UserPrefIPC.onGetAbsoluteFilePath(async (relativeFilePath) => this.getAbsoluteFilePath(relativeFilePath)); UserPrefIPC.onGetEachPaths(async () => this.getEachPaths()); } + + public read(): string { const path = this.getPrefPath(); if (!fs.existsSync(path)) this.write(''); @@ -33,6 +46,16 @@ class _UserPrefBind { fs.writeFileSync(path, text); } + private delete() { + const path = this.getPrefPath(); + if (!fs.existsSync(path)) return; + + fs.unlinkSync(path); + + private cleanup() { + const path = this.getPrefDirPath(); + if (!fs.existsSync + private deleteRelativeFile(relativeFilePath: string) { const path = this.getAbsoluteFilePath(relativeFilePath); if (!path.toLowerCase().includes('jasper')) { diff --git a/src/Main/Util/PathUtil.ts b/src/Main/Util/PathUtil.ts index 842d07d3..d1a5ac69 100644 --- a/src/Main/Util/PathUtil.ts +++ b/src/Main/Util/PathUtil.ts @@ -1,3 +1,4 @@ +import fs from 'fs'; import path from 'path'; class _PathUtil { @@ -8,6 +9,136 @@ class _PathUtil { getPath(relativePathFromSrc: string) { return path.normalize(`${this.getSrcPath()}/${relativePathFromSrc}`); } + + // Read directory and iterate through all subdirectories and files + readDirectory(dirPath: string) { + const fullPath = this.getPath(dirPath); + this.iterateDirectory(fullPath); + } + + // write code to iterate through all subdirectories and files and log them + iterateFiles(dirPath: string) { + fs.readdir(dirPath, { withFileTypes: true }, (err, files) => { + if (err) { + console.error(`Error reading directory: ${err.message}`); + return; + } + + files.forEach(file => { + const fullPath = path.join(dirPath, file.name); + if (file.isDirectory()) { + console.log(`Directory: ${fullPath}`); + } else { + console.log(`File: ${fullPath}`); + } + }); + }); + } + + + private iterateDirectory(dirPath: string) { + fs.readdir(dirPath, { withFileTypes: true }, (err, files) => { + if (err) { + console.error(`Error reading directory: ${err.message}`); + return; + } + + files.forEach(file => { + const fullPath = path.join(dirPath, file.name); + if (file.isDirectory()) { + console.log(`Directory: ${fullPath}`); + this.iterateDirectory(fullPath); // Recursively iterate through subdirectories + } else { + console.log(`File: ${fullPath}`); + } + }); + }); + } } export const PathUtil = new _PathUtil(); + +// Example usage: +PathUtil.readDirectory('some/relative/path'); + +class Node { + data: T; + next: Node | null; + + constructor(data: T) { + this.data = data; + this.next = null; + } +} + +class LinkedList { + head: Node | null; + + constructor() { + this.head = null; + } + + // Add a node at the end of the list + append(data: T): void { + const newNode = new Node(data); + if (this.head === null) { + this.head = newNode; + return; + } + + let current = this.head; + while (current.next !== null) { + current = current.next; + } + current.next = newNode; + } + + // Add a node at the beginning of the list + prepend(data: T): void { + const newNode = new Node(data); + newNode.next = this.head; + this.head = newNode; + } + + // Delete a node by value + delete(data: T): void { + if (this.head === null) return; + + if (this.head.data === data) { + this.head = this.head.next; + return; + } + + let current = this.head; + while (current.next !== null && current.next.data !== data) { + current = current.next; + } + + if (current.next !== null) { + current.next = current.next.next; + } + } + + // Print the list + printList(): void { + let current = this.head; + while (current !== null) { + console.log(current.data); + current = current.next; + } + } +} + +// Example usage: +const list = new LinkedList(); +list.append(1); +list.append(2); +list.append(3); +list.printList(); // Output: 1 2 3 +list.prepend(0); +list.printList(); // Output: 0 1 2 3 +list.delete(2); +list.printList(); // Output: 0 1 3 + + +Link \ No newline at end of file diff --git a/src/Main/Util/test-match.py b/src/Main/Util/test-match.py new file mode 100644 index 00000000..e9262189 --- /dev/null +++ b/src/Main/Util/test-match.py @@ -0,0 +1,44 @@ +# This program calculates the area of a circle + +import math + +radius = float(input("Enter the radius of the circle: ")) +area = math.pi * radius**2 + +print(f"The area of the circle with radius {radius} is {area}.") + +# This program swaps the values of two variables + +x = 5 +y = 10 + +print(f"Before swapping: x = {x}, y = {y}") + +temp = x +x = y +y = temp + +print(f"After swapping: x = {x}, y = {y}") + +# This program generates a list of squares of numbers from 1 to 10 + +squares = [x**2 for x in range(1, 11)] + +print("List of squares of numbers from 1 to 10:") +for square in squares: + print(square) + +# This program checks if a given number is prime + +num = 17 + +is_prime = True +for i in range(2, int(math.sqrt(num)) + 1): + if num % i == 0: + is_prime = False + break + +if is_prime: + print(f"{num} is a prime number.") +else: + print(f"{num} is not a prime number.") diff --git a/src/Main/Util/testipd.ts b/src/Main/Util/testipd.ts new file mode 100644 index 00000000..1f7ea0bd --- /dev/null +++ b/src/Main/Util/testipd.ts @@ -0,0 +1,40 @@ +interface Person { + name: string; + age: number; + email?: string; +} + +class Employee implements Person { + name: string; + age: number; + email?: string; + + constructor(name: string, age: number, email?: string) { + this.name = name; + this.age = age; + this.email = email; + } + + printDetails() { + console.log(`Name: ${this.name}, Age: ${this.age}, Email: ${this.email || 'N/A'}`); + } +} + +const employee1 = new Employee('John Doe', 30, 'john.doe@example.com'); +const employee2 = new Employee('Jane Smith', 25); + +employee1.printDetails(); +employee2.printDetails(); + +// write code for merge sort +function mergeSort(arr: number[]): number[] { + if (arr.length <= 1) { + return arr; + } + + const mid = Math.floor(arr.length / 2); + const left = mergeSort(arr.slice(0, mid)); + const right = mergeSort(arr.slice(mid)); + + return merge(left, right); +} \ No newline at end of file diff --git a/src/Main/Window/MiscWindow/MiscWindow.ts b/src/Main/Window/MiscWindow/MiscWindow.ts index 8819693f..1bddb84b 100644 --- a/src/Main/Window/MiscWindow/MiscWindow.ts +++ b/src/Main/Window/MiscWindow/MiscWindow.ts @@ -11,6 +11,8 @@ class _MiscWindow { alwaysOnTop: true, }); + + miscWindow.webContents.on('did-finish-load', () => { const url = new URL(miscWindow.webContents.getURL()); miscWindow.setTitle(url.origin); @@ -22,3 +24,5 @@ class _MiscWindow { } export const MiscWindow = new _MiscWindow(); + +expo \ No newline at end of file diff --git a/src/Main/python/ai-tag-test.py b/src/Main/python/ai-tag-test.py new file mode 100644 index 00000000..71928b5b --- /dev/null +++ b/src/Main/python/ai-tag-test.py @@ -0,0 +1,39 @@ + // close + async close(): Promise { + return this.invoke(ChannelNames.close); + } + + onClose(handler: () => Promise) { + this.handle(ChannelNames.close, handler); + } + + // create table + async createTable(tableName: string, columns: SQLColumns[]): Promise { + return this.invoke(ChannelNames.createTable, { tableName, columns }); + } + + onCreateTable(handler: (_ev, tableName: string, columns: SQLColumns[]) => Promise) { + this.handle(ChannelNames.createTable, handler); + } + + // drop table + async// close + async close(): Promise { + return this.invoke(ChannelNames.close); + } + + onClose(handler: () => Promise) { + this.handle(ChannelNames.close, handler); + } + + // create table + async createTable(tableName: string, columns: SQLColumns[]): Promise { + return this.invoke(ChannelNames.createTable, { tableName, columns }); + } + + onCreateTable(handler: (_ev, tableName: string, columns: SQLColumns[]) => Promise) { + this.handle(ChannelNames.createTable, handler); + } + + // drop table + async \ No newline at end of file diff --git a/src/Main/python/ai_tag.py b/src/Main/python/ai_tag.py new file mode 100644 index 00000000..780b1b97 --- /dev/null +++ b/src/Main/python/ai_tag.py @@ -0,0 +1,48 @@ +def merge_two_lists(l1, l2): + dummy = ListNode(0) + current = dummy + + while l1 and l2: + if l1.val < l2.val: + current.next = l1 + l1 = l1.next + else: + current.next = l2 + l2 = l2.next + current = current.next + + if l1: + current.next = l1 + else: + current.next = l2 + + return dummy.next + + + + + +class TestMergeTwoLists(unittest.TestCase): + def list_to_array(self, head): + array = [] + while head: + array.append(head.val) + head = head.next + return array + + def array_to_list(self, array): + dummy = ListNode(0) + current = dummy + for val in array: + current.next = ListNode(val) + current = current.next + return dummy.next + + def test_merge_two_lists(self): + l1 = self.array_to_list([1, 2, 4]) + l2 = self.array_to_list([1, 3, 4]) + merged_head = merge_two_lists(l1, l2) + self.assertEqual(self.list_to_array(merged_head), [1, 1, 2, 3, 4, 4]) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/src/Main/python/bs.py b/src/Main/python/bs.py new file mode 100644 index 00000000..e01f7d94 --- /dev/null +++ b/src/Main/python/bs.py @@ -0,0 +1,45 @@ +def binary_search(arr, target): + left, right = 0, len(arr) - 1 + + while left <= right: + mid = (left + right) // 2 + + if arr[mid] == target: + return mid + elif arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return -1 + +# Example usage: +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +target = 5 +result = binary_search(arr, target) + +if result != -1: + print(f"Element found at index {result}") +else: + print("Element not found in the array") + +def longest_substring(s): + if not s: + return 0 + + max_length = 0 + left = 0 + seen = {} + + for right in range(len(s)): + if s[right] in seen and seen[s[right]] >= left: + left = seen[s[right]] + 1 + seen[s[right]] = right + max_length = max(max_length, right - left + 1) + + return max_length + +# Example usage: +input_string = "abcabcbb" +result = longest_substring(input_string) +print(result) # Output: 3 \ No newline at end of file diff --git a/src/Main/python/flask_test.py b/src/Main/python/flask_test.py new file mode 100644 index 00000000..dca84ed5 --- /dev/null +++ b/src/Main/python/flask_test.py @@ -0,0 +1,63 @@ +import sqlite3 +from flask import Flask, request, render_template_string + +app = Flask(__name__) + +# Removed hard-coded credentials and secret +DB_PATH = 'database.db' + +# Enhanced login function to use parameterized queries to avoid SQL injection vulnerability +def login(username, password): + conn = sqlite3.connect(DB_PATH) + cursor = conn.cursor() + + query = "SELECT * FROM users WHERE username=? AND password=?" + cursor.execute(query, (username, password)) + + user = cursor.fetchone() + + conn.close() + + + return user + +@app.route('/login', methods=['POST']) +def login_page(): + username = request.form['username'] + password = request.form['password'] + + user = login(username, password) + + u + if user: + return 'Login successful' + else: + return 'Login failed' + +# Properly escaping user input to prevent XSS vulnerability +@app.route('/hello') +def hello_page(): + name = request.args.get('name') + + html = "

Hello, {{ name }}!

" + + return render_template_string(html, name=name) + +if __name__ == '__main__': + app.run () + + + self.assertIn('', response.text) + self.assertIn('', response.text) + self.assertIn('Login', response.text) + +def test_login_form_submission(self): + app = Flask(__name__) + app.config['TESTING'] = True + login_page = app.route('/login') + response = self.client.post(login_page, {'username': 'test_username', 'password': 'test_password'}) + self.assertEqual(response.status_code, 302) + self.assertIn('Login successful', response.text) + +def test_protected_page(self): + app = Flask(__name__) \ No newline at end of file diff --git a/src/Main/python/inline_tag.py b/src/Main/python/inline_tag.py new file mode 100644 index 00000000..4488c4e9 --- /dev/null +++ b/src/Main/python/inline_tag.py @@ -0,0 +1,25 @@ +class TaskManager: + def __init__(self): + self.tasks = [] + + def add_task(self, task): + self.tasks.append(task) + print(f"Task '{task}' added.") + + + def remove_task(self, task): + if task in self.tasks: + self.tasks.remove(task) + print(f"Task '{task}' removed.") + else: + print(f"Task '{task}' not found.") + + def + + def list_tasks(self): + if not self.tasks: + print("No tasks available.") + else: + print("Tasks:") + for task in self.tasks: + print(f"- {task}") \ No newline at end of file diff --git a/src/Main/python/keerthy_3.py b/src/Main/python/keerthy_3.py new file mode 100644 index 00000000..1cefec74 --- /dev/null +++ b/src/Main/python/keerthy_3.py @@ -0,0 +1,101 @@ +import sys +from ctypes import Array, Structure, Union + +_array_type = type(Array) + +def _other_endian(typ): + """Return the type with the 'other' byte order. Simple types like + c_int and so on already have __ctype_be__ and __ctype_le__ + attributes which contain the types, for more complicated types + arrays and structures are supported. + """ + # check _OTHER_ENDIAN attribute (present if typ is primitive type) + if hasattr(typ, _OTHER_ENDIAN): + return getattr(typ, _OTHER_ENDIAN) + # if typ is array + if isinstance(typ, _array_type): + return _other_endian(typ._type_) * typ._length_ + # if typ is structure or union + if issubclass(typ, (Structure, Union)): + return typ + raise TypeError("This type does not support other endian: %s" % typ) + +class _swapped_meta: + def __setattr__(self, attrname, value): + if attrname == "_fields_": + fields = [] + for desc in value: + name = desc[0] + typ = desc[1] + rest = desc[2:] + fields.append((name, _other_endian(typ)) + rest) + value = fields + super().__setattr__(attrname, value) +class _swapped_struct_meta(_swapped_meta, type(Structure)): pass +class _swapped_union_meta(_swapped_meta, type(Union)): pass + +################################################################ + +# Note: The Structure metaclass checks for the *presence* (not the +# value!) of a _swappedbytes_ attribute to determine the bit order in +# structures containing bit fields. + +if sys.byteorder == "little": + _OTHER_ENDIAN = "__ctype_be__" + + LittleEndianStructure = Structure + + class BigEndianStructure(Structure, metaclass=_swapped_struct_meta): + """Structure with big endian byte order""" + __slots__ = () + _swappedbytes_ = None + + LittleEndianUnion = Union + + class BigEndianUnion(Union, metaclass=_swapped_union_meta): + """Union with big endian byte order""" + __slots__ = () + _swappedbytes_ = None + +elif sys.byteorder == "big": + _OTHER_ENDIAN = "__ctype_le__" + + BigEndianStructure = Structure + + class LittleEndianStructure(Structure, metaclass=_swapped_struct_meta): + """Structure with little endian byte order""" + __slots__ = () + _swappedbytes_ = None + + BigEndianUnion = Union + + class LittleEndianUnion(Union, metaclass=_swapped_union_meta): + """Union with little endian byte order""" + __slots__ = () + _swappedbytes_ = None + +else: + raise RuntimeError("Invalid byteorder") + + +class Node: + def __init__(self, value): + self.value = value + self.next = None + +def reverse_list(head): + current = head + previous = None + while current is not None: + next = current.next + current.next = previous + previous = current + current = next + return previous + +# Example usage +head = Node(1) +head.next = Node(2) +head.next.next = Node(3) + +print(reverse_list(head)) # Output: 3 2 1 \ No newline at end of file diff --git a/src/Main/python/keerthy_code.py b/src/Main/python/keerthy_code.py new file mode 100644 index 00000000..133b2ebd --- /dev/null +++ b/src/Main/python/keerthy_code.py @@ -0,0 +1,31 @@ +class Solution: + def check_prime(self, x: int) -> bool: + for i in range(2, int(x**0.5) + 1): + if x % i == 0: + return False + return True + + def primeSubOperation(self, nums: List[int]) -> bool: + for i in range(len(nums)): + # In case of first index, we need to find the largest prime less than nums[0]. + if i == 0: + bound = nums[0] + else: + # Otherwise, we need to find the largest prime, that makes the current element + # closest to the previous element. + bound = nums[i] - nums[i - 1] + + # If the bound is less than or equal to 0, then the array cannot be made strictly increasing. + if bound <= 0: + return False + + # Find the largest prime less than bound. + largest_prime = 0 + for j in range(bound - 1, 1, -1): + if self.check_prime(j): + largest_prime = j + break + + # Subtract this value from nums[i]. + nums[i] = nums[i] - largest_prime + return True \ No newline at end of file diff --git a/src/Main/python/llm_code.py b/src/Main/python/llm_code.py new file mode 100644 index 00000000..d1599a37 --- /dev/null +++ b/src/Main/python/llm_code.py @@ -0,0 +1,32 @@ +import heapq + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + def __lt__(self, other): + return self.val < other.val + +def mergeKLists(lists): + min_heap = [] + + # Initialize the heap with the head nodes of all lists + for l in lists: + if l: + heapq.heappush(min_heap, l) + + dummy = ListNode() + current = dummy + + while min_heap: + # Extract the smallest node from the heap + smallest_node = heapq.heappop(min_heap) + current.next = smallest_node + current = current.next + + # If the extracted node has a next node, insert it into the heap + if smallest_node.next: + heapq.heappush(min_heap, smallest_node.next) + + return dummy.next \ No newline at end of file diff --git a/src/Main/python/llm_keerthy_3.py b/src/Main/python/llm_keerthy_3.py new file mode 100644 index 00000000..b63506a3 --- /dev/null +++ b/src/Main/python/llm_keerthy_3.py @@ -0,0 +1,62 @@ +def searchMatrix(matrix, target): + if not matrix or not matrix[0]: + return False + + rows, cols = len(matrix), len(matrix[0]) + row, col = 0, cols - 1 + + while row < rows and col >= 0: + if matrix[row][col] == target: + return True + elif matrix[row][col] > target: + col -= 1 + else: + row += 1 + + return False + + + + +import unittest + +class TestSearchMatrix(unittest.TestCase): + def test_target_found(self): + matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] + ] + target = 5 + self.assertTrue(searchMatrix(matrix, target)) + + def test_target_not_found(self): + matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] + ] + target = 20 + self.assertFalse(searchMatrix(matrix, target)) + + def test_empty_matrix(self): + matrix = [] + target = 1 + self.assertFalse(searchMatrix(matrix, target)) + + def test_single_element_matrix_found(self): + matrix = [[1]] + target = 1 + self.assertTrue(searchMatrix(matrix, target)) + + def test_single_element_matrix_not_found(self): + matrix = [[1]] + target = 2 + self.assertFalse(searchMatrix(matrix, target)) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/src/Main/python/llm_written_code_aia.py b/src/Main/python/llm_written_code_aia.py new file mode 100644 index 00000000..bb8b9b8a --- /dev/null +++ b/src/Main/python/llm_written_code_aia.py @@ -0,0 +1,87 @@ +import unittest + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +def remove_nth_from_end(head, n): + dummy = ListNode(0) + dummy.next = head + first = dummy + second = dummy + + for _ in range(n + 1): + first = first.next + + + while first is not None: + first = first.next + second = second.next + + second.next = second.next.next + return dummy.next + +class TestRemoveNthFromEnd(unittest.TestCase): + def list_to_array(self, head): + array = [] + while head: + array.append(head.val) + head = head.next + return array + + def array_to_list(self, array): + dummy = ListNode(0) + current = dummy + for val in array: + current.next = ListNode(val) + current = current.next + return dummy.next + + + def test_remove_nth_from_end(self): + head = self.array_to_list([1, 2, 3, 4, 5]) + n = 2 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [1, 2, 3, 5]) + + def test_remove_first_node(self): + head = self.array_to_list([1, 2, 3, 4, 5]) + n = 5 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [2, 3, 4, 5]) + + def test_remove_last_node(self): + head = self.array_to_list([1, 2, 3, 4, 5]) + n = 1 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [1, 2, 3, 4]) + + def test_single_node(self): + head = self.array_to_list([1]) + n = 1 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), []) + + def test_remove_middle_node(self): + head = self.array_to_list([1, 2, 3, 4, 5, 6]) + n = 3 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [1, 2, 3, 5, 6]) + + def test_remove_second_last_node(self): + head = self.array_to_list([1, 2, 3, 4, 5]) + n = 2 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [1, 2, 3, 5]) + + def test_remove_node_from_two_element_list(self): + head = self.array_to_list([1, 2]) + n = 2 + new_head = remove_nth_from_end(head, n) + self.assertEqual(self.list_to_array(new_head), [2]) + +if __name__ == '__main__': + unittest.main() + + diff --git a/src/Main/python/manual_code_aia.py b/src/Main/python/manual_code_aia.py new file mode 100644 index 00000000..d7d45f40 --- /dev/null +++ b/src/Main/python/manual_code_aia.py @@ -0,0 +1,61 @@ + +class Solution: + def check_prime(self, x: int) -> bool: + for i in range(2, int(x**0.5) + 1): + if x % i == 0: + return False + return True + + def primeSubOperation(self, nums: List[int]) -> bool: + for i in range(len(nums)): + # In case of first index, we need to find the largest prime less than nums[0]. + if i == 0: + bound = nums[0] + else: + # Otherwise, we need to find the largest prime, that makes the current element + # closest to the previous element. + bound = nums[i] - nums[i - 1] + + # If the bound is less than or equal to 0, then the array cannot be made strictly increasing. + if bound <= 0: + return False + + # Find the largest prime less than bound. + largest_prime = 0 + for j in range(bound - 1, 1, -1): + if self.check_prime(j): + largest_prime = j + break + + # Subtract this value from nums[i]. + nums[i] = nums[i] - largest_prime + return True +import unittest + +class TestPrimeArray(unittest.TestCase): + def test_prime_list(self): + nums = [2, 3, 5, 7, 11] + prime = PrimeArray() + self.assertTrue(prime.prime(nums)) + + def test_prime_list_with_odd_numbers(self): + nums = [2, 3, 5, 7, 11, 13] + prime = PrimeArray() + self.assertFalse(prime.prime(nums)) + + def test_prime_list_with_negative_numbers(self): + nums = [-2, -import unittest + +class TestPrimeArray(unittest.TestCase): + def test_prime_list(self): + nums = [2, 3, 5, 7, 11] + prime = PrimeArray() + self.assertTrue(prime.prime(nums)) + + def test_prime_list_with_odd_numbers(self): + nums = [2, 3, 5, 7, 11, 13] + prime = PrimeArray() + self.assertFalse(prime.prime(nums)) + + # def test_prime_list_with_negative_numbers(self): + # nums = [-2, - \ No newline at end of file diff --git a/src/Main/python/sl.py b/src/Main/python/sl.py new file mode 100644 index 00000000..6ea8288f --- /dev/null +++ b/src/Main/python/sl.py @@ -0,0 +1,24 @@ +from typing import List + +class Solution: + def maxSumSubarray(self, nums: List[int], k: int) -> int: + if not nums or k <= 0 or k > len(nums): + return 0 + + # Calculate the sum of the first window + window_sum = sum(nums[:k]) + max_sum = window_sum + + # Slide the window from start to end of the array + for i in range(len(nums) - k): + # Subtract the element going out of the window and add the new element + window_sum = window_sum - nums[i] + nums[i + k] + max_sum = max(max_sum, window_sum) + + return max_sum + +# Example usage +solution = Solution() +nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +k = 3 +print(solution.maxSumSubarray(nums, k)) # Output: 27 (sum of subarray [8, 9, 10]) \ No newline at end of file diff --git a/src/Main/python/sl_2.py b/src/Main/python/sl_2.py new file mode 100644 index 00000000..3a0070c7 --- /dev/null +++ b/src/Main/python/sl_2.py @@ -0,0 +1,33 @@ +def test_login_page(): + # Test that the login page is accessible + response = app.get('/login') + assert response.status_code == 200 + + # Test that the login form is valid + response = app.post('/login', data={'username': 'test', 'password': 'test'}) + assert response.status_code == 302 + + # Test that the user is logged in after successful login + response = app.get('/') + assert response.status_code == 200 + assert response.json['user'] == {'username': 'test', 'id': 1} + + # Test that the user is not logged in after invalid login + response = app.post('/login', data={'username': 'test', 'password': 'invalid'}) + assertdef test_login_page(): + # Test that the login page is accessible + response = app.get('/login') + assert response.status_code == 200 + + # Test that the login form is valid + response = app.post('/login', data={'username': 'test', 'password': 'test'}) + assert response.status_code == 302 + + # Test that the user is logged in after successful login + response = app.get('/') + assert response.status_code == 200 + assert response.json['user'] == {'username': 'test', 'id': 1} + + # Test that the user is not logged in after invalid login + response = app.post('/login', data={'username': 'test', 'password': 'invalid'}) + assert \ No newline at end of file diff --git a/src/Main/python/sl_test.py b/src/Main/python/sl_test.py new file mode 100644 index 00000000..d831dd57 --- /dev/null +++ b/src/Main/python/sl_test.py @@ -0,0 +1,26 @@ +def sliding_window(arr, k): + if not arr or k <= 0: + return [] + + n = len(arr) + if k > n: + return [] + + window = [] + result = [] + + for i in range(n): + if i >= k: + result.append(window) + window.pop(0) + window.append(arr[i]) + + result.append(window) + + return result + +# Example Usage +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +k = 3 +result = sliding_window(arr, k) +print(result) \ No newline at end of file diff --git a/src/Main/python/sl_win_test.py b/src/Main/python/sl_win_test.py new file mode 100644 index 00000000..9e188c9d --- /dev/null +++ b/src/Main/python/sl_win_test.py @@ -0,0 +1,18 @@ +def max_sum_subarray(arr, k): + if k <= 0 or k > len(arr): + return -1 + + window_sum = sum(arr[:k]) + max_sum = window_sum + + for i in range(len(arr) - k): + window_sum = window_sum - arr[i] + arr[i + k] + max_sum = max(max_sum, window_sum) + + return max_sum + +# Test the function with an example +arr = [4, 2, 1, 7, 8, 1, 2, 8, 1, 0] +k = 3 +result = max_sum_subarray(arr, k) +print("The maximum sum of a subarray of size", k, "is:", result) \ No newline at end of file diff --git a/src/Main/python/tes-auth.py b/src/Main/python/tes-auth.py new file mode 100644 index 00000000..667232f4 --- /dev/null +++ b/src/Main/python/tes-auth.py @@ -0,0 +1,38 @@ +import unittest +from flask import Flask, request, render_template_string, login, redirect, url_for +from flask_test import TestCase + + +class TestFlaskApp(TestCase): + def test_login_page(self): + app = Flask(__name__) + app.config['TESTING'] = True + login_page = app.route('/login') + response = self.client.get(login_page) + self.assertEqual(response.status_code, 200) + self.assertIn('= 0 && current < arr[j]) { + arr[j + 1] = arr[j]; + j--; + } + + // at this point, j is -1 or arr[j] < current + arr[j + 1] = current; + } + + return arr; +} diff --git a/test/armstrong.py b/test/armstrong.py new file mode 100644 index 00000000..147edc6d --- /dev/null +++ b/test/armstrong.py @@ -0,0 +1,22 @@ +def is_armstrong_number(num): + # Convert the number to a string to easily iterate over digits + num_str = str(num) + # Calculate the number of digits + num_digits = len(num_str) + # Calculate the sum of the digits raised to the power of the number of digits + sum_of_powers = sum(int(digit) ** num_digits for digit in num_str) + # Check if the sum of powers is equal to the original number + return sum_of_powers == num + +def find_armstrong_numbers(start, end): + armstrong_numbers = [] + for num in range(start, end + 1): + if is_armstrong_number(num): + armstrong_numbers.append(num) + return armstrong_numbers + +# Example usage +start = 100 +end = 999 +armstrong_numbers = find_armstrong_numbers(start, end) +print(f"Armstrong numbers between {start} and {end}: {armstrong_numbers}") \ No newline at end of file diff --git a/test/binary_search.py b/test/binary_search.py new file mode 100644 index 00000000..8f07f522 --- /dev/null +++ b/test/binary_search.py @@ -0,0 +1,109 @@ +package main + +import ( + "fmt" +) +def containsDuplicate(nums): + seen = set() + for num in nums: + if num in seen: + return True + seen.add(num) + return False + +# Example +nums = [1, 2, 3, 1] +print(containsDuplicate(nums)) # Output: True + +nums = [1, 2, 3, 4] +print(containsDuplicate(nums)) # Output: False + + + + + + +// binarySearch function to perform binary search on a sorted array +func binarySearch(arr []int, target int) int { + left, right := 0, len(arr)-1 + + for left <= right { + mid := left + (right-left)/2 + + if arr[mid] == target { + return mid // target found + } else if arr[mid] < target { + left = mid + 1 // search in the right half + } else { + right = mid - 1 // search in the left half + } + } + + return -1 // target not found +} + +# Python program to check if the number is an Armstrong number or not + +# take input from the user +num = int(input("Enter a number: ")) + +# initialize sum +sum = 0 + +# find the sum of the cube of each digit +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** 3 + temp //= 10 + +# display the result +if num == sum: + print(num,"is an Armstrong number") +else: + print(num,"is not an Armstrong number") + +func main() { + arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + target := 7 + + result := binarySearch(arr, target) + if result != -1 { + fmt.Printf("Element %d found at index %d\n", target, result) + } else { + fmt.Printf("Element %d not found in the array\n", target) + } +} + +def isAnagram(s, t): + if len(s) != len(t): + return False + + char_count = {} + + for char in s: + if char in char_count: + char_count[char] += 1 + else: + char_count[char] = 1 + + for char in t: + if char in char_count: + char_count[char] -= 1 + if char_count[char] == 0: + del char_count[char] + else: + return False + + return len(char_count) == 0 + +# Test the function +s = "anagram" +t = "nagaram" +print(isAnagram(s, t)) # Output: True + +s = "rat" +t = "car" +print(isAnagram(s, t)) # Output: False + + diff --git a/test/linked_list.py b/test/linked_list.py new file mode 100644 index 00000000..09c9b32d --- /dev/null +++ b/test/linked_list.py @@ -0,0 +1,52 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + + def append(self, data): + new_node = Node(data) + if not self.head: + self.head = new_node + return + last_node = self.head + while last_node.next: + last_node = last_node.next + last_node.next = new_node + + def prepend(self, data): + new_node = Node(data) + new_node.next = self.head + self.head = new_node + + def delete_with_value(self, data): + if not self.head: + return + if self.head.data == data: + self.head = self.head.next + return + current_node = self.head + while current_node.next and current_node.next.data != data: + current_node = current_node.next + if current_node.next: + current_node.next = current_node.next.next + + def print_list(self): + current_node = self.head + while current_node: + print(current_node.data, end=" -> ") + current_node = current_node.next + print("None") + +# Example usage +ll = LinkedList() +ll.append(1) +ll.append(2) +ll.append(3) +ll.prepend(0) +ll.print_list() # Output: 0 -> 1 -> 2 -> 3 -> None +ll.delete_with_value(2) +ll.print_list() # Output: 0 -> 1 -> 3 -> None \ No newline at end of file diff --git a/test/llm_code.py b/test/llm_code.py new file mode 100644 index 00000000..3ba99cc8 --- /dev/null +++ b/test/llm_code.py @@ -0,0 +1,53 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + + def append(self, data): + new_node = Node(data) + if not self.head: + self.head = new_node + return + last_node = self.head + while last_node.next: + last_node = last_node.next + last_node.next = new_node + + def print_list(self): + current_node = self.head + while current_node: + print(current_node.data, end=" -> ") + current_node = current_node.next + print("None") + + def join(self, other_list): + if not self.head: + self.head = other_list.head + return + last_node = self.head + while last_node.next: + last_node = last_node.next + last_node.next = other_list.head + +# Example usage: +ll1 = LinkedList() +ll1.append(1) +ll1.append(2) + +ll2 = LinkedList() +ll2.append(3) +ll2.append(4) + +ll3 = LinkedList() +ll3.append(5) +ll3.append(6) + +# Join ll2 and ll3 to ll1 +ll1.join(ll2) +ll1.join(ll3) + +ll1.print_list() # Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None \ No newline at end of file diff --git a/test/multi.py b/test/multi.py new file mode 100644 index 00000000..efe9f7ac --- /dev/null +++ b/test/multi.py @@ -0,0 +1,15 @@ +def convert_decimal(number): + binary = bin(number) + octal = oct(number) + hexadecimal = hex(number) + + return binary, octal, hexadecimal + +# Example usage +number = 42 +binary, octal, hexadecimal = convert_decimal(number) + +print(f"Decimal: {number}") +print(f"Binary: {binary}") +print(f"Octal: {octal}") +print(f"Hexadecimal: {hexadecimal}") \ No newline at end of file diff --git a/test/my_code.py b/test/my_code.py new file mode 100644 index 00000000..3738ab96 --- /dev/null +++ b/test/my_code.py @@ -0,0 +1,20 @@ +import pandas as pd +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.linear_model import LogisticRegression + +train = pd.read_csv('../input/train.csv') +test = pd.read_csv('../input/test.csv') + +v = TfidfVectorizer() + +X_train = v.fit_transform(train['comment_text']) +X_test = v.transform(test['comment_text']) + +for label in ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']: + y = train[label] + model = LogisticRegression() + model.fit(X_train, y) + test[label] = model.predict_proba(X_test)[:, 1] + +test.drop('comment_text', axis=1, inplace=True) +test.to_csv('simplest.csv', index=False) \ No newline at end of file diff --git a/test/my_code_2.py b/test/my_code_2.py new file mode 100644 index 00000000..5acd99ff --- /dev/null +++ b/test/my_code_2.py @@ -0,0 +1,28 @@ + import random + +class Character: + def __init__(self, name, health): + self.name = name + self.health = health + + def attack(self, target): + damage = random.randint(1, 10) + target.health -= damage + print(f"{self.name} attacks {target.name} for {damage} damage!") + + def is_alive(self): + return self.health > 0 + +hero = Character("Hero", 100) +enemy = Character("Goblin", 50) + +while hero.is_alive() and enemy.is_alive(): + hero.attack(enemy) + if not enemy.is_alive(): + print(f"{enemy.name} is defeated!") + break + + enemy.attack(hero) + if not hero.is_alive(): + print(f"{hero.name} is defeated!") + break \ No newline at end of file diff --git a/test/sample.ts b/test/sample.ts new file mode 100644 index 00000000..ca59d504 --- /dev/null +++ b/test/sample.ts @@ -0,0 +1,16 @@ +class Person { + name: string; + age: number; + + constructor(name: string, age: number) { + this.name = name; + this.age = age; + } + + greet() { + console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); + } +} + +const person = new Person("Alice", 30); +person.greet(); \ No newline at end of file diff --git a/unittest b/unittest new file mode 100644 index 00000000..a7da33cf --- /dev/null +++ b/unittest @@ -0,0 +1,22 @@ +import unittest +from src.Main.python.bs import longest_substring + +class TestLongestSubstring(unittest.TestCase): + + def test_empty_string(self): + self.assertEqual(longest_substring(""), 0) + + def test_unique_characters(self): + self.assertEqual(longest_substring("abcdef"), 6) + + def test_repeating_characters(self): + self.assertEqual(longest_substring("abcabcbb"), 3) + + def test_all_identical_characters(self): + self.assertEqual(longest_substring("aaaaaa"), 1) + + def test_mixed_characters(self): + self.assertEqual(longest_substring("pwwkew"), 3) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file