instruction
stringlengths
0
30k
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` Before, I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move "<script src="authorized.js"><script>" to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
Suppose we are using Spark on top of Hive, specifically the SQL API. Now suppose we have a table A with two partition columns, part1 and part2 and that we are insert overwriting into A with dynamic partitions from a select statement. It would look something like this: ``` INSERT OVERWRITE A PARTITION (part1, part2) -- hint here SELECT -- /*+ REPARTITION(part1, part2) */ col1 ,col2 ,part1 ,part2 FROM tmp_tbl -- or repartion here -- DISTRIBUTE BY part1, part2; ``` Now my question is: Are there any benefits in using distribute by/order by/cluster by/sort by on the select statement, either the explicit clause or the hint? Would the write operation be more efficient somehow? Or does it not matter? Or even, could this make no difference at all and it's just increasing the complexity and causing unnecessary shuffle? I searched the web and SO but didn't find anything on this specific topic. Sorry for any mistakes, I wrote this on my phone.
Building [turborepo](https://turbo.build/) with [keystonejs ](https://keystonejs.com/). Steps: ```bash // create turborepo npx create-turbo@latest my-monorepo cd my-monorepo // add keystone to turborepo cd apps npm init keystone-app my-keystone-app cd my-keystone-app npm run build ``` Here is the build process stuck with following screen: [enter image description here](https://i.stack.imgur.com/6tDSv.png) And then a bunch of errors (<Html> should not be imported outside of pages/_document) for every model, ending like this: [enter image description here](https://i.stack.imgur.com/mPCCG.png) How do I fix this error and let Keystone run inside turborepo? I tried to move the keystone folder outside of `turborepo (the same folder),` and it worked fine. Build works. But even the blank keystone inside `turborepo` becomes dead after node modules are installed. node 18.18.0 "@keystone-6/auth": "^7.0.2", "@keystone-6/core": "^5.7.2", "@keystone-6/fields-document": "^8.0.2",
null
I'm trying to create a master with all this tabs in it but it worked until tab 36 after that it just dosen't update the new tab in to the master. Formula: `=QUERY({IMPORTRANGE(B3,B4&"!A2:M");IMPORTRANGE(B3,C4&"!A2:M");IMPORTRANGE(B3,D4&"!A2:M");IMPORTRANGE(B3,E4&"!A2:M");IMPORTRANGE(B3,F4&"!A2:M");IMPORTRANGE(B3,G4&"!A2:M");IMPORTRANGE(B3,H4&"!A2:M");IMPORTRANGE(B3,I4&"!A2:M");IMPORTRANGE(B3,J4&"!A2:M");IMPORTRANGE(B3,K4&"!A2:M");IMPORTRANGE(B3,L4&"!A2:M");IMPORTRANGE(B3,M4&"!A2:M");IMPORTRANGE(B3,N4&"!A2:M");IMPORTRANGE(B3,O4&"!A2:M");IMPORTRANGE(B3,B5&"!A2:M");IMPORTRANGE(B3,C5&"!A2:M");IMPORTRANGE(B3,D5&"!A2:M");IMPORTRANGE(B3,E5&"!A2:M");IMPORTRANGE(B3,F5&"!A2:M");IMPORTRANGE(B3,G5&"!A2:M");IMPORTRANGE(B3,H5&"!A2:M");IMPORTRANGE(B3,I5&"!A2:M");IMPORTRANGE(B3,J5&"!A2:M");IMPORTRANGE(B3,K5&"!A2:M");IMPORTRANGE(B3,L5&"!A2:M");IMPORTRANGE(B3,M5&"!A2:M");IMPORTRANGE(B3,N5&"!A2:M");IMPORTRANGE(B3,O5&"!A2:M");IMPORTRANGE(B3,B6&"!A2:M");IMPORTRANGE(B3,C6&"!A2:M");IMPORTRANGE(B3,D6&"!A2:M");IMPORTRANGE(B3,E6&"!A2:M");IMPORTRANGE(B3,F6&"!A2:M");IMPORTRANGE(B3,G6&"!A2:M");IMPORTRANGE(B3,H6&"!A2:M");IMPORTRANGE(B3,I6&"!A2:M");IMPORTRANGE(B3,J6&"!A2:M")},"select * where Col1 is not null")` I just want to make sure all new tabs work I need to be able to include 50 tabs on the same master sheet.
I am trying to create a structure `Student` which contains q substructures named `Course`. Each `Course` is a structure with a credit and point `int` values. How do I set up my `Student` structure to have an integer number of `Course` structures within it? Thanks ``` struct Student{ int q; Course course[q]; }; struct Course{ int credit; int point; }; ``` I tried this but VSC is telling me it is wrong.
I have a Laravel store script. I wrote a plugin for this script that makes a backup from the database. I have routed it with the following command: Route::get('/backupsfiles/cronbackup', [BackupFilesController::class,'cronbackup'])->name('backupsfiles.cronbackup'); And I have created a cron job with the following command in cPanel: wget -O - http://subdomain.domain.com/backupsfiles/cronbackup If I execute this command from the terminal environment of my computer that has Linux operating system, this script will be executed. But the problem is that I want this script to be executed only from my cPanel host and no one else can execute it from another Linux terminal. In addition, there are other functions in the **BackupFilesController** file that even guest users can use without logging in. For example, if a backup file has been shared, they can download it without logging in. Is there a solution? thanks in advance
is there a solution to run cron job command in cpanel only from my cPanel host?
|php|laravel|cron|jobs|
PDO how to get key-value pairs from fetchAll()?
Queries per day is a project based quota. They reset at midnight west coast USA time. Don't take that quote screen at face value its not very accurate just run your code
This is my `truffle-config.js` <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> require("babel-register"); const HDWalletProvider = require("truffle-hdwallet-provider"); require("dotenv").config(); module.exports = { networks: { Sepolia: { provider: function() { return new HDWalletProvider( process.env.MNEMONIC, process.env.PROJECT_ENDPOINT, address_index=0, num_addresses=2 ); }, network_id: 11155111 , gas: 4500000, gasPrice: 10000000000, }, development: { host: process.env.LOCAL_ENDPOINT.split(":")[1].slice(2), port: process.env.LOCAL_ENDPOINT.split(":")[2], network_id: "*", }, compilers: { solc: { version: "^0.4.24", }, }, }, }; <!-- end snippet --> I am unable to get the network ID for a Sepolia test network. Below is the link of the error I am getting [1]: https://i.stack.imgur.com/HPl09.png
|javascript|blockchain|
Jetpack Compose how to reverse edge-to-edge when leaving composition
|android-activity|android-jetpack-compose|android-statusbar|android-compose|
On Windows and macOS, file chooser dialogs are built into the operating system, and there is a way for an application to tell the dialog to localize the text on buttons and titles to the system language (usually by not explicitly setting the button and title text). On Linux, while there is no system file chooser dialog, the vast majority of applications use GTK. However, GTK's file chooser dialogs require users to provide strings for the button and title text: ```c dialog = gtk_file_chooser_dialog_new ("Open File", parent_window, action, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL); ``` Leaving those strings empty or null leads to the buttons and title having no text at all, instead of having some default text. Does GTK have its own set of localized default button and title text that application developers can tap into? Note that many Linux applications use the [gettext](https://www.gnu.org/software/gettext/) internationalization library, but that depends on the application to provide a translation database for every language they wish to support, which is not what I'm looking for. I'm looking for a way for my application to show proper dialog text in every language that GTK knows about, even if my application doesn't have translated strings for them. Note also that that GTK message dialogs created with `gtk_message_dialog_new` can have correctly translated button text, assuming that the user has installed the correct language packs, as no text is explicitly specified (you just pass `GTK_BUTTONS_OK_CANCEL` to it to get correctly translated "OK" and "Cancel" buttons), but there seems to be no equivalent for file chooser dialogs.
Do GTK file chooser dialogs come with localized strings for buttons and titles?
|c|dialog|internationalization|gtk|
Make the code to: System.out.println("sin(" + a + ")^2 " + "sin(" + b + ")^2 =" + g);
I stumbled on this class when browsing the internet this morning: [`CStrBufT`][1]. I understand that it is meant to be used instead of: CString::GetBuffer CString::GetBufferSetLength CString::ReleaseBuffer But the documentation lacks a usage example, and my searches on the internet don't seem to show this class being used, but the respective `CString` methods. What is the correct way to use this wrapper when you need a buffer? [1]: https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/reference/cstrbuft-class?view=msvc-170
I am using `react-bootstrap` `Table` filteredData function should return `searchTerm` matches record from the data. I am getting empty data on search now. How to loop through Object and return true If any of the searchTerm match? I tried `some` instead of 'every' still the data is empty ```javascript import { Table, Pagination, Form } from 'react-bootstrap'; ``` ```javascript const dummyData = [ { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-18'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-17'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-16'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-15'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-14'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-13'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-12'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-11'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-19'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-22'), edit:'edite',delete:'delete'}, { consumerID: 1, consumerName : 'John', emailId: 25, mobileno:'234567' , vehiclePlte:'abcg', SchemeCashback:'abcg' , Cashbackalance:'abcg' , status :'approved',createdDate: new Date('2024-03-24'), edit:'edite',delete:'delete'}, // Add more dummy data as needed ]; const [data, setData] = useState(dummyData); ``` ```javascript const filteredData = useMemo(() => { return data.filter(row => Object.entries(row).every(([key, value]) => { if (key === 'createdDate') { // Check if createdDate is null or matches the search date return !searchDate || value.toISOString().split('T')[0] === searchDate; } return value.toString().toLowerCase().includes(searchTerm.toLowerCase()); }) ); }, [data, searchTerm, searchDate]); ``` ```javascript <input type="text" placeholder="Search..." value={searchTerm} className='rounded border border-1 border-solid border-dark' onChange={(e) => setSearchTerm(e.target.value)} /> ```
I am working on a project where I record 5 seconds of audio and store it as a wave file onto an sd card. I want to be able to play the wave file through a speaker that I have connected to the pico board, which is why I trying to find a fix without the use of audio editing software. I am able to record and play the audio, however the voice in the audio is distorted and is also very hard to hear as there is a loud ringing noise throughout the recording. With a sample rate of 22050Hz, I have read the microphone ADC.value() multiplied it by 3.3V/65535, as the ADC value is given as a 16 bit number. I also tried dividing the voltage by 4096, which is the value I am supposed to use because the pico board is 12 bit. Trying both of these have both resulted in the ringing sound still playing in the audio. I am extremely new to the microcontroller world and I don't have that great of an understanding of how sound capture works with microphones. **Am I doing something wrong or is there anything I can do to improve the quality of the recording without the use of audio editing software? **
Ringing noise overpowering voice / Recording audio with Max 9814 microphone on Raspberry pi pico using ADC Pin / Circuitpython
|audio|raspberry-pi-pico|adc|adafruit-circuitpython|
null
I have a Front End React Native application, and i am dealing with sensitive information. Asides their auth information, I tried encrypting, which i thought was a good idea to do. I'm encrypting using AWS with the keys stored on SSM, I also have to process payment transaction. These are all communicating with the server? Should i just rely on TLS to do the necessary encryption for the data in Transit? As mentioned i am currently using AWS SSM to encrypt, although i fear for the security of the application.
Is TLS enough for client server encryption or if dealing with sensitive data, its better to add ur own encryption also. for example leverage AWS SSM?
|node.js|react-native|encryption|aws-ssm|
null
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` Before, I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move "<scrip src="authorized.js"></script>" (intentional "script misplelling due to StackOverflow's formatting) to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
"Too Large Data" error on my master spreadsheet
null
{"Voters":[{"Id":11810933,"DisplayName":"NotTheDr01ds"},{"Id":2670892,"DisplayName":"greg-449"},{"Id":1940850,"DisplayName":"karel"}]}
|sql|json|db2|db2-400|
I am facing a issue and cannot solve it even though I looked for some other questions related to nginx 499 error. I am using Django for my project, and the problem is from the social login (kakao login) error. my accounts/views.py looks like this: ``` BASE_DIR = Path(__file__).resolve().parent.parent env_file = BASE_DIR / ".env" if os.getenv("DJANGO_ENV") == "production": env_file = BASE_DIR / ".env.prod" env = environ.Env() env.read_env(env_file) BASE_URL = env("BASE_URL") KAKAO_CALLBACK_URI = BASE_URL + "accounts/kakao/callback/" REST_API_KEY = env("KAKAO_REST_API_KEY") CLIENT_SECRET = env("KAKAO_CLIENT_SECRET_KEY") @extend_schema( summary="카카오 로그인", description="카카오 로그인 페이지로 리다이렉트합니다.", responses={ 302: OpenApiResponse( description="Redirects to the Kakao login page.", response=None ) }, ) @api_view(["GET"]) @permission_classes([AllowAny]) def kakao_login(request): return redirect( f"https://kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={KAKAO_CALLBACK_URI}&response_type=code" ) # @extend_schema(exclude=True) # @permission_classes([AllowAny]) # def finish_login(data): # accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data) # return accept @extend_schema(exclude=True) @permission_classes([AllowAny]) def kakao_callback(request): code = request.GET.get("code") print(f"code: {code}") # Access Token Request token_req = requests.get( f"https://kauth.kakao.com/oauth/token?grant_type=authorization_code&client_id={REST_API_KEY}&client_secret={CLIENT_SECRET}&redirect_uri={KAKAO_CALLBACK_URI}&code={code}" ) print(f"token_req: {token_req}") token_req_json = token_req.json() print(f"token_req_json: {token_req_json}") error = token_req_json.get("error") if error is not None: raise JSONDecodeError(error) access_token = token_req_json.get("access_token") print(f"access_token: {access_token}") # Email Request profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}, ) profile_data = profile_request.json() print(f"profile_data: {profile_data}") kakao_oid = profile_data.get("id") kakao_account = profile_data.get("kakao_account") username = kakao_account["profile"]["nickname"] profile_image_url = kakao_account["profile"]["profile_image_url"] email = kakao_account.get("email") # 회원가입, 로그인 로직 data = {"access_token": access_token, "code": code} # TODO 유저 프로필 이미지 저장하도록 try: user = CustomUser.objects.get(email=email) # 유저가 존재하는 경우 accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data) accept_status = accept.status_code print(accept_status) if accept_status != 200: return Response({"err_msg": "failed to signin"}, status=accept_status) accept_json = accept.json() print(f"accept_json, {accept_json}") # key 이름 변경 accept_json["accessToken"] = accept_json.pop("access") accept_json["refreshToken"] = accept_json.pop("refresh") accept_json["userProfile"] = accept_json.pop("user") accept_json["userProfile"]["id"] = accept_json["userProfile"].pop("pk") return JsonResponse(accept_json) except CustomUser.DoesNotExist: # 기존에 가입된 유저가 없으면 새로 가입 # accept = finish_login(data) accept = requests.post(f"{BASE_URL}accounts/kakao/login/finish/", data=data) accept_status = accept.status_code if accept_status != 200: return Response({"err_msg": "failed to signup"}, status=accept_status) # user의 pk, email, first name, last name과 Access Token, Refresh token 가져옴 accept_json = accept.json() # key 이름 변경 accept_json["accessToken"] = accept_json.pop("access") accept_json["refreshToken"] = accept_json.pop("refresh") accept_json["userProfile"] = accept_json.pop("user") accept_json["userProfile"]["id"] = accept_json["userProfile"].pop("pk") return JsonResponse(accept_json) @extend_schema(exclude=True) class KakaoLoginView(SocialLoginView): adapter_class = kakao_view.KakaoOAuth2Adapter client_class = OAuth2Client callback_url = KAKAO_CALLBACK_URI ``` and this is my urls.py: ``` urlpatterns = [ path("kakao/login/", views.kakao_login, name="kakao_login"), path("kakao/callback/", views.kakao_callback, name="kakao_callback"), path( "kakao/login/finish/", views.KakaoLoginView.as_view(), name="kakao_login_todjango", ) ] ``` and myproject/views.py ``` urlpatterns = [ path("", kakao_login_page, name="home"), path("admin/", admin.site.urls), # path("accounts/", include("dj_rest_auth.urls")), # path('accounts/', include('allauth.urls')), path("accounts/", include("accounts.urls")), path("registration/", include("dj_rest_auth.registration.urls")), # swagger 관련 path("api/schema/", SpectacularAPIView.as_view(), name="schema"), path( "api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui", ), path( "api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc", ), ] ``` and my nginx.conf ``` upstream resumai { server web:8000; } server { listen 80; location / { proxy_pass http://resumai; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_connect_timeout 300s; proxy_send_timeout 300s; proxy_read_timeout 300s; send_timeout 300s; } location /static/ { alias /home/app/web/static/; } location /media/ { alias /home/app/web/media/; } } ``` The problem is that, when I access to page **/accounts/kakao/login**,I get redirect response (302) which is right. However, I get 502 error from the web, and 499 error from the nginx docker container which looks like this (I hid my code): [enter image description here](https://i.stack.imgur.com/56FeY.png) This is my docker nginx error: [enter image description here](https://i.stack.imgur.com/RRbiX.png) I thought this may be a issue related to load balancer which I am using, but I do not know how to solve this problem. Is there somebody who can help me handling with this issue please ??
Docker nginx ELB(load balancer) 499 error
|django|nginx|amazon-ec2|load-balancing|amazon-elb|
null
I have a collection of documents with a **timestamp** field named 'date'. I want to query a single document with the specific 'date' : 2024/02/29 00:00:00 GMT05.30. So in flutter I'm trying to get that doc by following query StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('mycolloection').where('date', isEqualTo: DateTime(2024,2,29,0,0,0,0,0),).snapshots(),), but above code is not retrieving any documents. So I played with isGreaterThan and isLesserThan for several hours and found out there is a hidden milliseconds value in the firestore timestamp. So I have to give a milliseconds value as well. But this value is changing with different dates and it looks like completely random number. Can anyone explain what is happening here....
Flutter firestore isEqualTo 'timestamp' is not working
|flutter|firebase|google-cloud-firestore|
I have a list of form [[[key1,value1],[key2,value2],...,500],...,n] - aka L2 orderbook data with 500 levels. I want to translate this list into a dataframe, containing columns key_1,...,key_500 and value_1,...,value_500. - A dataframe that has a price + volume column for each level (e.g. level_1_volume, level_2_volume, ..., level_500_volume) My current solution is simply looping through the existing dataframe (which simply has this list as a column) with df.iterrows(), extracting the values into separate lists, then creating dataframes using these lists and merging these as columns. Doesn't feel terribly efficient compared to other operations on my data set, is there some way to do this with built-in methods? List1 = [[key1.1,val1.1],[key2.1,val2.1],...] List2 = [[key1.2,val1.2],[key2.2,val2.2],...] key1_column, val1_column, key2_column, val2_column Row_List1 key1.1 val1.1 key2.1 val2.1 Row_List2 key1.2 val1.2 key2.2 val2.2 Current Solution # Initialize empty lists for prices and volumes prices_bids = [[] for _ in range(500)] volumes_bids = [[] for _ in range(500)] prices_asks = [[] for _ in range(500)] volumes_asks = [[] for _ in range(500)] # Iterate through each row for index, row in df.iterrows(): attributes = row["bids"] result_bids = [[key,attributes[key]] for key in sorted(attributes.keys(), reverse=True)] attributes = row["asks"] result_asks = [[key,attributes[key]] for key in sorted(attributes.keys(), reverse=False)] for i in range(500): prices_bids[i].append(np.float64(result_bids[i][0])) volumes_bids[i].append(np.float64(result_bids[i][1])) prices_asks[i].append(np.float64(result_asks[i][0])) volumes_asks[i].append(np.float64(result_asks[i][1])) # Create DataFrame from lists for i in range(500): # Expressing prices as spreads df[f"bid_level_{i}_price"] = pd.Series((df["mid_price"]/pd.Series(prices_bids[i],dtype='float64')-1)*10000,dtype="float64") df[f"bid_level_{i}_volume"] = pd.Series(volumes_bids[i],dtype='float64') df[f"ask_level_{i}_price"] = pd.Series((df["mid_price"]/pd.Series(prices_asks[i],dtype='float64')-1)*10000,dtype="float64") df[f"ask_level_{i}_volume"] = pd.Series(volumes_asks[i],dtype='float64')
This is due to `executable_path` is an argument of `webdriver.chrome.service.Service`, see [ducumentation][1] Just use driver = webdriver.Chrome() [1]: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.chrome.webdriver
So after using openais chatgptand dall-e im using gym and theres this error with my code thats the same error that keeps popping out (for reference i havee intel hd 3000 and its saying theres something which is not there in my opengl) so the code and error is this code (main.py): ``` import gym import matplotlib.pyplot as plt env = gym.make('MountainCar-v0') # Observation and action space obs_space = env.observation_space action_space = env.action_space print("The observation space: {}".format(obs_space)) print("The action space: {}".format(action_space)) # reset the environment and see the initial observation obs = env.reset() print("The initial observation is {}".format(obs)) # Sample a random action from the entire action space random_action = env.action_space.sample() # # Take the action and get the new observation space new_obs, reward, done, info = env.step(random_action) print("The new observation is {}".format(new_obs)) env.render(mode = "human") ``` error: ``` Warning: Parameters to load are deprecated. Call .resolve and .require separately. result = entry_point.load(False) The observation space: Box(2,) The action space: Discrete(3) The initial observation is [-0.53907843 0. ] The new observation is [-0.53996238 -0.00088394] Traceback (most recent call last): File "c:\Users\Acer\Desktop\game-bot\main.py", line 23, in <module> env.render(mode = "human") File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\gym\core.py", line 174, in render return self._render(mode=mode, close=close) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\gym\core.py", line 341, in _render return self.env.render(mode, close) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\gym\core.py", line 174, in render return self._render(mode=mode, close=close) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\gym\envs\classic_control\mountain_car.py", line 79, in _render self.viewer = rendering.Viewer(screen_width, screen_height) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\gym\envs\classic_control\rendering.py", line 51, in __init__ self.window = pyglet.window.Window(width=width, height=height, display=display) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\window\win32\__init__.py", line 104, in __init__ super(Win32Window, self).__init__(*args, **kwargs) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\window\__init__.py", line 582, in __init__ self._create_projection() File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\window\__init__.py", line 590, in _create_projection shader.Shader(self._default_vertex_source, 'vertex'), File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\graphics\shader.py", line 794, in __init__ shader_id = glCreateShader(shader_type) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\gl\lib_wgl.py", line 66, in __call__ return self.func(*args, **kwargs) File "C:\Users\Acer\AppData\Local\Programs\Python\Python310\lib\site-packages\pyglet\gl\lib.py", line 25, in MissingFunction raise MissingFunctionException(name, requires, suggestions) pyglet.gl.lib.MissingFunctionException: glCreateShader is not exported by the available OpenGL driver. OpenGL 2.0 is required for this functionality. ``` I did try to update opengl but still the same error. I checked lierally all the answers but still im got the same error.
React state with JSX elements is setting the last ref in ref array to null
|javascript|reactjs|
I am new to Wordpress development and I am trying to create a plugin which makes it possible for a user to create a custom image. I have created the `custom-image` plugin using html, css and javascript. The plugin is shown with a shortcode using this code in `custom-image.php`: function form_shortcode() { this_is_a_function_which_outputs_html(); return ob_get_clean(); } add_shortcode('custom-image-shortcode', 'form_shortcode'); Below, you can find the current structure of my plugin which is located in `public_html/wp-content/plugins/`: - custom map -- css -- img -- js -- custom-image.php The css, img and js folders contains some code for the tool defined in the `custom-image.php` However, I would like to create a button which would make it possible to add the customised image as a product to the Woocommerce Cart. I have tried the following, but that does not work: Following code in `custom-image/js/custom-add-to-cart.js`: jQuery( function($) { if (typeof wc_params_custom === 'undefined') return false; $('.custom.add-to-cart').on('click', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: wc_params_custom.ajax_url, data: { 'action' :'custom_add_to_cart', 'nonce' : wc_params_custom.nonce, // ==> nonce 'product_id' : '160', // ==> integer 'quantity' : 1, 'height' : '96 in.', 'width' : '120 in.', 'totalArea' : '80 sq ft', 'cost' : '$636.00', 'numPanels' : 5, 'enteredHeight' : '96 in.', 'enteredWidth' : '120 in.' }, success: function (response) { $(document.body).trigger("wc_fragment_refresh"); console.log(response); }, error: function (error) { console.log(error); } }); }); }); Following code in `admin-ajax.php`: add_action('wp_enqueue_scripts', 'enqueue_custom_ajax_add_to_cart_scripts'); function enqueue_custom_ajax_add_to_cart_scripts() { wp_enqueue_script( 'custom-add-to-cart', plugins_url('/custom-image/js/') . '/custom-add-to-cart.js', array('jquery'), '1.0', true ); wp_localize_script( 'custom-add-to-cart', 'wc_params_custom', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('nonce_custom_atc') ) ); } // PHP WP Ajax receiver add_action('wp_ajax_custom_add_to_cart', 'custom_ajax_add_to_cart'); add_action('wp_ajax_nopriv_custom_add_to_cart', 'custom_ajax_add_to_cart'); function custom_ajax_add_to_cart() { $cart_item_key = null; // Initializing if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'nonce_custom_atc') && isset($_POST['product_id']) && $_POST['product_id'] > 0 && isset($_POST['quantity']) && $_POST['quantity'] > 0) { $cart_item_key = WC()->cart->add_to_cart( intval($_POST['product_id']), intval($_POST['quantity']), 0, array(), array( 'height' => isset($_POST['height']) ? sanitize_text_field($_POST['height']) : '', 'width' => isset($_POST['width']) ? sanitize_text_field($_POST['width']) : '', 'totalArea' => isset($_POST['totalArea']) ? sanitize_text_field($_POST['totalArea']) : '', 'cost' => isset($_POST['cost']) ? sanitize_text_field($_POST['cost']) : '', 'numPanels' => isset($_POST['numPanels']) ? intval($_POST['numPanels']) : '', 'enteredHeight' => isset($_POST['enteredHeight']) ? sanitize_text_field($_POST['enteredHeight']) : '', 'enteredWidth' => isset($_POST['enteredWidth']) ? sanitize_text_field($_POST['enteredWidth']) : '', ) ); } wp_die( $cart_item_key ? "Cart item key: {$cart_item_key}" : "Error: not added!" ); } And a simple button in the `custom-image.php`, so it is shown in the shortcode: <button class="custom add-to-cart">Add to Cart</button> Someone advice? I would like to keep the code in the plugin repository, so it stays maintainable, if its possible.
Categories and courses are two tables. Based on Category, an 'n' number of data can be inserted into the course. While fetching the API response, it should be like below. **Controller** public function catlist($catid) { $category = DB::table('courses') ->join('categories', 'courses.category_id', '=', 'categories.id')// joining the Categories table , where category_id and categories id are same ->select( 'categories.id as catid', 'categories.name as catname', 'courses.id as courseid', 'courses.title as coursename' ) ->where('courses.category_id', '=', $catid) ->get(); foreach ($category as $cat) { $data = [ 'category'=>[ "id" => $cat->catid, "name" => $cat->catname, ], 'courselist'=>[ "id" => $cat->courseid, "name" => $cat->coursename, ] ]; } return response()->json([ 'success' => true, 'data' => $data, ],200); } The actual result is: "data": { "category": { "id": 1, "name": "Test Category" }, "courseList": { "id": 2, "title": "Course 2" } } Expected results will be: ``` data=[ category: { id: 1, name: "Test Category" }, courseList: [ { id: 1, title: "Course 1", }, { id: 2, title: "Course 2", }, ], ] ```
Iterating over joined query data in Laravel Lumen
|laravel|lumen|laravel-10|
I'm new to developing Visual Studio Extensions and I'm trying to make one that runs Visual Studio's "Replace in Files" (Edit.ReplaceinFiles) command and then automatically runs the Navigate Backwards (View.NavigateBackward) command so that the view doesn't move to the next matching result after replacing a line of code. Preventing the view from moving until I decide so would be very helpful when testing REGEX (regular expressions) in the find-and-replace command as it would allow me to verify that text was replaced properly before moving to the next file or next matching code line in the same document. I followed [this tutorial](https://www.youtube.com/watch?v=Pk7jdsvEhfc) for creating a basic extension using a [Extensibility Essentials 2022](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ExtensibilityEssentials2022) Command template and upon trying to use DTE code to run a visual studio command I get the following error: `CSOI 03: The name 'GetService' does not exist in the current context` Below is the code from my "MyCommand.cs" VSIX project file that I'm working from. What exactly do I have to do to make the DTE code work or is there a better way of trying to run Visual Studio Commands from an extension? ```c# using System.ComponentModel.Composition; using System.Linq; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Tassk = System.Threading.Tasks.Task; namespace ReplaceNoScroll { [Command(PackageIds.MyCommand)] internal sealed class MyCommand : BaseCommand<MyCommand> { protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { //Get reference to the current active document var docView = await VS.Documents.GetActiveDocumentViewAsync(); // Get the DTE object var dte = (EnvDTE80.DTE2)GetService(typeof(EnvDTE.DTE)); // Execute the "Navigate Backwards" command dte.ExecuteCommand("View.NavigateBackward"); } } } ```
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` Before, I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move "<scrip src="authorized.js"></script>``` to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
I find it to be similar to Java, but with more C-style functionality. Which I guess makes it better, since you can have [unions](https://stackoverflow.com/a/126807/16217248) and pointers (though pointers can only be used in `unsafe` code) but both are a staple in most of my programming. Though I have not used C# much.
OpenGL Error [Python [OpenGL] [OpenAI Gym]
|python|opengl|openai-gym|
null
Generic type 'ɵɵComponentDeclaration' requires 7 type argument(s). 18 static ɵcmp: i0.ɵɵComponentDeclaration<FaStackComponent, "fa-stack", never, { "size": "size"; }, {}, never, ["*"], false>; i want to access fa icons in angular.
Angular genric error while using fontawesome in angular12
|angular12|
null
The following: ``` interface IThing { virtual string A => "A"; } ``` Is the so called [default interface method][1] and virtual as far as I can see actually does nothing because: > The `virtual` modifier may be used on a function member that would otherwise be implicitly `virtual` I.e. it just an implicit declaration of the fact that method is virtual since the team decided to not restrict such things. See also the [Virtual Modifier vs Sealed Modifier][2] part of the spec: > Decisions: Made in the LDM 2017-04-05: > - non-`virtual` should be explicitly expressed through `sealed` or `private`. > - `sealed` is the keyword to make interface instance members with bodies non-`virtual` > - We want to allow all modifiers in interfaces > - ... Note that default implemented `IThing.A` is not part of the `Thing`, hence you can't do `new Thing().A`, you need to cast to the interface first. If you want to override the `IThing.A` in the `Thing2` then you can implement the interface directly: ``` class Thing2: Thing, IThing { public string A => "!"; } Console.WriteLine(((IThing)new Thing()).A); // Prints "A" Console.WriteLine(((IThing)new Thing2()).A); // Prints "!" ``` Aother way would be declaring `public virtual string A` in the `Thing` so your current code for `Thing2` works: ``` class Thing: IThing { public virtual string A => "A"; } class Thing2: Thing { public override string A => "!"; } ``` [1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods [2]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#virtual-modifier-vs-sealed-modifier
I'm trying to build and push a docker image from a dockerfile in my private repo in dockerhub using buildctl-daemonless.sh command using argo workflow, the following is the step in the workflow that does the job. The problem is that I get that it runs successfully but I couldn't find the image pushed ``` - name: image inputs: parameters: - name: path - name: image volumes: - name: test-secret-secret secret: secretName: test-secret-secret container: readinessProbe: exec: command: [ sh, -c, "buildctl debug workers" ] image: moby/buildkit:v0.9.3-rootless volumeMounts: - name: work mountPath: /work - name: test-secret-secret mountPath: /.docker workingDir: /work/{{inputs.parameters.path}} env: - name: BUILDKITD_FLAGS value: --oci-worker-no-process-sandbox - name: DOCKER_CONFIG value: /.docker command: [ sh, -c, "buildctl-daemonless.sh" ] args: - build - --frontend=dockerfile.v0 - --local context=. - --local dockerfile=. - --output type=image,name=docker.io/ineselmufti/repo-test:argoworkflow,push=true ``` The only thing I get from the logs is this ``` time="2024-03-31T11:30:27 UTC" level=info msg="capturing logs" argo=true NAME: buildctl - build utility USAGE: buildctl [global options] command [command options] [arguments...] VERSION: v0.9.3 COMMANDS: du disk usage prune clean up build cache build, b build debug debug utilities help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --debug enable debug output in logs --addr value buildkitd address (default: "unix:///run/user/1000/buildkit/buildkitd.sock") --tlsservername value buildkitd server name for certificate validation --tlscacert value CA certificate for validation --tlscert value client certificate --tlskey value client key --tlsdir value directory containing CA certificate, client certificate, and client key --timeout value timeout backend connection after value seconds (default: 5) --help, -h show help --version, -v print the version ``` Any thoughts please what could be the problem
I am getting the error below, and spinning wheels figuring it out. It only happens during my github actions build. When I run the build locally, it works fine and I can hit the route handler. I can also run the github action locally using [act](https://github.com/nektos/act) and Docker, and then I get the error as well. Here's the error: ``` TypeError [ERR_INVALID_URL]: Invalid URL at new NodeError (node:internal/errors:405:5) at new URL (node:internal/url:676:13) at new ni (/home/runner/work/frontend/.next/server/app/api/reports/route.js:6:40210) ``` And the file in question is `src/app/api/reports/route.tsx`: ``` export async function GET(request: Request) { const { searchParams } = new URL(request.url); // <- here is the problem const id = searchParams.get('id'); const partitionKey = searchParams.get('partitionKey'); if (!id || !partitionKey) { return NextResponse.json({msg: 'Success'}); } ``` The result I expect is that the build completes and I can hit: `http://localhost:3000/api/reports?id=SOME_ID&partitionKey=SOME_KEY` And get a result. The actual result is the error above, during build time (not even runtime). When I run it locally, the URL above works. I have tried a ton, including: 1. I changed the name of the file to `route-bad.tsx` and the build succeeds 2. I took out the URL parsing and the build succeeds. 3. I tried an alternate form of build parsing the just uses strings and the `qs` library. I still get the error. Any help is appreciated!
INVALID_URL deploying next.js app to Azure Static Webapp during github actions build
|typescript|next.js|github-actions|azure-static-web-app|
null
First, as I said in the comment, you can use an enum for this. Its variants will be assigned consecutive numbers (starting from zero), and you can retrieve the associated number with `as`: `Enum::Variant as usize`. Second, Rust indeed does not support this C syntax for initializing arrays, but it does have const-eval more powerful than C's: ```rust enum Types { Normal, Grass, Fire, Water, Electric, Fighting, Flying, Rock, } static MATCHUP_TABLE: [[f32; 8]; 8] = { let mut result = [[0.; 8]; 8]; result[Types::Normal as usize][Types::Normal as usize] = 1.; result[Types::Normal as usize][Types::Grass as usize] = 1.; // ... result[Types::Grass as usize][Types::Normal as usize] = 1.; // ... result }; ``` This looks terrible compared to the C code, but fortunately Rust also has macros: ```rust macro_rules! init_types { { $init:expr; $( [$key:ident] = $value:expr ),* $(,)? } => {{ // Ensure there are no duplicates or missing entries. if false { match loop {} { $( Types::$key => {})* } } let mut result = [$init; Types::VARIANTS_COUNT]; $( result[Types::$key as usize] = $value; )* result }}; } enum Types { Normal, Grass, Fire, Water, Electric, Fighting, Flying, Rock, } impl Types { const VARIANTS_COUNT: usize = 8; } static MATCHUP_TABLE: [[f32; Types::VARIANTS_COUNT]; Types::VARIANTS_COUNT] = init_types! { [0.; 8]; [Normal] = [1.; Types::VARIANTS_COUNT], [Grass] = init_types! { 0.; [Normal] = 1., [Grass] = 1., [Fire] = 1., [Water] = 1., [Electric] = 1., [Fighting] = 1., [Flying] = 1., [Rock] = 1. }, // ... }; ``` And this has almost the syntax of the C code. The only awkwardness is the need to specify a start value, but this isn't a big deal, and can be worked around if needed.
Before I start, I am very new to `redux` and quite new to `React` in general. I am integrating the `Subscription` functionality of Razorpay for an app. Everything is working fine but when I try to chain `dispatch` of HTTP endpoints, it is not working. Here is the code snippet: ```js const SubscriptionForm: FC<ISubscriptionForm> = ({ planId, totalCount }) => { const { data: user, isFetching } = useAppSelector((store) => store.user.details); const dispatch = useAppDispatch(); const [Razorpay] = useRazorpay(); const handlePayment = async (subscription_id: any, userDetails: { name: string; email: string; phone: string}) => { const options: any = { key: process.env.REACT_APP_RAZORPAY_ID, amount: "500", currency: "USD", name: "Test App", description: "Test Transaction", image: Logo, subscription_id: subscription_id, handler: (razaorpayResponse: { razorpay_payment_id: any; razorpay_subscription_id: any; razorpay_signature: any; }) => { dispatch(SubscriptionRestService.verifySignature({ razaorpayResponse})) .then((response) => { if (SubscriptionRestService.verifySignature.fulfilled.match(response)) { console.log("Success:", response); dispatch(SubscriptionRestService.updateSubscriptionStatus({ subscriptionId: subscription_id, status: "active" })) .then((response) => { if (SubscriptionRestService.updateSubscriptionStatus.fulfilled.match(response)) { console.log("Success:", response); toast.success("Subscription was activated successfully"); } else { console.error("Error:", response); toast.error("Subscription activation may have failed. Please contact support if payment was deducted"); } }) .catch((error) => { console.error("Error:", error); }); toast.success("Subscription was activated successfully"); } else { console.error("Error:", response); toast.error("Subscription may have failed. Please contact support if payment was deducted"); } }) .catch((error) => { console.error("Error:", error); }); }, theme: { color: "#e9e6e6", }, prefill: { name: userDetails.name, email: userDetails.email, contact: userDetails.phone, } }; const rzp1 = new Razorpay(options); rzp1.open(); } ``` This thing works perfectly fine as long as I remove the inner dispatch: `dispatch(SubscriptionRestService.updateSubscriptionStatus({ subscriptionId: subscription_id, status: "active" }))` But when I add the inner dispatch it gives `Invalid Hook Call` Error I want to get away with this error and have the `chained dispatch` working. The 2 dispatch `asyncThunks` are as follows: ```js const verifySignature = createAsyncThunk( 'subscription/verify_signature', async (args:{razaorpayResponse: { razorpay_payment_id: any; razorpay_subscription_id: any; razorpay_signature: any; }}, { rejectWithValue }) => { try { return (await HttpClient.post('/payment/verify-signature', args.razaorpayResponse)).data; } catch (error: any) { return rejectWithValue(error.message); } }); const updateSubscriptionStatus = createAsyncThunk( 'subscription/update_status', async (args: { subscriptionId: any, status: any }, { rejectWithValue }) => { try { return (await HttpClient.post('/payment/update-subscription-status', args)).data; } catch (error: any) { return rejectWithValue(error.message); } }); ``` The `verifySignature` is working fine but when I dispatch the `updateSubscriptionStatus` it fails.
Chaining of dispatch HTTP requests isn't working in Razorpay React
|javascript|reactjs|react-hooks|react-redux|razorpay|
null
How to "MakeScreenshoot" FullPage on TListBox or VertScrollbox? I code like this, but the result not full. Some component not captured when i uses "Makescreenshoot" var ABitmap : TBitmap; var OldHeight := vsReceipt.Height; var AAlign := vsReceipt.Align; var AAnchor := vsReceipt.Anchors; try vsReceipt.Align := TAlignLayout.None; vsReceipt.Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight]; vsReceipt.Height := lbReceipt.ContentBounds.Size.cy + 24; ABitmap := lbReceipt.MakeScreenshot; if Assigned(ABitmap) then begin ABitmap.SaveToFile('bfaprintreceipt.png'); ABitmap.DisposeOf; end; finally vsReceipt.Align := AAlign; vsReceipt.Height := OldHeight; vsReceipt.Anchors := AAnchor; end; And the result like this > [![Result][1]][1] I want result like this > [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/J71m6.png [2]: https://i.stack.imgur.com/zD510.png
How to MakeScreenshot fullpage on Delphi
|android|delphi|listbox|firemonkey|
Using the following sequence of methods I was able to get a rough approximation. It is a very simple solution and might not work for all cases. **1. Morphological operations** To merge neighboring lines perform morphological (dilation) operations on the binary image. ```python img = cv2.imread('image_path', 0) # grayscale image img1 = cv2.imread('image_path', 1) # color image th = cv2.threshold(img, 150, 255, cv2.THRESH_BINARY)[1] kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (19, 19)) morph = cv2.morphologyEx(th, cv2.MORPH_DILATE, kernel) ``` [![enter image description here][1]][1] **2. Finding contours and extreme points** 1. My idea now is to find contours. 2. Then find the extreme points of each contour. 3. Finally find the closest distance among these extreme points between neighboring contours. And draw a line between them. ```python cnts1 = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)` cnts = cnts1[0] # storing contours in a variable ``` Lets take a quick detour to visualize where these extreme points are present: ```python # visualize extreme points for each contour for c in cnts: left = tuple(c[c[:, :, 0].argmin()][0]) right = tuple(c[c[:, :, 0].argmax()][0]) top = tuple(c[c[:, :, 1].argmin()][0]) bottom = tuple(c[c[:, :, 1].argmax()][0]) # Draw dots onto image cv2.circle(img1, left, 8, (0, 50, 255), -1) cv2.circle(img1, right, 8, (0, 255, 255), -1) cv2.circle(img1, top, 8, (255, 50, 0), -1) cv2.circle(img1, bottom, 8, (255, 255, 0), -1) ``` (***Note:*** The extreme points points are based of contours from morphological operations, but drawn on the original image) [![enter image description here][2]][2] **3. Finding closest distances between neighboring contours** Sorry for the many loops. 1. First, iterate through every contour (split line) in the image. 2. Find the extreme points for them. Extreme points mean top-most, bottom-most, right-most and left-most points based on its respective bounding box. 3. Compare the distance between every extreme point of a contour with those of every other contour. And draw a line between points with the least distance. ```python for i in range(len(cnts)): min_dist = max(img.shape[0], img.shape[1]) cl = [] ci = cnts[i] ci_left = tuple(ci[ci[:, :, 0].argmin()][0]) ci_right = tuple(ci[ci[:, :, 0].argmax()][0]) ci_top = tuple(ci[ci[:, :, 1].argmin()][0]) ci_bottom = tuple(ci[ci[:, :, 1].argmax()][0]) ci_list = [ci_bottom, ci_left, ci_right, ci_top] for j in range(i + 1, len(cnts)): cj = cnts[j] cj_left = tuple(cj[cj[:, :, 0].argmin()][0]) cj_right = tuple(cj[cj[:, :, 0].argmax()][0]) cj_top = tuple(cj[cj[:, :, 1].argmin()][0]) cj_bottom = tuple(cj[cj[:, :, 1].argmax()][0]) cj_list = [cj_bottom, cj_left, cj_right, cj_top] for pt1 in ci_list: for pt2 in cj_list: dist = int(np.linalg.norm(np.array(pt1) - np.array(pt2))) #dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 ) if dist < min_dist: min_dist = dist cl = [] cl.append([pt1, pt2, min_dist]) if len(cl) > 0: cv2.line(img1, cl[0][0], cl[0][1], (255, 255, 255), thickness = 5) ``` [![enter image description here][3]][3] **4. Post-processing** Since the final output is not perfect, you can perform additional morphology operations and then skeletonize it. [1]: https://i.stack.imgur.com/bNRGx.jpg [2]: https://i.stack.imgur.com/g7Oko.jpg [3]: https://i.stack.imgur.com/YTxsi.jpg
Couldn't find the image pushed in dockerhub using buildkit and argo workflow
|argo-workflows|docker-buildkit|argo|buildkit|
null
By default, a `QLineEdit` is greyed-out when disabled. If you set a stylesheet with a simple directive, e.g. setting a border, this cancels that default behaviour. Fortunately it is possible to mimic the default behaviour, like so: qle.setStyleSheet('QLineEdit[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}') But how might I *combine* this conditional greying-out with setting a border (unconditionally)? Here is an MRE: import sys from PyQt5 import QtWidgets class Window(QtWidgets.QWidget): def __init__(self): super().__init__() self.setWindowTitle("QLE stylesheet question") self.setMinimumSize(400, 30) layout = QtWidgets.QVBoxLayout() qle = QtWidgets.QLineEdit() qle.setObjectName('qle') # qle.setStyleSheet('border:4px solid yellow;') # this sets up the style sheet to reproduce the default PyQt behaviour for a QLE (greyed-out if disabled, otherwise not) # qle.setStyleSheet('QLineEdit[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}') # doesn't work: when disabled is not greyed-out! qle.setStyleSheet('#qle {border:4px solid yellow;} #qle[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}') # qle.setEnabled(False) # uncomment to see "disabled" appearance layout.addWidget(qle) self.setLayout(layout) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
Grey-out QLineEdit as per disabled state automatically, combined with non-conditional style sheet directive?
|python|pyqt|qtstylesheets|
The data structure for this is a [Trie][1] (Prefix Tree): A tree-like data structure used to store a dynamic set of strings where each node represents a single character. * Time Efficiency: Search, Insertion & Deletion: With a time-complexity of **O(m)** where m is the length of the string. * Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings. -- Trie Visualization for your input (Green nodes are marked: endOfString): [![enter image description here][3]][3] -- PHP implementation: ```php <?php class TrieNode { public $childNode = []; // Associative array to store child nodes public $endOfString = false; // Flag to indicate end of a string } class Trie { private $root; public function __construct() { $this->root = new TrieNode(); } public function insert($string) { if (!empty($string)) { $this->insertRecursive($this->root, $string); } } private function insertRecursive(&$node, $string) { if (empty($string)) { $node->endOfString = true; return; } $firstChar = $string[0]; $remainingString = substr($string, 1); if (!isset($node->childNode[$firstChar])) { $node->childNode[$firstChar] = new TrieNode(); } $this->insertRecursive($node->childNode[$firstChar], $remainingString); } public function commonPrefix() { $commonPrefix = ''; $this->commonPrefixRecursive($this->root, $commonPrefix); return $commonPrefix; } private function commonPrefixRecursive($node, &$commonPrefix) { if (count($node->childNode) !== 1 || $node->endOfString) { return; } $firstChar = array_key_first($node->childNode); $commonPrefix .= $firstChar; $this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix); } } // Example usage $trie = new Trie(); $trie->insert("Softball - Counties"); $trie->insert("Softball - Eastern"); $trie->insert("Softball - North Harbour"); $trie->insert("Softball - South"); $trie->insert("Softball - Western"); echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL; ?> ``` Output: Common prefix: Softball - [Demo][2] [1]: https://en.wikipedia.org/wiki/Trie [2]: https://onecompiler.com/php/428w3k8pe [3]: https://i.stack.imgur.com/aY2XN.png
I have a long timeframe where I want to store every time a neuron "fires" during this time. Since "firing" is a discrete event, this can be done by simply recording the time of each event into a C++ vector, thereby creating a much sparser representation then storing information about every point in time. What makes this difficult is that I want to deal with several neurons at once. My solution to this problem has been to create a class includes a map from each neuron's identifier (an integer) to that neuron's vector: using namespace std; typedef pair<int,vector<int> > Pair; typedef map<int,vector<int> > Map; class SpikeTrain{ public: Map * train;//Spike train double * dt;//timestep int * t_now;//curent timestep (index) vector<int>::iterator * spikeIt;//Array of iterators for traversal. //Methods, etc; }; The map part of this works fine. The problem comes when I try to ask: how many events occur at any given time step. This is an easier question to ask then to answer, because, if you remember, only the times at which events occur on each neuron are stored. I therefore turn to the strategy of using iterators initializing an array of iterators: void SpikeTrain::beginIterator(){ spikeIt= new vector<int>::iterator[N()]; t_now = new int(0); int n=N(); for(int i = 0;i<n;i++){ if((*train)[i].size()>0){ spikeIt[i] = (*train)[i].begin(); } } } Where the first time of each event is pointed to by the iterator corresponding to the individual neuron [N() is simply the number of neurons, i.e. vectors, that I am counting over], that is, the first entry in its vector of spikes. I then attempt to traverse my sparse sudo-matrix by looking at each time, counting over the number of neurons that spike at that time and, if a neuron does spike, moving the corresponding iterator in my array to the next entry in its vector: bool* SpikeTrain::spikingNow(){ bool * spikingNeurons = new bool[N()]; int n = N(); for (int i = 0;i<n;i++){ if(*(spikeIt[i]) ==(*t_now)){ spikingNeurons[i] =true; spikeIt[i]++; } } (*t_now)++; return spikingNeurons; } My problem, then, comes in attempting to access each iterator in the array to compare to the current time. I get a >EXC_BAD_ACCESS(code = 1,address = 0x0) at: if(*(spikeIt[i]) ==(*t_now))
|c++|iterator|sparse-matrix|
> The [`ValueFromPipelineByPropertyName`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.4#valuefrompipelinebypropertyname-argument) argument indicates that the parameter accepts input from a property of a pipeline object. The object property must have the same name or alias as the parameter. The binding happens by pipeline already, you don't need to manually pass the argument, moreover, [`$_` (PSItem)](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_psitem?view=powershell-7.4) is only automatically populated in the context of scriptblock and your second statement has no scriptblock. ```sh $obj = [pscustomobject]@{ id = 4444 } # works, the value of `id` is taken from pipeline $obj | Get-Process ``` As to why the `ForEach-Object` example works, simply because you're passing the value of `id` property as argument to the `-Id` parameter, it is pretty much the same as: ```sh Get-Process -Id $obj.Id ```
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` Before, I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move the authorized.js script to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
I faced to same problem in my project. I found a solution. You can use displayName with your function export const nameOfFunction = (props) => ( ... ) nameOfFunction.displayName = 'nameOfFunction' And than you can call like that: console.log(nameOfFunction.displayName) Result: >>> nameOfFunction
You can assign and cast, but you can't use this pointer without invoking undefined behaviour (UB). To pun the types I would rather recommend memcpy or unions
This is due to `executable_path` is an argument of `webdriver.chrome.service.Service`, see [ducumentation][1] Just use driver = webdriver.Chrome() service = webdriver.chrome.service.Service(executable_path='a/b/c') [1]: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.chrome.webdriver
I'm trying to build and push a docker image from a dockerfile in my private repo in dockerhub using buildctl-daemonless.sh command using argo workflow, the following is the step in the workflow that does the job. The problem is that I get that it runs successfully but I couldn't find the image pushed ``` - name: image inputs: parameters: - name: path - name: image volumes: - name: test-secret-secret secret: secretName: test-secret-secret container: readinessProbe: exec: command: [ sh, -c, "buildctl debug workers" ] image: moby/buildkit:v0.9.3-rootless volumeMounts: - name: work mountPath: /work - name: test-secret-secret mountPath: /.docker workingDir: /work/{{inputs.parameters.path}} env: - name: BUILDKITD_FLAGS value: --oci-worker-no-process-sandbox - name: DOCKER_CONFIG value: /.docker command: [ sh, -c, "buildctl-daemonless.sh" ] args: - build - --frontend=dockerfile.v0 - --local context=. - --local dockerfile=. - --output type=image,name=docker.io/myusername/repo-test:argoworkflow,push=true ``` The only thing I get from the logs is this ``` time="2024-03-31T11:30:27 UTC" level=info msg="capturing logs" argo=true NAME: buildctl - build utility USAGE: buildctl [global options] command [command options] [arguments...] VERSION: v0.9.3 COMMANDS: du disk usage prune clean up build cache build, b build debug debug utilities help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --debug enable debug output in logs --addr value buildkitd address (default: "unix:///run/user/1000/buildkit/buildkitd.sock") --tlsservername value buildkitd server name for certificate validation --tlscacert value CA certificate for validation --tlscert value client certificate --tlskey value client key --tlsdir value directory containing CA certificate, client certificate, and client key --timeout value timeout backend connection after value seconds (default: 5) --help, -h show help --version, -v print the version ``` Any thoughts please what could be the problem
I have written below GitHub. actions in order to use the GitHub tags within go code but its failing with below error. Could you please explain what's wrong with the code and how we can debug that? Error : Run actions/github-script@v6 SyntaxError: Unexpected identifier at new AsyncFunction (<anonymous>) at callAsyncFunction (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:15143:16) at main (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:15236:26) at /home/runner/work/_actions/actions/github-script/v6/dist/index.js:15217:1 at /home/runner/work/_actions/actions/github-script/v6/dist/index.js:15268:3 at Object.<anonymous> (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:15271:12) at Module._compile (node:internal/modules/cjs/loader:1198:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1252:10) at Module.load (node:internal/modules/cjs/loader:1076:32) at Function.Module._load (node:internal/modules/cjs/loader:911:12) Error: Unhandled error: SyntaxError: Unexpected identifier ##[debug]Node Action run completed with exit code 1 ##[debug]Finishing: Run actions/github-script@v6 Code : name: Update Values on Tag on: push: tags: - 'v*' # Trigger only in case of new tag jobs: update_values: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/github-script@v6 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | git config --global user.email "jdbdsj@gmail.com" git config --global user.name "Github actions" echo "Release Tag: ${{ github.ref_name }}" release_tag="${{ github.ref_name }}" # Update the value in the specified file (replace with your details) sed -i "s/const version = .*/const version = \"$release_tag\"/" ./hackkerRankSolutions/version.go git add version.go git commit -m "Update version to $release_tag in actions.yaml" git push origin main
Not sure what `Serilog` NuGet packages you have installed in your project but for `Serilog` to write into file you need `Serilog.Sinks.File` - `LoggerConfiguration` extension `File()` is part of that Nuget package. [Docs][1] [1]: https://github.com/serilog/serilog-sinks-file
|powershell|parameters|parameter-passing|
## **Solution:** Change: `var dataRange = s.getRange(2,1,s.getLastRow(),s.getLastColumn()).getValues();` To: `var dataRange = s.getRange(2,1,s.getLastRow()-1,s.getLastColumn()).getValues();` **Explanation:** Logging `s.getRange(2,1,s.getLastRow(),s.getLastColumn()).getValues()` outputs a data set with a blank array element at the end. This is because `s.getLastRow()` gives you the last row size starting from the first row of your sheet. **Sample:** [![image](https://i.stack.imgur.com/07YZJ.png)](https://i.stack.imgur.com/07YZJ.png) Using the script `var range = sheet.getRange(2,1, sheet.getLastRow(), sheet.getLastColumn()).getValues(); ` in this context logs the following: ``` [ [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ 'Test 1 ', 'Test 2', 'Test 3' ], [ '', '', '' ] ] ``` Since excluding the headers on your range while defining the number of rows including the header itself, it will output a blank array element at the end. Now the reason why it outputs an error `"Exception: Unexpected error while getting the method or property getFileById on object DriveApp. renameFiles @ RenameFiles.gs:11"` is because at the last index of your loop, `var id = dataRange[a][0];` has no value, thus the method `DriveApp.getFileById(id)` throws the exception error. **Reference:** [https://developers.google.com/apps-script/reference/spreadsheet/sheet\#getrangerow,-column,-numrows,-numcolumns](https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column,-numrows,-numcolumns)
As I understand the issue and from what I can see in your code, the issue is that you have radio buttons for each question and they all have the same value in the name attribute of the input element (`name="Options"`). Therefor you can only select one option for all questions in the same form. Radio buttons are grouped by their name and only one radio button can be selected in each group. Give the radion buttons for each question a unique name, like `name="question_1"` etc. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> fieldset { display: flex; flex-direction: column; } <!-- language: lang-html --> <form name="form01"> <fieldset> <legend>Question 1?</legend> <label><input type="radio" value="1" name="question_1">Option 1</label> <label><input type="radio" value="2" name="question_1">Option 2</label> <label><input type="radio" value="3" name="question_1">Option 3</label> </fieldset> <fieldset> <legend>Question 2?</legend> <label><input type="radio" value="1" name="question_2">Option 1</label> <label><input type="radio" value="2" name="question_2">Option 2</label> <label><input type="radio" value="3" name="question_2">Option 3</label> </fieldset> <fieldset> <legend>Question 3?</legend> <label><input type="radio" value="1" name="question_3">Option 1</label> <label><input type="radio" value="2" name="question_3">Option 2</label> <label><input type="radio" value="3" name="question_3">Option 3</label> </fieldset> </form> <!-- end snippet -->
I’ll just mimic the string in a *pre* tag and do the string parsing... <!DOCTYPE html><head></head> <body onload="Process();"> <script> function Process(){ let S=Cont.innerHTML; S=S.replace(/\n+/g,'').replace(/ +/g,'').replace(/{/g,' {\n ').replace(/;/g,';\n').replace(/:/g,': ').replace(/,/g,', '); Cont.innerHTML=S; } </script> <pre id="Cont"> p { color: hsl(0deg, 100%, 50%; } </pre> </body></html> You start by stripping all spaces and all LFs and then insert them back this time strategically, as desired. What I’ve done here is compatible with CSS but if your *CodeBlocks* may also contain JS or HTML then you’ll need a separate function to handle each. I hope you don’t get any mixed *CodeBlocks* because it then gets very tricky!
I have tried multple solutons in the platform but none seems to work. I can seem to wrap my around the error AttributeError: 'Wildcards' object has no attribute 'sample' Here is what I am trying to do: ``` import pandas as pd sample_csv = os.path.join(BASE_DIR, "samples.csv") sample_table = pd.read_csv(sample_csv).set_index('sample', drop=False) def get_fq1(wildcards): return sample_table.loc[wildcards.sample, 'fastq1'] def get_fq2(wildcards): return sample_table.loc[wildcards.sample, 'fastq2'] def get_fq_files_dict(wildcards): return { "r1" : sample_table.loc[wildcards.sample, 'fastq1'], "r2" : sample_table.loc[wildcards.sample, 'fastq2'], } rule fastp: input: unpack(get_fq_files_dict) output: expand(base_dir + "/trimmed/{sample}_trimmed.{r}.fastq.gz", sample=SAMPLES_f, # This is refined elsewhere, r=['_1','_2']) shell: """ echo {input} # This is just a decoy command """ ``` This code throws me the error `AttributeError: 'Wildcards' object has no attribute 'sample'` Does anybody have an idea what is not right?
Problems with wilcard
|snakemake|
null