instruction
stringlengths
0
30k
|java|xml|postgresql|psql|mybatis|
null
I have CSV files for 167 patients, they have the same number and type of columns but the number of rows in each CSV file varies. I want to train a CNN or LSTM but without combining all the CSVs. I want to train the model using each file separately because it's important for me to distinguish between each patient, so I don't combine all the files. Each file has a target column which is the values of a signal that I need to predict. It's a regression problem. Each file has about 50 columns, meaning 50 features. Could you help me? I don't know how to do this. I combined all the files and trained my model with 80% of the data, but then I realized that it's incorrect to combine the data from all the patients. Each patient has a unique behavior in their characteristics.
How to train a model with CSV files of multiple patients?
|deep-learning|neural-network|recurrent-neural-network|
null
Hibernate `ClobJdbcType` provides several binder types, but it's not documented and not so obvious for all developers. What are the "benefits" of: * _Stream_ vs simple _String_ binder? (guess streams could have better performance on LOB types? ) * _Extracting_ (`STREAM_BINDING_EXTRACTING` vs `STREAM_BINDING`)? Bonus question: `ClobJdbcType#STREAM_BINDING_EXTRACTING` uses <code>CallableStatement#setCharacterStream(String, Reader, <b>long</b>)</code>, but `PgPreparedStatement#setCharacterStream(String, Reader, long)` has been never implemented for **`long`** stream length. Why?
Hibernate ClobJdbcType bindings: what are the diferences?
|postgresql|hibernate|jdbc|clob|
The mistake was a typo: was `spring.jpa.hibernate.dll-auto=create` instesd of `spring.jpa.hibernate.ddl-auto=update ` ddl != dll
**! EDIT: A solution can be found at the bottom of the question !** I am using a Huawei E3372 4G USB dongle on Win8.1. This dongle's settings can be accessed via browser by typing 192.168.8.1 and the user can enable a 4G connection by manually clicking the "Enable mobile data" button. This is the script I am trying to use to "Enable mobile data" connection, knowing I'm doing something wrong only on line 4: ``` #!/bin/bash curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml TOKEN=$(grep -v '<?xml version="1.0" encoding="UTF-8"?><response><token>' -v '</token></response>' token.xml) curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ``` Upon executing the first curl command, the xml file's content would look like this: ``` <?xml version="1.0" encoding="UTF-8"?><response><token>ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o</token></response> ``` Just for test purposes, if I manually insert the token in the bash script, it works like a charm: ``` #!/bin/bash curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ``` I've found several suggestions for the same or similar dongles, none of them worked for me, it must be due to my insufficient knowledge. My cry for help is about line 4 of the top-most script. I am making a mistake somewhere obviously. Thank you in advance for your help. ===== EDIT: SOLUTION IS FOUND ! ===== markp-fuso's suggestion was the path to my solution. Kudos. I just noticed that besides a variable "token" which was changing upon each "on/off" action, this dongle also had a less variable "SesTokInfo" which is not being changed upon each "on/off" action (I just tested that manually) and it is different than what it was yesterday. It could be "plug/unplug" of dongle that causes that, I honestly can't know. To whom it may concern: The final form of the working script which I've just tested with positive result twice would be: (note that the script contains the curl command to "Enable mobile data". The one to "Disable mobile data" should contain 0 instead of 1 in the "dataswitch>1</dataswitch" part. ``` #!/bin/bash curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml curl -s -X GET "http://192.168.8.1/api/webserver/SesTokInfo" > sestoken.xml TOKEN=$(sed -En 's|.*<token>(.*)</token>.*|\1|p' token.xml) SESTOKEN=$(sed -En 's|.*<SesInfo>(.*)</SesInfo>.*|\1|p' sestoken.xml) typeset -p TOKEN typeset -p SESTOKEN curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=$SESTOKEN" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>" date exec $SHELL ```
So, I have forked a project from my friend and we need to work on it but apparently after doing `npm install ` and `npm start`. It is just showing Loading web3,accounts, contracts. I read somewhere that I need to use `truffle migrate` but is not identifying truffle. So, here for some help. Here, is the Home.js file import { useEffect, useState } from "react"; import TempContract from "./truffle_abis/TempContract.json"; import Web3 from "web3"; import Base from "./components/Base"; const Home = () => { const [contractInstance, setContractInstance] = useState(undefined); const [account, setAccount] = useState(null); const [web3, setWeb3] = useState(null); const [isOwner, setIsOwner] = useState(false); const [start, setStart] = useState(); const [end, setEnd] = useState(); const [loading, setLoading] = useState(false); const getData = async () => { try { setLoading(true); const web3 = new Web3(Web3.givenProvider || "ws://localhost:7545"); const accounts = await web3.eth.getAccounts(); console.table(accounts); const networkId = await web3.eth.net.getId(); const deployedNetwork = TempContract.networks[networkId]; const instance = new web3.eth.Contract( TempContract.abi, deployedNetwork && deployedNetwork.address ); setContractInstance(instance); setAccount(accounts[0]); setWeb3(web3); } catch (error) { console.log("Failed to load web3, accounts, or contract."); console.log("Get Data error: ", error); } finally { console.log("Loaded all data"); setLoading(false); } }; const getInfo = async () => { if (contractInstance && account) { console.log(contractInstance); const owner = await contractInstance.methods.getOwner().call(); console.log("owner: ", owner); console.log("account: ", account); if (account === owner) { setIsOwner(true); } let start = await contractInstance.methods.getStart().call(); let end = await contractInstance.methods.getEnd().call(); setStart(start); setEnd(end); } }; useEffect(() => { if (!window.location.hash) { window.location = window.location + "#loaded"; window.location.reload(); } }, []); useEffect(() => { getData(); }, []); useEffect(() => { getInfo(); }, [contractInstance, account]); useEffect(() => { console.log(loading); }, [loading]); return ( <div> <div> {!web3 ? ( <div> <div> <h1>Loading web3,accounts and contracts </h1> </div> </div> ) : ( <div> <Base isOwner={isOwner} /> <div> <h1>Welcome to the voting app</h1> </div>{" "} Hello! <div> Your address is {account} </div> {isOwner ? ( <div>You are owner </div> ) : ( <div>You are not owner </div> )} </div> )} </div> </div> ); }; export default Home; And here is the package.json { "name": "blockchain-voting", "version": "0.1.0", "private": true, "dependencies": { "@emotion/react": "^11.7.0", "@emotion/styled": "^11.6.0", "@mui/icons-material": "^5.2.0", "@mui/material": "^5.2.2", "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "bootstrap": "^5.1.3", "history": "^5.1.0", "react": "^17.0.2", "react-bootstrap": "^2.0.2", "react-bootstrap-table": "^4.3.1", "react-dom": "^17.0.2", "react-router-dom": "^6.0.2", "react-scripts": "^5.0.1", "web-vitals": "^1.0.1", "web3": "^4.7.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "prettier": "^2.5.1", "prettier-plugin-solidity": "^1.0.0-beta.19" } } and truffle.config module.exports = { networks: { development: { host: "127.0.0.1", port: 7545, network_id: "*", }, }, compilers: { solc: { version: "0.8.10", optimizer: { enabled: true, runs: 200, }, }, }, contracts_directory: "./src/contracts/", contracts_build_directory: "./src/truffle_abis/", };
Solidity based blockchain not getting account and networkId
|reactjs|node.js|solidity|web3js|truffle|
|kubectl|client-go|
Any wordpress plugin to robustly detect and prevent the sharing of contact details (email address and phone number) in user-generated content globally? For a wordpress website like Fiverr. com Unfortunately, Google cannot answer this question.
What wordpress plugin prevent sharing of contact information amongst users?
|wordpress|wordpress-theming|
null
Try using Scala 2 syntax fastparse.parse("1234", implicit p => parseAll(MyParser.int(p))) https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA Possible Scala 3 syntaxes are fastparse.parse("1234", p => {given P[_] = p; parseAll(MyParser.int(p))}) https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/11 fastparse.parse("1234", { case p @ given P[_] => parseAll(MyParser.int(p))}) https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/13 It would be nice if `fastparse.parse("1234", p ?=> parseAll(MyParser.int(p)))` worked, but this would require changes in fastparse. --- https://stackoverflow.com/questions/72034665/correct-scala-3-syntax-for-providing-a-given-from-a-higher-order-function-argume https://github.com/scala/scala3/discussions/12007
Using Ctrl+L(clear screen) solution for `jshell`(Mac OS) ```java System.out.print("\u001b[2J\u001b[H"); System.out.flush(); ``` e.g. ```java long start = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { for (int j = 0; j < 60; j++) { for (int k = 0; k < 60; k++) { System.out.println("Time 'hh:mm:ss' -> " + String.format("%02d", i) + ":" + String.format("%02d", j) + ":" + String.format("%02d", k) + ", Actual time elapsed: " + (System.currentTimeMillis() - start)/1000 + " sec"); Thread.sleep(995); System.out.print("\u001b[2J\u001b[H"); System.out.flush(); } } } ``` output: All previous results are hidden, but if you scroll up, you get previous results like `Time 'hh:mm:ss' -> 00:00:11, Actual time elapsed: 11 sec` ``` Time 'hh:mm:ss' -> 00:00:12, Actual time elapsed: 12 sec ```
so this happened to me i ran "truffle develop" in the terminal and then i wrote "migrate" and it worked .Hope it helped!
NextJS build fails: fetch failed ECONNREFUSED
I want to create a new polars dataframe from numpy arrays, so I want to add the column-names when creating the dataframe (as I do with pandas). ``` df = pl.DataFrame(noisy_data.tolist(), columns=[f"property_{i}" for i in range(num_columns)]) ``` But polars does not like "columns" ``` TypeError: DataFrame.__init__() got an unexpected keyword argument 'columns' ``` In the Polats dataframe documentation I cannot see any parameter for defining the columns names ``` class polars.DataFrame( data: FrameInitTypes | None = None, schema: SchemaDefinition | None = None, *, schema_overrides: SchemaDict | None = None, strict: bool = True, orient: Orientation | None = None, infer_schema_length: int | None = 100, nan_to_null: bool = False, ) ``` Another option is to rename the columns with a list of names after df creation.
I wanna create a new laravel project using composer. I have install composer. I ran this command: "composer global require laravel/intaller" and this worked but then I ran this command "laravel new <project-name>" but I got the error: "A connection timeout was encountered. If you intend to run Composer without connecting to the internet, run the command again prefixed with COMPOSER_DISABLE_NETWORK=1 to make Composer run in offline mode." I checked my internet connection and found it OK. I deleted the files created by the command and ran this again but got the same error. I noticed that the processes "Downloading laravel/pint (v1.15.0)" does not completes gives error(the same error mentioned above). then ran the command "composer clear-cache" and "composer install" in the project directory (having the the created files) but all in vain.
Laravel installation via composer gives connection timeout error
|php|laravel|composer-php|
null
A quick aside, we can cast to-and-fro from one table type to another, with restrictions: /** create a TYPE by using a temp table**/ CREATE TEMP TABLE tmpNewNames AS SELECT 0 a, 0 b , 0 c ; SELECT /** note: order, type & # of columns must match exactly**/ ROW((rec).*)::tmpNewNames AS rec_newNames -- f1,f2,f3 --> a,b,c , (ROW((rec).*)::tmpNewNames).* -- expand the new names ,'>> old names >>' AS ">> old names >>" ,* FROM ( SELECT /** inspecting rec: PG assigned stand-in names f1, f2, f3, etc... **/ rec -- a record ,(rec).* -- expanded fields f1, f2, f3 FROM ( SELECT ( 1, 2, 3 ) AS rec -- an anon type record ) cte0 )cte1 ; There is one caveat to consider, that if you later drop the temp table-type hybrid as a stand-in, be sure to use the CASCADE argument when dropping that temp table. I've observed that in previous versions of PG that server ab-ends arose while dropping temp tables that were repurposed as TYPEs. TYPE hierarchies entail inheritance, so CASCADE is understandably required -- the hazard being that if PG doesn't warn against dependent objects, this cross-purposing of a table in lieu of hard-typing might understandably lead to a logical inconsistency & system instability.
{"OriginalQuestionIds":[9508518],"Voters":[{"Id":3358272,"DisplayName":"r2evans","BindingReason":{"GoldTagBadge":"r"}}]}
I have imported the .less file to the vue component, but it still gives me an error. I define the variables in `base.less` under `assets/less`. [enter image description here](https://i.stack.imgur.com/rMSZP.jpg) And import it to `App.vue`. [enter image description here](https://i.stack.imgur.com/2eaJ3.jpg) The error message in VScode is property value expected. I installed less, and variables are able to use in main.less. There's others who encounter the same problem just add an import statement and solved, but it didn't work for me.
how to use less variables in vue components?
|vue.js|less|vue-composition-api|
null
I'm on Laravel 10, and created an API using sanctum. In my controller, I want to call the local API to display in a view. The API works fine using postman, but when called in my controller the page doesn't load and times out. Below is my module route in `module/api/routes/api.php` ``` Route::group(['middleware' => ['auth:sanctum', 'api']], function () { Route::get('sample', [ApiController::class, 'sample']); }); ``` here is the HTTP code in my controller ``` use Illuminate\Support\Facades\Http; $response = Http::withHeaders([ "Accept"=> "application/json", "Authorization" => "Bearer " . env('SANCTUM_AUTH') ]) ->get(route('sample').'/', ['type' => '2']); dd($response); ``` and this is the error i'm getting. `cURL error 28: Operation timed out after 30006 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://127.0.0.1:8000/sample/?type=2` How do I call the API locally with sanctum?
The problem is in your **#open_modal** click handler. You are replacing content of document body with document.body.innerHTML += `...`, which mean that all your event bindings are destroyed, because there no more elements they are referenced to. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#replacing_the_contents_of_an_element The solution can be <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="div_1"> <p>One</p> <p>Two</p> <p>Three</p> </div> <p id="open_modal">open the modal</p> <div id="modal" style="display: none; position: fixed; z-index: -1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4)"> <div id="modal_content"> <span id="modal_close">&times;</span> <p style="color: green;">Some text in the Modal..</p> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { let test = document.querySelector('#div_1'); for (let i = 0; i < test.children.length; i++) { test.children[i].addEventListener('click', () => { console.log(test.children[i].innerHTML); }); } }); document.querySelector('#open_modal').addEventListener('click', () => { document.querySelector('#modal').style.display = 'block'; document.querySelector('#modal').style.zIndex = '1'; }); document.querySelector('#modal_close').addEventListener('click', () => { document.querySelector('#modal').style.display = 'none'; document.querySelector('#modal').style.zIndex = '-1'; }); </script> </body> </html> <!-- end snippet -->
Below is the solution: --> You might have enabled "auto-save = afterDelay". Change it or disable it. --> No issues with extentions. --> In case you are still having issues, it could be your key-bindings. Go to settings and open settings.json (see tutorial on youtube) and remove everything between {}. This will set your VS code to default.
I'm new to SQS but I have worked with Azure Service Bus, and if I remember correctly, once you 'pop' a message from the queue it essentially no longer exists in the queue so you don't have to worry about multiple consumers getting the same message (please excuse me if this is incorrect). I'm following the Amazon .NET SDK example for 'Receiving and Deleting' a message from the queue, which to me implies that until it is deleted it may be possible for another consumer to pick it up. Is this correct? Is there a way to remove it from the queue at the same time it is received or otherwise protect it from duplicate consuming? ``` // Receive a single message from the queue. var receiveMessageRequest = new ReceiveMessageRequest { AttributeNames = { "GlobalTransactionId", "Amount", "TransactionDate" }, MaxNumberOfMessages = 1, MessageAttributeNames = { "All" }, QueueUrl = queueUrl, VisibilityTimeout = 0, WaitTimeSeconds = 0, }; var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest); // Delete the received message from the queue. var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle, }; var deleteMessageResponse = await client.DeleteMessageAsync(deleteMessageRequest); ```
Does Amazon SQS Receive Message Process Make it Unavailable?
|amazon-sqs|message-bus|
null
|c#|blazor|syncfusion|system.text.json|.net-8.0|
I am trying to convert the following column into new rows: | Id | Prices | | -------- | -------------- | | 001 | ["March:59", "April:64", "May:62"] | | 002 | ["Jan:55", ETC] | to | id | date | price | |:---- |:------:| -----:| | 001 | March | 59 | | 001 | April | 64 | | 001 | May | 62 | | 002 | Jan | 55 | The date:price pairs aren't stored in a traditional dictionary format like the following solution: https://stackoverflow.com/questions/68219903/convert-dictionary-keys-to-rows-and-show-all-the-values-in-single-column-using-p I managed to get the key:value pairs into individual rows like: | Id | Prices | | -------- | -------------- | | 001 | March:59 | | 001 | April:64 | And could split these into two columns using string manipulation but this feels inefficient instead of actually using the key:value pairs. Can anyone help please?
Python - Converting Date:Price list to new rows
|python|pandas|list|dictionary|key-value|
I'm working out of a text book JavaScript All-In_One. I'm following the directions to write an array. I'm using vscode. This is my array: const list = new Products['eggs','milk','cheese','garlic','onion','kale','salt','pepper']; When I run visual studio I get the error. Products not defined. I tried declaring the array before assigning it. When I run the code I expect to get the list in the array. When I write Products.length I expect to get the length of the array characters. I tried using the console in the browser and I get the same error.
How can I fix code for a simple array. I created a constructor by using key word:new I run code and get: ReferenceError: Products not defined
|java|android|firebase|firebase-realtime-database|firebase-authentication|
null
null
null
null
when i connect plesk panel eith filezilla this is give me always error Disconnected from server Status: Connecting to 44.194.246.170:21... Status: Connection established, waiting for welcome message... Status: Plain FTP is insecure. Please switch to FTP over TLS. Status: Logged in Status: Retrieving directory listing... Command: PWD Response: 257 "/" is the current directory Command: TYPE I Response: 200 Type set to I Command: PORT 192,168,29,176,196,199 Response: 200 PORT command successful Command: MLSD Error: Connection timed out after 20 seconds of inactivity Error: Failed to retrieve directory listing give me answer what is problem beacause i use lightsail plesk panel
when i connect lightsail plesk panel this is give me error
|filezilla|
null
![enter image description here](https://i.stack.imgur.com/4A5H6.png) I am trying to combine the "n" column to matching word (there are multiple words from a big dataset). That way the percentages reflect all of the combined "n" by circumstances of rescue, but they are subsetted by the different circumstances of rescue. I subsetted the data so that only these two columns showed up by using: subset.raptors.all.circumstances<-select(raptorswildone_noduplicates_allcircumstancesbystate, 'Circumstances of Rescue','n') from the original data set (which had unncessary columns in it). Now I just need to combine the alike circumstances of rescues.
{"OriginalQuestionIds":[10865957],"Voters":[{"Id":12002570,"DisplayName":"user12002570","BindingReason":{"GoldTagBadge":"c++"}}]}
[npm commands not working in powershell](https://i.stack.imgur.com/GycZk.png) I tried reinstall it the the error persists..Add and removed it from environment variable.. Restarted my pc nothing seems to be working [It shows in command prompt](https://i.stack.imgur.com/FP6n2.png) I want to run npm on both command prompt and powershell..
Npm command not working in poweshell but works in cmd
|node.js|powershell|
null
this took me around 30 minutes - 1 hour. So in order to save y'all time, all you might need to care about is the port in the service. For me, I mistakenly keep curl into the app port, but in fact we should have curl into the service:port. Here is an example apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 3000 # (Assumption only) - assume your app run at port 3000 --- apiVersion: v1 kind: Service metadata: name: nginx-service spec: selector: app: nginx ports: - protocol: TCP port: 9999 # <--- ** this is what we need to look at ** targetPort: 3000 So instead of curl nginx-service:3000, the correct one is nginx-service:9999. You can test this out by: kubectl -n default run tmp-shell --rm -i --tty --image nicolaka/netshoot -- /bin/bash and run the following to test: tmp-shell:~# nslook up app1-service Server: 10.96.0.10 Address: 10.96.0.10#53 Name: app1-service.demo.svc.cluster.local Address: 10.109.78.150 tmp-shell:~# curl app1-service:9991 Hello from app1
I am trying automate a login using python's selenium. There is a hcaptcha which needs to solved before pressing login button. I have done this code so far: def solve_captcha(self): solved = False api_key = os.getenv("TWO_CAPTCHA_APIKEY") solver = TwoCaptcha(api_key) code = None try: print("Solving captcha......") result = solver.hcaptcha( sitekey="ced407c5-238b-4144-9b59-4dcd58092d36", url="https://www.bakecaincontrii.com/u/login/" ) except Exception as e: print(e) else: solved = True code = result["code"] # sys.exit('solved: ' + str(result)) return str(code) def test(self, url_path): wait = WebDriverWait(self, 120) self.get(url_path) print("Url hit") print("going to next step......") time.sleep(3) # shake the mouse actions = ActionChains(self) num_of_shakes = 2 for _ in range(num_of_shakes): actions.move_by_offset(5, 5) actions.move_by_offset(-5, -5) actions.perform() time.sleep(2) # checking for the modal accept_cookie = wait.until( EC.visibility_of_element_located((By.XPATH, "//button[@class='btn btn-primary w-50 rounded-pill b1']"))) accept_cookie = wait.until(EC.element_to_be_clickable(( By.XPATH, "//button[@class='btn btn-primary w-50 rounded-pill b1']" ))) accept_cookie.click() time.sleep(3) # accept_cookie.click() # if accept_cookie.is_displayed(): # accept_cookie.click() print("check email field....") xpath_email = "//input[@placeholder='Email']" xpath_e_mail = "//input[@placeholder='E-mail']" email = wait.until(EC.element_to_be_clickable((By.XPATH, f"{xpath_email}|{xpath_e_mail}"))) print("email field found...") email.click() print("email field clicked") print("sending keys to email fields") email.send_keys("") time.sleep(3) # filling up the password password = wait.until(EC.element_to_be_clickable(( By.XPATH, "//input[@placeholder='Password']" ))) time.sleep(2) password.click() time.sleep(2) password.send_keys("") time.sleep(2) # cp = wait.until(EC.element_to_be_clickable( # (By.XPATH, '//*[@id="hcap-script"]/iframe') # )) # print("Captcha loaded") # time.sleep(3) # cp.click() # print("Captcha Clicked") solve_captcha = self.solve_captcha() print("code", solve_captcha) print("processing code to element") code = str(solve_captcha) print(type(code)) time.sleep(2) script = f"document.querySelector(" + "'" + '[name="h-captcha-response"]' + "'" + ").innerHTML = " + "'" + code + "'" # script = f'document.querySelector(\'input[name="h-captcha-response"]\').value = "{code}";' print(script) self.execute_script(script) print("now going to login") print("login button processing......") time.sleep(2) # login login_button = wait.until(EC.element_to_be_clickable(( By.XPATH, '//*[@id="app"]/main/div[2]/form/button' ))) login_button.click() time.sleep(2) But the issue I got right now is I can't submit the hcaptcha. I tried to search a lot but unable to find a solution for this. How can I check mark the hcaptha when it's solved. I used twocaptcha for solving hcaptcha.
Finally, I've found a solution to this problem without utilizing the redirect and refreshListenable properties of GoRouter. The concept involves creating a custom redirection component. Essentially, authStateChanges are globbally listened, and upon any change in AuthenticationState, we navigate to our redirection component. In my implementation, this redirection component is a splash page. From there, you can proceed to redirect to the desired page. Here is my code Router Class class AppRouter { factory AppRouter() => _instance; AppRouter._(); static final AppRouter _instance = AppRouter._(); final _config = GoRouter( initialLocation: RoutePaths.splashPath, routes: <RouteBase>[ GoRoute( path: RoutePaths.splashPath, builder: (context, state) => const SplashPage(), ), GoRoute( path: RoutePaths.loginPath, builder: (context, state) => const LoginPage(), ), GoRoute( path: RoutePaths.registrationPath, builder: (context, state) => const RegistrationPage(), ), GoRoute( path: RoutePaths.homePath, builder: (context, state) => const HomePage(), ), ], ); GoRouter get config => _config; } class RoutePaths { static const String loginPath = '/login'; static const String registrationPath = '/register'; static const String homePath = '/home'; static const String splashPath = '/'; } Authentication Bloc class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> { AuthenticationBloc( this.registerUseCase, this.loginUseCase, ) : super(const AuthenticationInitial()) { on<AuthenticationStatusCheck>((event, emit) async { await emit.onEach( FirebaseAuth.instance.authStateChanges(), onData: (user) async { this.user = user; emit(const AuthenticationLoading()); await Future.delayed(const Duration(seconds: 1), () { if (user == null) { emit(const AuthenticationInitial()); } else { emit(AuthenticationSuccess(user)); } }); }, ); }); Main final router = AppRouter().config; return MultiBlocProvider( providers: [ BlocProvider<AuthenticationBloc>( create: (context) => sl<AuthenticationBloc>()..add(const AuthenticationStatusCheck()), ), ], child: BlocListener<AuthenticationBloc, AuthenticationState>( listenWhen: (previous, current) => previous.runtimeType != current.runtimeType, listener: (context, state) { if (state is AuthenticationLoading) { router.go(RoutePaths.splashPath); } }, child: MaterialApp.router( title: 'Hero Games Case Study', theme: ThemeData.dark( useMaterial3: true, ), routerConfig: router, ), ), ); splash_page return BlocListener<AuthenticationBloc, AuthenticationState>( listener: (context, state) { if (state is AuthenticationSuccess) { context.go(RoutePaths.homePath); } else if (state is AuthenticationInitial) { context.go(RoutePaths.loginPath); } }, child: Scaffold( appBar: AppBar( title: const Text('Splash Page'), ), body: const Center( child: CircularProgressIndicator(), ), ), ); NOTE: If you will use deeplinking, you can add the code below to your GoRouter redirect: (context, state) { if (context.read<AuthenticationBloc>().user == null && (state.fullPath != RoutePaths.loginPath && state.fullPath != RoutePaths.registrationPath && state.fullPath != RoutePaths.splashPath)) { return RoutePaths.splashPath; } return null; },
[this is my result][1]I ran the deep learning for regression, it is a multimodal model with two loss functions. the mse and mae are acceptable, but the r2 is so horrible. any idea can explain it? what should I check? Thanks!!!!! this is my code. def r_squared(y_true, y_pred): SS_res = K.sum(K.square(y_true - y_pred)) SS_tot = K.sum(K.square(y_true - K.mean(y_true))) return 1 - SS_res/(SS_tot + K.epsilon()) optimizer1 = keras.optimizers.Adam(1e-5, clipnorm=0.3, epsilon=1e-4) model.compile(optimizer=optimizer1, loss=losses1, loss_weights=loss_weights1, metrics=['mse',r_squared,'mae']) [1]: https://i.stack.imgur.com/MA8x2.jpg
Error is :- Access to XMLHttpRequest at 'https://lets-talk-orcin.vercel.app/socket.io/?EIO=4&transport=polling&t=OwKav8O&sid=Qge6bm6DZTQlvvJBAAAA' from origin 'https://lets-talk-frontend.vercel.app' has been blocked by CORS policy:No 'Access-Control-Allow-Origin' header is present on the requested resource. I have created a chat app using nodejs and reactjs. On my local machine it works perfectly but after deploying on vercel it gives above error. please help me to solve this. My server side code to connect with socket io is ``` app.use( cors({ origin: process.env.FRONTEND_URL, credentials: true, }) ) const server = app.listen(PORT, () => { console.log("Listening at port no. ", PORT); }); // Frontend url is :- https://lets-chat-frontend.vercel.app const io = require('socket.io')(server, { cors: { origin: process.env.FRONTEND_URL, methods: ["GET", "POST"], transports: ['websocket', 'polling'], }, allowEIO3: true }); ``` My client side code to connect with socket io is ``` import { io } from "socket.io-client"; export const socket = io("https://lets-talk-orcin.vercel.app/", { autoConnect: false, }); ```
Error while uploading the socket io chat app
|javascript|reactjs|node.js|socket.io|
null
You can use a guard to prevent recursive calls ``` vb Private m_updating As Boolean ``` Then in the TextChanged event handlers check, set and reset the guard. Here `HEX_TextChanged` as an example ``` vb Private Sub HEX_TextChanged(sender As Object, e As EventArgs) Handles HEX.TextChanged If Not m_updating Then m_updating = True Try ' TODO: put your conversion and updating logic here Finally m_updating = False End Try End If End Sub ``` The Try-Finally statement makes sure the guard is reset in any case, even if a exception should occur or the code was left prematurely with a Return-statement.
I am building an app within an application called Rhino where it has a button to call this method. ```C# public void AttachPopupToViewportWindow() { _originalBound = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Bounds; try { _formWindow = new SW.Win32Window(NativeHandle); General._viewportWindow.AddControl(_formWindow); } catch (System.ComponentModel.Win32Exception ex) { } } ``` When the method is called repeatedly in a very short time, the `NativeHandle` cannot be read anymore and it throws an Unhandled Exception. [![enter image description here][1]][1] The `NativeHandle` represents a `IntPtr` address to the WPF control. I tried different ways of bypassing this exception. They all failed to work. Why hasn't the try-catch block catch the exception? [1]: https://i.stack.imgur.com/LXBgx.png
How can I submit invisible hCaptcha
|python|selenium-webdriver|2captcha|hcaptcha|
{"Voters":[{"Id":3689450,"DisplayName":"VLAZ"},{"Id":1940850,"DisplayName":"karel"},{"Id":5468463,"DisplayName":"Vega"}],"SiteSpecificCloseReasonIds":[13]}
there! I was wondering if Svelte has a way to update state in a non-blocking fashion. Here's artifically slow tabs example. https://svelte.dev/repl/565c333f0ab141c1a97e96f855d2e7d0?version=4.2.12 As you can see, when you switch Tab 2, it prevents tab button from being active until tab content rendering finishes. It makes the UI feel less snappy. I was seeking something like useTransition in React: https://react.dev/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition Thanks in advance!
Non-blocking state update
|javascript|performance|svelte|
I am running my first Spring based project where I was trying to execute this class but as I mentioned, it shows me some processing and nothing happens. [enter image description here](https://i.stack.imgur.com/lV36W.png) I tried searching for the solution, where I checked my main method, tried to rerun it as java application. I would really be thankful if someone finds the solution for this problem
I am trying to run java application in Eclipse, When I try to do Run > Run as > Java Application it starts to show little processing but nothing happe
|java|spring|eclipse|configuration|compilation|
null
So I am trying to use a code for a dji tello drone for face tracking, which I got from https://github.com/Shreyas-dotcom/DJITello_FaceTracking/blob/main/Code%3A%20V2. I had modified it for my needs and the drone flies, streams and everything expect it does not follow mw as i need it to do. Can anyone see why the code is not working for me? ' This is the code: import cv2 import numpy as np from djitellopy import tello import time me = tello.Tello() me.connect() # Getting the drones battery print(me.get_battery()) me.streamon() me.takeoff() me.send_rc_control(0, 0, 0, 0) time.sleep(4.6) w, h = 360, 240 fbRange = [6200, 6800] pid = [0.4, 0.4, 0] pError = 0 def findFace(img): face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(imgGray, 1.2, 8) myFaceListC = [] myFaceListArea = [] for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cx = x + w // 2 cy = y + h // 2 area = w * h cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED) myFaceListC.append([cx, cy]) myFaceListArea.append(area) command1 = x command2 = y command3 = w command4 = h if command1 > 0: print("Drone Movement: Right") else: print("Drone Movement: Left") if command2 > 0: print("Drone Movement: Forward") else: print("Drone Movement: Backward") if command3 > 0: print(" Drone Movement: Up") else: print("Drone Movement: Down") if command4 > 0: print("Drone Movement: Yaw Right") else: print("Drone Movement: Yaw Left") if len(myFaceListArea) != 0: i = myFaceListArea.index(max(myFaceListArea)) return img, [myFaceListC[i], myFaceListArea[i]] else: return img, [[0, 0], 0] def trackFace( info, w, pid, pError): area = info[1] x, y = info[0] fb = 0 error = x - w // 2 speed = pid[0] * error + pid[1] * (error - pError) speed = int(np.clip(speed, -100, 100)) if area > fbRange[0] and area < fbRange[1]: fb = 0 elif area > fbRange[1]: fb = -20 elif area < fbRange[0] and area != 0: fb = 20 if x == 0: speed = 0 error = 0 print(speed, fb) me.send_rc_control(0, fb, 0, speed) return error cap = cv2.VideoCapture(1) while True: _, img = cap.read() img = me.get_frame_read().frame img = cv2.resize(img, (w, h)) img, info = findFace(img) pError = trackFace( info, w, pid, pError) #print(“Center”, info[0], “Area”, info[1]) cv2.imshow('person', img) if cv2.waitKey(1) & 0xFF == ord('q'): me.land() break '
## tl;dr Call [`List#reversed`][1] for a reversed-encounter-order view onto the original list, without changing the original. ```java Double l = lat.reversed().get(i); // A different encounter order, but *not* changing the list’s original encounter order. Double ll = lng.reversed().get(i); ``` ## `SequencedCollection#reversed` As of Java 21+, the [`List`][2] interface is a sub-interface of the new [`SequencedCollection`][3] interface. See [*JEP 431: Sequenced Collections*](https://openjdk.org/jeps/431) for details. As an implementation of `List` & `SequencedCollection`, [`ArrayList`][4] now offers the [`reversed`][1] method. This method returns a `List` object which is really a *view* onto the original list. So calling `List#reversed` does *not* alter the original list’s sequence, in contrast to `Collections.reverse` which *does* alter the original. ```java List < Double > oneTwoThree = List.of( 1d , 2d , 3d ); List < Double > threeTwoOne = oneTwoThree.reversed( ); System.out.println( "oneTwoThree = " + oneTwoThree ); System.out.println( "threeTwoOne = " + threeTwoOne ); System.out.println( "oneTwoThree = " + oneTwoThree ); ``` When run: ```none oneTwoThree = [1.0, 2.0, 3.0] threeTwoOne = [3.0, 2.0, 1.0] oneTwoThree = [1.0, 2.0, 3.0] ``` [1]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html#reversed() [2]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html [3]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/SequencedCollection.html [4]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/ArrayList.html
Basically I have an authentication application, where I have an authentication page where my user is sent every time the system does not recognize that he is authenticated, authentication occurs when he has a valid token registered in his localstorage with "authorization", so through "requireAuth" I created a mechanism where when a valid token is not identified in localstorage, the user is sent to the authentication page when he tries to access "/", and if he is authenticated, then he goes straight to "/ " and cannot access the auth page. This way ``` import { useContext } from "react" import { AuthContext } from "./AuthContext" import Authpage from "../pages/Authpage"; import { Navigate } from "react-router-dom"; export const RequireAuth = ({ children }: { children: JSX.Element }) => { const auth = useContext(AuthContext); if (!auth.user) { return <Navigate to="/auth" replace />; } return children; } ``` As you can see, the "/" page is protected ``` import { Routes, Route, useNavigate, useLocation } from 'react-router-dom'; import './App.css'; import Homepage from './pages/Homepage'; import Authpage from './pages/Authpage'; import Signuppage from './pages/Signuppage/Signuppage'; import { RequireAuth } from './context/RequireAuth'; import { RequireNotAuth } from './context/RequireNotAuth'; import React from 'react'; import GoogleAuthRedirect from './pages/GoogleAuthRedirect'; export function InvalidRoute() { const navigate = useNavigate(); React.useEffect(() => { navigate('/'); }, [navigate]); return null; } function App() { return ( <Routes> <Route path='/' element={<RequireAuth><Homepage /></RequireAuth>} /> <Route path='/auth' element={<Authpage />} /> <Route path='/signup' element={<Signuppage />} /> <Route path='/googleauth/:id' element={<GoogleAuthRedirect />} /> </Routes> ); } export default App; ``` This is the part where my user gets thrown after authentication before being sent to "/" ``` import * as C from './styles'; import { useNavigate, useParams } from 'react-router-dom'; import { useContext, useEffect, useState } from 'react'; import { useApi } from '../../hooks/useApi'; import { AuthContext } from '../../context/AuthContext'; type Props = {} const GoogleAuthRedirect = (props: Props) => { const { id } = useParams(); const api = useApi(); const auth = useContext(AuthContext); const navigate = useNavigate(); const [loading, setLoading] = useState(false); useEffect(() => { const getToken = async() => { try { if (id) { const token = await api.verifyToken(id); setLoading(true); setLoading(false); if (token.success) { localStorage.setItem('authorization', id); setLoading(true); setLoading(false); navigate('/'); } } else { console.log("Token não definido."); } } catch (err) { console.log(err); } } getToken(); }, []); return ( <div> <h3>Autenticando...</h3> </div> ) } export default GoogleAuthRedirect; ``` The problem is that after authenticating and sending the page "/", nothing is rendered on the page and it is only rendered if I press f5 and refresh the page. Somehow I thought it could be because it is being sent before authenticating in useEffect, so I tried loading it to extend this time and without success. ps: Homepage ``` import { useContext, useEffect, useState } from 'react'; import * as C from './styles'; import { useNavigate } from 'react-router-dom'; import { useApi } from '../../hooks/useApi'; import { AuthContext } from '../../context/AuthContext'; type Props = {} const Homepage = (props: Props) => { const navigate = useNavigate(); const auth = useContext(AuthContext); const api = useApi(); const [loading, setLoading] = useState(true); useEffect(() => { const verifyAuthTK = async () => { const authorization = localStorage.getItem('authorization'); if (authorization) { const isAuth = await api.verifyToken(authorization); if (isAuth.success) { setLoading(false); } } }; verifyAuthTK(); }, []); if (loading) { return <div>Carregando...</div>; } return ( <C.Container> homepage </C.Container> ) } export default Homepage; ```
Assuming no date comes before Jan 1, 1970 (standard epoch time). This should suffice. The code below basically counts up the number of seconds from 1/1/1970 at midnight accounting for leap years as it goes. Below assumes a basic understanding that: * Leap years have 366 days. Non leap-years have 365 days * Leap years usually occur on years divisible by 4, but not on years divisible by 100 unless also divisible by 400 (the year 2000 is a leap year, but the year 2100 will not). * That the `DateTime` struct will never have negative numbers, months less than 1 or greater than 12. Hours are assumed to be between 0-23 (military time). Minutes are a value between 0-59. * Months are assumed to be numbered between 1-12 ``` #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <inttypes.h> struct DateTime { int day, month, year, hour, minute; }; const int SECONDS_IN_DAY = 86400; int isLeapYear(int year) { if (year % 4) return 0; if (year % 400 == 0) return 1; if (year % 100 == 0) return 0; return 1; } int64_t seconds_since_epoch(const struct DateTime* dt) { size_t days_in_month[13] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 }; int year = 1970; int month = 1; int day = 1; int64_t total = 0; while (year < dt->year) { if (isLeapYear(year)) { total += 366 * SECONDS_IN_DAY; } else { total += 365 * SECONDS_IN_DAY; } year++; } if (isLeapYear(year)) { days_in_month[2] = 29; } while (month < dt->month) { total += days_in_month[month] * SECONDS_IN_DAY; month++; } total += (dt->day - day) * SECONDS_IN_DAY; total += 60 * 60 * dt->hour; // hours to seconds total += 60 * dt->minute; // minutes to seconds return total; } // Function to calculate time difference int calculate_time_difference(char date_in[], char time_in[], char date_out[], char time_out[]) { struct DateTime dt1, dt2; sscanf(date_in, "%d-%d-%d", &dt1.day, &dt1.month, &dt1.year); sscanf(time_in, "%d:%d", &dt1.hour, &dt1.minute); sscanf(date_out, "%d-%d-%d", &dt2.day, &dt2.month, &dt2.year); sscanf(time_out, "%d:%d", &dt2.hour, &dt2.minute); // Convert date and time to seconds since epoch int64_t seconds1 = seconds_since_epoch(&dt1); int64_t seconds2 = seconds_since_epoch(&dt2); auto difference_in_seconds = abs(seconds1 - seconds2); int difference_in_minutes = difference_in_seconds / 60; return difference_in_minutes; } int main() { int time_diff = calculate_time_difference("01-01-2024", "19:05", "02-01-2024", "9:05"); printf("Time difference->%i\n", time_diff); return 0; } ```
[![postman req to generate access token](https://i.stack.imgur.com/mtgv1.png)](https://i.stack.imgur.com/mtgv1.png) I was following this [miro doc](https://developers.miro.com/docs/getting-started-with-oauth) to prompt users to install Miro, got **stuck at step 3 while exchanging authorization code for access token** to make Miro API calls, but it keeps throwing 401 error even after using the valid credentials. Thanks in advance for any help or insight in this matter.
Miro oauth api throws error 401 Invalid authorization code
|javascript|node.js|api|rest|oauth|
null
I want to make a Slack App that works with images provided by the users of the channel. For discussion sake, let's say a user drops a picture, my app would detect the picture, upload it to my backend server, then analyze the image and respond with some text to the user. How do I go about detecting that a user has dropped an image into a channel that my app is watching? Is there an example I can read somewhere?
Detect image added by user in channel
|slack-api|
By my knowledge of this, clustering your node.js should prove effective in spreading the workload among several cpu cores. The code snippet for clustering is correct and should help with any scalability issues. I would suggest using clusters because I don't have much experience with Redis but i do know that it can help depending on workload and resources.
You can test if you are creating the first cell and then insert an anchor. <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-js --> var table = document.getElementById("modalTabloTable"); var thead = table.tHead; var tbody = table.tBodies[0]; while (thead.rows.length > 0) { thead.deleteRow(0); } while (tbody.rows.length > 0) { tbody.deleteRow(0); } const data = [{ id: 0, title: "Test 1" }, { id: 1, title: "Test 2" }, { id: 2, title: "Test 3" } ]; let theadrow = thead.insertRow(); Object.keys(data[0]).forEach(function(key) { let th = document.createElement("th"); th.innerText = key; theadrow.appendChild(th); }); data.forEach(function(item) { let row = tbody.insertRow(); Object.keys(item).forEach((key, i) => { let cell = row.insertCell(); if (i == 0) { let anchor = document.createElement('A'); anchor.href = `#${item[key]}`; anchor.innerText = item[key]; cell.appendChild(anchor); } else { cell.innerText = item[key]; } }); }); <!-- language: lang-html --> <table id="modalTabloTable"> <thead> </thead> <tbody> </tbody> </table> <!-- end snippet -->
I'm trying to write a chatbot. I get the error, "You tried to access openai.Completion, but this is no longer supported in openai\>=1.0.0." Could someone help me figure out how to rewrite this to work with v1.0.0 of openAI API? ``` import openai # Replace 'your_api_key_here' with your actual OpenAI API key openai.api_key = 'your_api_key_here' def chat_with_gpt(prompt): """ Sends a prompt to GPT and returns the generated response. :param prompt: The input text to send. :return: The text of the generated response. """ try: response = openai.Completion.create( model="gpt-3.5-turbo", # Adjust with the appropriate model you have access to prompt=prompt, temperature=0.7, max_tokens=150, n=1, stop=None ) return response.choices[0].text.strip() except Exception as e: return f"An error occurred: {str(e)}" def main(): print("GPT-3.5: Hello! How can I assist you today? Type 'quit' to exit.") chat_history = [] # To store the conversation history while True: user_input = input("You: ") if user_input.lower() == "quit": print("GPT-3.5: Goodbye! Have a great day!") break # Concatenate the chat history with the new message for context prompt = "\n".join(chat_history + [f"You: {user_input}", "GPT-3.5:"]) response = chat_with_gpt(prompt) print(f"GPT-3.5: {response}") # Update the chat history chat_history.extend([f"You: {user_input}", f"GPT-3.5: {response}"]) # Optional: Limit the history size to the last few exchanges to manage token limits chat_history = chat_history[-6:] if __name__ == "__main__": main() ``` I also tried openai.ChatCompletion with similar error.
**Context: ** Our app recently switched to using Custom Chrome Tabs for authentication. WebViews wouldn't allow login from Google and Facebook due to privacy restrictions. Everything worked well using `onResume` and `onNewIntent` lifecycle methods to detect when the user closes the Custom Chrome Tab and is redirected back to our app. However, a recent Chrome update introduced a minimize button (Picture-in-Picture mode) for Custom Chrome Tabs. For our authentication flow, this minimize functionality is undesirable. We want the user to complete authentication before interacting with the app again. Unfortunately, modifying Chrome Tab behavior directly is limited due to privacy concerns. Our current issue is that when the user minimizes the Custom Chrome Tab, our app using onResume interprets it as a complete closure. I've explored `onMinimized` and `onUnMinimized` APIs from CustomTabCallback, but they don't detect the scenario where the user minimizes and then closes the tab. This leaves our app's activity empty, resulting in a poor user experience. **Question: ** - Are there ways to reliably detect when a minimized Custom Chrome Tab is finally closed by the user? - Are there alternative solutions to effectively track the minimize functionality for our authentication process? **Additional Information: ** I've explored `onMinimized` and `onUnMinimized` APIs from `CustomTabCallback`. To track the minimized state, I implemented a flag. However, this approach has limitations. Inside onResume, I use a timer (set to 750 milliseconds) to periodically check the flag. If the flag shows the tab is minimized, I avoid treating it as a closed tab. This introduces a slight delay in detecting the close event, and I'm curious if there are better solutions. But as I said earlier this solution can resolve detecting the minimize state but when user closes the custom tab when it is in minimized state we dont have any way to detect. Is there any way to detect the closing of custom tab in minimized state?
Detecting of Minimize of custom Chrome Tabs on Android?
|android|authentication|android-activity|lifecycle|chrome-custom-tabs|
null