All Invalid Random Paths in the URL Return The Normal Web Page Instead of 404 Not Found Page Posted: 22 Jun 2022 10:34 AM PDT I have a website: https://www.includekarabuk.com For instance this url contains an article: https://www.includekarabuk.com/kategoriler/genel/Siber-Guvenlikte-Dusuk-Seviye-Aciklik-Nedir.php But when I add invalid path to the existing url, page is still being showed. https://www.includekarabuk.com/kategoriler/genel/Siber-Guvenlikte-Dusuk-Seviye-Aciklik-Nedir.php/test123343242314321423423423/ https://www.includekarabuk.com/kategoriler/genel/Siber-Guvenlikte-Dusuk-Seviye-Aciklik-Nedir.php/sdfdsfdsfsdfdsfsdfsdfsdfsdsdfdsfsdfd/ https://www.includekarabuk.com/kategoriler/genel/Siber-Guvenlikte-Dusuk-Seviye-Aciklik-Nedir.php/132432432/ But because css and javascript file locations will be invalid due to added extra path, page is displayed as broken. I want to stop this. When the web server receives invalid path as with above, it should respond as 404 not found page coming from web server. How can I do that? I am using Apache web server and php scripting language. Note: I am not using any MVC framework. |
How do I Convert WSF Script to work in MS Edge Posted: 22 Jun 2022 10:34 AM PDT I am looking to modify the below script to work in Chrome or MS Edge. Can anyone help? I have tried modifying several times and I just can not get it to work. I would really appreciate any guidance. I am looking to modify the below script to work in Chrome or MS Edge. Can anyone help? I have tried modifing several times and I just can not get it to work. </runtime> <script language="vbscript"> 'Set objArgs = WScript.Arguments.Named sCallIdKey = WScript.Arguments.Named.item("EIC_CallidKey") sDNIS = WScript.Arguments.Named.item("AC_NumericDNIS") sANI = WScript.Arguments.Named.item("AC_NumericANI") sWorkgroupSkills = WScript.Arguments.Named.item("Eic_AttDynamicWorkgroupSkills") sCallTime = WScript.Arguments.Named.item("Eic_InitiationTime") sCountry = WScript.Arguments.Named.item("AC_OriginatingCountry") set WshShell=WScript.CreateObject("WScript.Shell") WshShell.run "chrome.exe" WScript.sleep 100 set objShell = CreateObject("Shell.Application") objShell.ShellExecute"about:blank" szHTMLBody = _ "<div align='center'><b><font size='5'>" & _ "<br><br>" & _ "I3 Interaction Id: <font color='blue'>" & sCallIdKey & _ "<br><br>" & _ "<font color='black'>Product: " & sWorkgroupSkills & _ "<br>" & _ "DNIS: " & sDNIS & " " & sCountry & _ "<br><br><br>" & _ "Caller's Telephone Number: " & sANI & _ "<br>" & _ "Time of Call: " & sCallTime & _ "</font></b></div>" objShell.document.Body.InnerHTML = szHTMLBody objExplorer.Visible = 1 Do While (objExplorer.Busy) WScript.Sleep 1000 Loop Set objShell = CreateObject("WScript.Shell") objShell.AppActivate objExplorer.document.Title objExplorer.Visible = True 'objExplorer.Quit Set objExplorer = Nothing Set objShell = Nothing </script> |
Funny network packets with upcounting hardware address Posted: 22 Jun 2022 10:34 AM PDT I have written a little program to investigate my home network, to see what packets are underway. I print the hardware address, and the number of packets. Looks quite normal, i know all these addresses. But when i start Firefox, some new source addresses pop up. What are these? Normally i would say, there is a bug in my code, but they appear, when i start firefox, especially if i open a new tab?! I have a Kubuntu 22.04 with Firefox 101.0.1 device: 00:00:40:11:4f:a5 --> 1 packets device: 00:00:40:11:54:fa --> 1 packets device: 00:00:40:11:66:c5 --> 1 packets device: 00:00:40:11:69:30 --> 1 packets device: 00:00:40:11:69:4e --> 1 packets device: 00:00:40:11:6e:e1 --> 1 packets device: 00:00:40:11:79:3a --> 1 packets device: 00:00:40:11:7d:32 --> 1 packets device: 00:00:40:11:83:05 --> 1 packets device: 00:00:40:11:9a:ca --> 1 packets device: 00:00:40:11:9c:2d --> 1 packets device: 00:00:40:11:9c:30 --> 1 packets My code is (gcc code.cpp -o code, run it with sudo): #include <stdio.h> #include <string.h> #include <inttypes.h> #include <arpa/inet.h> #include <errno.h> #include <ctype.h> #include <unistd.h> #include <stdlib.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <sys/ioctl.h> #include <netpacket/packet.h> #include <linux/if_ether.h> #include <linux/udp.h> #include <netinet/if_ether.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <ctime> #include <map> #define BUFSIZE 2048*8 struct hwaddr{ uint8_t c[6]; bool operator<(const struct hwaddr &other) const{ for(int i = 0; i<6; i++){ if(c[i] != other.c[i]){ return c[i] < other.c[i]; } } return false; } }; void printeth(struct ether_header * e){ uint8_t * hwa; hwa = e->ether_dhost; printf("dest: %02x:%02x:%02x:%02x:%02x:%02x ", hwa[0], hwa[1], hwa[2], hwa[3], hwa[4], hwa[5]); hwa = e->ether_shost; printf("sour: %02x:%02x:%02x:%02x:%02x:%02x ", hwa[0], hwa[1], hwa[2], hwa[3], hwa[4], hwa[5]); printf("type: %04x\n", (int)ntohs(e->ether_type)); } void printcounter(std::map<struct hwaddr, uint64_t> const & counter){ static uint64_t last = std::time(0); uint64_t const now = std::time(0); if(now == last){ return; } last = now; printf("\033[2J\033[1;1H"); printf("size: %d\n", (int)counter.size()); for(const auto & a : counter){ uint8_t * hwa = (uint8_t*)&a.first; printf("device: %02x:%02x:%02x:%02x:%02x:%02x --> %8lu packets\n", hwa[0], hwa[1], hwa[2], hwa[3], hwa[4], hwa[5], a.second); } } int main(int argc, char ** argv){ char buf[sizeof(struct ether_header)]; std::map<struct hwaddr,uint64_t> counter; int const sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (sockfd < 0){ printf("ERROR opening socket: %s\n", strerror(errno)); return 0; } while (1) { int const n = recv(sockfd, buf, sizeof(struct ether_header), 0); if(n >= sizeof(struct ether_header)){ struct ether_header * e = (struct ether_header*)buf; //printeth(e); counter[*(struct hwaddr*)&e->ether_shost]++; printcounter(counter); } } return 0; } |
The if-else statement is invalid in the Java language Posted: 22 Jun 2022 10:34 AM PDT |
ASP.NET core authentication and authorization with OIDC without creating local copies of the user Posted: 22 Jun 2022 10:34 AM PDT I've just created a new ASP.net core application using visual studio, it has the Authentication Type set to Individual Accounts : I've added some code to handle OIDC: builder.Services.AddAuthentication().AddOpenIdConnect(openIdOptions => { openIdOptions.ClientId = "myClientId"; openIdOptions.Authority = "myAuthority"; openIdOptions.ResponseType = OpenIdConnectResponseType.Code; openIdOptions.GetClaimsFromUserInfoEndpoint = false; openIdOptions.CallbackPath = "/signin-oidc"; openIdOptions.SaveTokens = true; Which is all well and good, I can click to login with OpenIdConnect: When I log in with the provided credentials it pops up asking me to Associate my OpenIdConnect account: I don't want to have to do this. Retrieving the access token and id token is sufficient for what I want to do, I don't require a local copy of the user. Being new to ASP.net and having not used Razor before it's not immediately obvious what code I should delete — if that's even the correct approach. I've played around with deleting various bits such as the Db setup as I don't really require it, although I suspect Razor does in some regard. The Program.cs looks as follows: var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDefaultIdentity<IdentityUser>(options => { }) .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddRazorPages(); builder.Services.AddAuthentication().AddGoogle(googleOptions => { googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"]; googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; }); builder.Services.AddAuthentication().AddOpenIdConnect(openIdOptions => { openIdOptions.ClientId = "clientId"; openIdOptions.Authority = "authority"; openIdOptions.ResponseType = OpenIdConnectResponseType.Code; openIdOptions.GetClaimsFromUserInfoEndpoint = false; openIdOptions.CallbackPath = "/signin-oidc"; openIdOptions.SaveTokens = true; }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}"); }); app.Run(); |
How to view container logs in GKE's Logs Explorer Posted: 22 Jun 2022 10:33 AM PDT In my GKE cluster (version v1.21.10-gke.2000) I would like to see output produced by pods/containers as logs in Logs Explorer. But clicking on Container Logs link in Workloads' Overview tab makes Logs Explorer return 'No data found'. Cloud Logging is enabled (Components: System, Workloads). Cloud Logging API is enabled as well. What I have tried so far: In another (test) project in a freshly created cluster (version 1.22.8-gke.201) this works correctly, i.e. what kubectl logs returns is also visible in Logs Explorer. The cluster mentioned at the beginning was created long ago and apparently requires some changes - how can I figure out what cluster (or maybe node pool) settings need to be modified to be able to see container logs in Logs Explorer? I would like to avoid creating a new cluster from scratch. |
How do I type a Response object from a fetch request? Posted: 22 Jun 2022 10:34 AM PDT I'm running parallel requests for a series of fetches. I want to type results as an array of response objects (instead of array of type any ) but I'm unsure of how to do this. I googled "how to type response object in Typescript" but didn't get useful hits. Is there a way to type the response object other than manually creating a custom type that has all the properties on a response object? Does Typescript have a special built in type we could use here? const results: any = []; fetch(URL, { headers: { ... } }) .then(response => { results.push(response); }) .catch(err => { ... }) const responses = await Promise.all(results); return responses; |
PHP Header Location with PHP variable to Whatsapp Message Posted: 22 Jun 2022 10:33 AM PDT I need to send a PHP variable like a whatsapp message. My code are attach: $fim = file_get_contents('pedidos/'.$pedidoaux); header("Location: http://api.whatsapp.com/send?1=pt_BR&phone=WHATSAPPNUMBER&text={$fim}"); How to I inser the $fim variable in code for send the value? Thank you. |
How to get conda environment .yaml file from poetry .toml? Posted: 22 Jun 2022 10:33 AM PDT I would like to use binder which requires a conda yaml environment. I personally prefer poetry. How can I convert a .toml file to a .yaml? This is the best I have found: https://pypi.org/project/poetry2conda/ |
Find minimum steps to convert all elements to zero Posted: 22 Jun 2022 10:34 AM PDT You are given an array of positive integers of size N. You can choose any positive number x such that x<=max(Array) and subtract it from all elements of the array greater than and equal to x. This operation has a cost A[i]-x for A[i]>=x. The total cost for a particular step is the sum(A[i]-x). A step is only valid if the sum(A[i]-x) is less than or equal to a given number K. For all the valid steps find the minimum number of steps to make all elements of the array zero. 0<=i<10^5 0<=x<=10^5 0<k<10^5 Can anybody help me with any approach? DP will not work due to high constraints. |
How can I change textblock.Text from another class? Posted: 22 Jun 2022 10:34 AM PDT I have UserControl elem with a textblock and i want to change text in it from MainWindow UserControl Class: public void textBlockFilling(long id) { var selectedProducts = from p in db.Products where p.ProductID == id select p; IEnumerable<TypesOfProduct> type = GetType(id); textBlockName.Text = textBlockName.Text.Split(':')[0]; textBlockName.Text += ": " + selectedProducts.First().ProductName; } MainWindow: void SearchString_OnSelect(object sender, SelectionChanged e) { if (e.Value != null) { Product product = e.Value as Product; ProductsView pa = new ProductsView(); pa.textBlockFilling(product.ProductID); } } But text didnt change -_-; Then i found another way: UC class: private delegate void NameCallBack(long varText); public void UpdateTextBox(long input) { db = new ApplicationContext(); if (!Dispatcher.CheckAccess()) { textBlockName.Dispatcher.BeginInvoke(new NameCallBack(UpdateTextBox), new object[] { input }); } else { if (db.Products == null) return; var selectedProducts = from p in db.Products where p.ProductID == input select p; textBlockName.Text = textBlockName.Text.Split(':')[0]; textBlockName.Text = ": " + selectedProducts.First().ProductName; } } And MainWindow : public static readonly ProductsView ProductsLogWindow = new ProductsView(); void SearchString_OnSelect(object sender, SelectionChanged e) { if (e.Value != null) { Product product = e.Value as Product; ProductsLogWindow.textBlockFilling(product.ProductID); } } But it still didnt work. Can you explain me what i'm doing wrong? |
what does mean in syntax (.id) of [answer = answerEl.id;] in javascript? [closed] Posted: 22 Jun 2022 10:34 AM PDT function getSelected() { let answer = undefined; answerEls.forEach((answerEl) => { if (answerEl.checked) { answer = answerEl.id; } }); return answer; } |
I have tried to install this package "pip install sslcommerz-python" but many errors came up. How could I solve this problem Posted: 22 Jun 2022 10:33 AM PDT error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. WARNING: No metadata found in c:\users\hadayetullah\appdata\local\programs\python\python310\lib\site-packages Rolling back uninstall of typed-ast Moving to c:\users\hadayetullah\appdata\local\programs\python\python310\lib\site-packages\typed_ast-1.5.4.dist-info from C:\Users\Hadayetullah\AppData\Local\Programs\Python\Python310\Lib\site-packages~yped_ast-1.5.4.dist-info Moving to c:\users\hadayetullah\appdata\local\programs\python\python310\lib\site-packages\typed_ast from C:\Users\Hadayetullah\AppData\Local\Programs\Python\Python310\Lib\site-packages~yped_ast error: legacy-install-failure × Encountered error while trying to install package. ╰─> typed-ast |
Best AWS Hardware for SIMD-JSON [closed] Posted: 22 Jun 2022 10:34 AM PDT I'm writing an application that involves parsing a good deal of JSON. I'm using the SIMD-JSON library. However, I understand that its performance depends a large degree on the hardware used. What should I look for when choosing hardware for SIMD-JSON-parsing-intensive work? EDIT: due to objections of asking for the "best choice" of hardware, I've amended the question. EDIT: not sure why this is closed, at a minimum the library requires x86. AWS-specific is important because it can be unclear what the hardware is that amazon offers, even when they claim the virtual hardware meets certain requirements. |
Cross-Origin problems when trying to send a POST request Posted: 22 Jun 2022 10:34 AM PDT I'm working on the frontend of a website with vanilla JS and I'm trying to use the Hapio API which basically allows you to book appointments. In order to create a new service (It's a barbershop website) I'm using the fetch web API to send a POST request. The API requires me to perform authentication using a bearer token, also I need to provide some parameters in the body of the request. I have the following code: //Params needed to create a new service const service = { name: 'Haircut 1', type: 'fixed', duration: 'PT45M', } fetch('https://eu-central-1.hapio.net/v1/services', { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, }, body: JSON.stringify(service), }). then(resp => resp.json()). then(data => console.log(data)) I'm just testing the endpoint on the Firefox console and I get the next error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://eu-central-1.hapio.net/v1/services. (Reason: CORS header 'Access-Control-Allow-Origin' missing). Status code: 200. I tried to run the same code on different browsers and I get different errors. This one for example is on Safari: [Error] Origin null is not allowed by Access-Control-Allow-Origin. Status code: 200 I googled a bit and most people say that I have to enable CORS on the server I'm trying to send the request to, but the thing is that I don't have control of it. I noticed that the Origin header is set to null . Any idea of how can I fix the problem? |
Why iterator type of priority_queue is wrong with range constructor? Posted: 22 Jun 2022 10:34 AM PDT The code is as following. #include <iostream> #include <queue> #include <unordered_map> using namespace std; typedef unordered_map<int,int>::iterator myIt; class cmpHelper { public: bool operator()(myIt l, myIt r){return l->second > r->second;} }; int main(int argc, char* argv[]){ unordered_map<int,int> freq_cnt({{3,1},{2,4},{5,2}}); priority_queue<myIt,vector<myIt>, cmpHelper> h(freq_cnt.begin(), freq_cnt.end()); //priority_queue<myIt, vector<myIt>, cmpHelper> h; } and hereunder shows corresponding compiler info g++ --version g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Default constructor is OK. And I tried to go through code under directory /usr/include/c++/7/bits/, but still no any idea. Please help point out what the problem is. Thanks. |
sveltekit static adapter does not work on cloudflare pages Posted: 22 Jun 2022 10:33 AM PDT I have a sveltekit website that I deployed to cloudflare pages, the problem is that when I deploy the app with the static adapter and try to visit the site it says "No webpage was found for the web address" but when I use the cloudflare adapter it works successfully, so I was intending to use the cloudflare adapter but I noticed that the number of "Functions requests today" was increasing although my app does not have any functions (some how every request is counted as a server function), So what am I doing wrong here? |
Android 12 reading file on Internal storage leads to "open failed: EACCES (Permission denied)" Posted: 22 Jun 2022 10:34 AM PDT after hours of headache and researching (even the second site of google :) ), I decided to ask here for a solution to my problem. What I'm trying to do is reading a Keepass File from my Internal Storage. The file is located under "/storage/emulated/0/Keepass". The file has to remain there, because it automatically syncs with a SynologyNAS. When im trying to open the file with the absolute path, I get the exception W/System.err: java.lang.IllegalArgumentException: The KeePass database file could not be found. You must provide a valid KeePass database file. W/System.err: at de.slackspace.openkeepass.KeePassDatabase.getInstance(KeePassDatabase.java:116) W/System.err: at de.philslr.passtick.MainActivity.readDb$lambda-5(MainActivity.kt:135) W/System.err: at de.philslr.passtick.MainActivity.$r8$lambda$1TiGYGtdMnuJx-_iduNC5-Ge9ag(Unknown Source:0) W/System.err: at de.philslr.passtick.MainActivity$$ExternalSyntheticLambda0.run(Unknown Source:2) W/System.err: at android.os.Handler.handleCallback(Handler.java:938) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99) W/System.err: at android.os.Looper.loopOnce(Looper.java:201) W/System.err: at android.os.Looper.loop(Looper.java:288) W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7870) W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) W/System.err: Caused by: java.io.FileNotFoundException: /storage/emulated/0/Keepass/passwords_ps.kdbx: open failed: EACCES (Permission denied) W/System.err: at libcore.io.IoBridge.open(IoBridge.java:575) W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160) W/System.err: at de.slackspace.openkeepass.KeePassDatabase.getInstance(KeePassDatabase.java:113) W/System.err: ... 11 more W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied) W/System.err: at libcore.io.Linux.open(Native Method) W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:567) W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:273) W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:567) W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7756) W/System.err: at libcore.io.IoBridge.open(IoBridge.java:561) W/System.err: ... 13 more And the code to read the file is: try { val file = File(path) val database = KeePassDatabase.getInstance(file).openDatabase("password") val entries = database.entries for (entry in entries) { Log.d("[KDBX Read]", "Entry: ${entry.title}") } } catch (e: Exception) { Toast.makeText(applicationContext, "Couldn't open database, there was an error", Toast.LENGTH_SHORT).show() e.printStackTrace() } I know there were some changes, to the file management with Android 12, but I guess there has to be a way to read the file anyway. Thanks in advance |
beautiful soup - getting a text from a tag inside another tag Posted: 22 Jun 2022 10:33 AM PDT i am trying to parse a web page using beautiful soup [for the first time in my life] and i am experiencing a strange error. there is a tag within a tag in html structure, and i keep getting the error AttributeError: 'NoneType' object has no attribute 'text' the structure of html tag is following: the whole grid of items on the page is within div class "properties_reviews" which then goes into div class "preview" for a particular item and that class "preview" has two more classes: "preview-media" for photo and "preview-content" for text info i need to parse. the class "preview-content" has [a] tag that contains two [span] tags with price and square of the item, and a [h2] tag with a territory i also need. <div class="properties-previews"> <div class="preview" <div class="preview-media"> <div class="preview-content"> <a href="/properties/1042-us-highway-1-hancock-me-04634/1330428" class="preview__link"> <span class="preview__price">$89,900</span> <span class="preview__size">1 ac</span> <div class="preview__subtitle"> <h2 class="-g-truncated preview__subterritory">Hancock County </h2> <span class="preview__extended">-- sq ft</span> </div> </a> so i am trying to get out $89,990 from preview_price ; 1 ac from preview_size ; hancock county from preview_subtitle and my python code so far has been something like this (i have omitted all imports and requests): landplots = soup.find_all('div', class_ = 'properties-previews') for l in landplots: plot_price = l.find('span', {"class": 'preview_price'}) plot_square = l.find('span', {"class": 'preview_size'}) plot_county = l.find('h2', class_ = '-g-truncated preview__subterritory').text plot_location = l.find('span', class_ = 'preview__locality -g-truncated').text print(plot_price).text print(plot_county) what am i doing wrong? i've come to understanding that once a tag is within another tag there should be some special syntax to get those words, but the error saying i have no text at all (on both prints i am doing) confuses me a lot. please help! |
Overflow when working with exponentials (Fortran) Posted: 22 Jun 2022 10:34 AM PDT I'm having problems regarding the calculation of some exponentials. The problem is, i have a sum of exponentials that each one gives me overflow, so i didn't found a way to use logarithm to free myself of such big numbers. For the code below, the program runs OK without overflow but I need to use bigger values of Eigenvalues, lets say, at least 300 times bigger. I couldn't find a way to work around the sum of exponentias using logarithm. As you can see, the problem is not in the final result, but in the intermediate calculations. Please let me know if this information is incomplete program testing implicit none integer, parameter :: q = SELECTED_REAL_KIND(10) integer, parameter :: qc = SELECTED_REAL_KIND(10) integer :: Ndim real (q) :: Temperature real (q),allocatable :: Eigenvalues (:),rho (:) real (q) :: Z integer :: i allocate (rho (Ndim),Eigenvalues(Ndim)) !Parameter Definition Ndim=4 Temperature=0.00000158 Eigenvalues(1)=-0.000893 Eigenvalues(2)=-0.000893 Eigenvalues(3)=-0.000788 Eigenvalues(4)=-0.000446 Z = 0.; rho = 0. do i =1, Ndim Z = Z + exp ( - Eigenvalues (i)/(Temperature)) write(*,*) Z enddo do i = 1, Ndim rho (i) = rho (i) + exp ( - Eigenvalues (i)/(Temperature) )/Z write(*,*) rho(i) enddo end |
How to read file and store it into wchar_t in C? Posted: 22 Jun 2022 10:33 AM PDT I am trying to get info from a .txt file called a.txt with the ReadFile() function, which is provided by <windows.h> , and store it in a wchar_t[] variable. Here is my code: #include <stdio.h> #include <windows.h> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); _setmode(_fileno(stdin), _O_U16TEXT); _setmode(_fileno(stderr), _O_U16TEXT); HANDLE fh = CreateFileW( L"a.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); LARGE_INTEGER size; GetFileSizeEx(fh, &size); DWORD sizeF = size.QuadPart; wchar_t* readBuffer = (wchar_t*)malloc(sizeF * sizeof(wchar_t)); DWORD bytesRead; if (ReadFile(fh, readBuffer, sizeF, &bytesRead, NULL)) { readBuffer[sizeF] = L'\0'; } wprintf(L"%s\n", readBuffer); CloseHandle(fh); } But the output I get is not what I expected. It is question marks in squares: What is wrong with my code? |
How to match and replace pattern without regex? Posted: 22 Jun 2022 10:34 AM PDT I was recently asked this in an interview and was figuring out a way to do this without using regex in Ruby as I was told it would be a bonus if you can solve it without using regex. Question: Assume that the hash has 1 million key, value pairs and we have to be able to sub the variables in the string that are between % % this pattern. How would I be able to do this without regex. We have a string str = "%greet%! Hi there, %var_1% that can be any other %var_2% injected to the %var_3%. Nice!, goodbye)" we have a hash called dict = { greet: 'Hi there', var_1: 'FIRST VARIABLE', var_2: 'values', var_3: 'string', } This was my solution: def template(str, dict) vars = value.scan(/%(.*?)%/).flatten vars.each do |var| value = value.gsub("%#{var}%", dict[var.to_sym]) end value end |
How do I assign a Boolean when value is missing using CROSSTAB? Posted: 22 Jun 2022 10:33 AM PDT I need help from the beehive. I am currently learning to use CROSSTAB in Postgres and have run into a blocker. Here's what I am getting: contactid | opt_in | purchase | deleted | 1 | 1 | 1 | 0 | 2 | 0 | 1 | 1 | 3 | 1 | 0 | 0 | Here's what I should get: contactid | opt_in | purchase | deleted | 1 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 | 1 | Now, as I understand, CROSSTAB takes the first value it finds and uses it for the first feature that is called, which is why contacted 3 has a 1 in opt-in instead of deleted, and why contacted 2 has a 0 in opt-in when it should be a 1. I just don't know how to fix this without upserting rows to the original table. Would really appreciate your guidance. Here's my script: CREATE EXTENSION IF NOT EXISTS tablefunc; with happening as (SELECT * FROM CROSSTAB($$ with happening as ( select distinct activity, a.contactid, case when activitydate<=creationdate+interval '2 weeks' then 1 else 0 end happening from contactactivities a left join contacts c on a.contactid=c.contactid group by activity, a.contactid, happening order by a.contactid) select contactid, activity, happening from happening order by contactid, activity; $$) AS happening (contactid int, opt_in int, purchase int, deleted int)) select contactid, coalesce(opt_in,'0'::int) opt_in, coalesce(purchase,'0'::int) purchase, coalesce(deleted,'0'::int) deleted from happening; Schema: CREATE TABLE IF NOT EXISTS contacts ( CONTACTID SERIAL, CREATIONDATE DATE ); CREATE TABLE IF NOT EXISTS contactActivities ( CONTACTID INT, ACTIVITY VARCHAR, ACTIVITYDATE DATE ); INSERT INTO contacts(CREATIONDATE) VALUES ('1/22/20'), ('1/25/20'), ('1/26/20'); INSERT INTO contactActivities(CONTACTID, ACTIVITY, ACTIVITYDATE) VALUES (1, 'opt-in', '1/22/20'), (1, 'purchase', '1/23/20'), (2, 'opt-in', '1/25/20'), (3, 'deleted', '1/27/20'), (2, 'purchase', '1/27/20'), (1, 'purchase', '1/28/20'), (2, 'deleted', '2/26/20'); |
How to map a class A that inherits from base class using AutoMapper in c# Posted: 22 Jun 2022 10:33 AM PDT I have a class GetData public class GetData { public FooClass PrevData {get;set;} public FooClass NewData {get;set;} } public class FooClass: Class B{} public class B { public string varC; public string varD; public string varE; } I need to use automapper to map class GetData's PrevDataA's fields to Class C's properties. I will then use class C to store data in database. public class C { public Data data {get;set;} public string var_e; } public class Data { public string var_c; public string var_d; } I have tried these two : CreateMap<GetData,C>() .ConvertUsing(src => src.PrevData.Select (x => new C { var_e = x.varE; varData= new Data() { var_c = varC; var_d = varD; }})); } Here I get an error on 'select' that testClass does not contain definition for 'Select'. Also, I have tried using below: .ForMember(dest => dest.Data.var_c, src => src.MapFrom(src.PrevData.VarC)) This is also giving an error saying : Expression "dest => dest.Data.var_C" must resolve top level member and not any child's properties. You can Forpath, a custom resolver on the childtype or the AfterMap option instead. Can anyone help in using ForPath or this. |
How to add padding to right to the string in python pandas? Posted: 22 Jun 2022 10:34 AM PDT please help to add padding after values. I'm trying to add right padding to the Gr no value in the excel output but not able to add. please suggest. po_nos =[] dates = [] refs = [] totals = [] mat_codes = [] qtys = [] vendor_no = [] inv_amt = [] order_no = [] reference = [] gr_no= [] distance = [] dispatch = [] mode = [] address = [] padding = 5 for pth in paths: doc = pdfplumber.open(pth) page = doc.pages[0] token = page.extract_text().splitlines() vendor = token[5][14:][:35] #add = token[34][39:] #GR No = token[35][48:][:5] data = [i for i in token if 'Invoice No:' in i][0].split(' ') data1 = [i for i in token if 'Ref:' in i][0].split(' ') data2 = [i for i in token if 'Order' in i][0].split(' ') data3 = [i for i in token if 'GR No' in i][0].split(' ') #data3 = '{0:>2}'.format(gr_no) #data3= data3[2].str.pad(5, side ='right') data3 = [i for i in data3 if 'GR No'].str.pad(2, side='right') print(data3) data4 = [i for i in token if 'Distance' in i][0] data5 = [i for i in token if 'Mode of Transportation:' in i][0].split(' ') data6 = [i for i in token if 'Name and Address' in i][0] data7 = [i for i in token if 'PO No:' in i][0].split(' ') data7 = [i for i in data7 if i!=''] ref = data[2] po_no = data7[11] refe = data1[7] order = data2[-9] gr = data3[2] mod = data5[15] dist= data4[49:53] add =data6[39:] date = data[5] idx = [i for i, j in enumerate(token) if j[:5] == 'Total'][0] total = token[idx].split(' ')[2] inv = token[idx].split(' ')[6] token = token[17:idx] token = [i for i in token if I[0] in ['1','2','3','4','5','6','7','8','9','10']] mat_code = [i.split(' ')[1] for I in token] qty = [i.split(' ')[-8] for I in token] po_nos.append([po_no]* Len(token)) mat_codes.append(mat_code) qtys.append(qty) address.append([add]* len(token)) distance.append([dist]* Len(token)) totals.append([total]* Len(token)) refs.append([ref] * Len(token)) dates.append([date] * Len(token)) vendor_no.append([vendor] * Len(token)) inv_amt.append([inv] * Len(token)) reference. Append([refe] * Len(token)) order_no.append([order] * Len(token)) gr_no.append([gr] * Len(token)) mode. Append([mod]* Len(token)) Excepted Output SNOI2203727 0 Km SFLR325225SAM 0 Km But i'm getting below SNOI2203727 Km D SFLR325225SAM 0 Km SFLR324710SAM 0 Km SNOI2204068 Km D |
GraphQL: making use of it to handle complex view/UI logic Posted: 22 Jun 2022 10:34 AM PDT I've got a requirement to move complex switches logic from UI layer to GraphQL layer. This complex switches logic is to perform a computation based on a bunch of backend configurations to determine whether a set of UI components should be shown or hidden. To show or hide a particular UI component in the set, it requires at least 3 levels deep of nested if -else branches logic. I'm currently thinking of adding the following type to the schema to solve this problem: type MyComplexView { componentAShown: Boolean! componentBShown: Boolean! # ... (gazzillion of other components here) componentXShown: Boolean! } ...and then I'd expect the data returned from the query would look something like: { "data": { "myComplexView": { "componentAShown": true, "componentBShown": false, // ... (gazzillion of other components here) "componentXShown": true, } } } But it just doesn't feel right, and it feels like I'm abusing the GraphQL layer for doing this kind of job. So question is, is this also a valid use case for making use of GraphQL? Is there an alternative or better way of doing it? The idea is to share the complex switches logic for all the clients (e.g. web and mobile) that are going to consume the API without re-writing/duplicating the logic again on the client-side. |
Unable to read Landsat 5 metadata using readMeta() of R Posted: 22 Jun 2022 10:34 AM PDT I am following a tutorial on remote sensing using R. The tutorial is available from here. pg 44. I would like to read the metadata for a Landsat 5 image, specifically for 1984-06-22 path/row 170/072 . The Landsat Product ID is LT05_L2SP_170072_19840622_20200918_02_T1 . Here is the L5 metadata. I am using the readMeta function from the RSToolbox package. The work should be pretty straightforward in that I put in the path to my metadata file and specify raw = F so that the metadata can be put in a format for further analyses. mtl <- readMeta(file = ".", raw = F) After doing this (reading the L5 using readMeta ) I get this error. Error in `.rowNamesDF<-`(x, value = value) : invalid 'row.names' length Now of course there are many ways of killing a rat, so I used this method here - whereby read.delim function is used to read the metadata file. This brings in a dataframe with all the metadata values alright. However, when this dataframe is put into the radCor function in order to convert the L5 DNs to Top-of-Atmosphere radiance, the following error appears: Error in radCor(june_landsat2, metaData = metadata_june, method = "rad") : metaData must be a path to the MTL file or an ImageMetaData object (see readMeta) Seems like radCor will accept nothing else apart from what is read by readMeta or the path to the MTL file itself. Not even the result from read.delim will do. Because the first error readMeta mentioned row.names length issue, I thought deleting the last row without a value in the metadata file would solve the issue, but this brings more complicated errors. In short, I would like to find a way to make readMeta read my L5 metadata file, since the result from readMeta is being used in other places of the tutorial. Thanks |
Flutter : Errors appearing after updating the Firebase auth package Posted: 22 Jun 2022 10:33 AM PDT I created the Firebase Auth class a year ago. Now After updating the Dart language and updating the firebase auth package some errors appeared. import 'package:firebase_auth/firebase_auth.dart'; class AuthService { final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map( (FirebaseUser user) => user.uid, ); // Sign up Email & passowrd Future<String> createUserWithEmailAndPassword( String email, String password, String name) async { final currentUser = await _firebaseAuth.createUserWithEmailAndPassword( email: email, password: password, ); //updat username var userUpdateInfo = UserUpdateInfo(); userUpdateInfo.displayName = name; await currentUser.updateProfile(userUpdateInfo); await currentUser.reload(); return currentUser.uid; } // sign in Email & password Future<String> sinInWithEmailAndPassword( String email, String password) async { return (await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password)) .uid; } // sign out signOut() { return _firebaseAuth.signOut(); } } click here to see error |
Azure functions node error when doing npm start Posted: 22 Jun 2022 10:33 AM PDT I am trying to run my azure functions locally by doing npm start or even the simple func start. It was working perfectly until today when the following error started coming: The func.deps.json file is here: C:\Program Files\Microsoft\Azure Functions Core Tools and it has the dependency below. I don't even use this and don't know what it is "Error: An assembly specified in the application dependencies manifest (func.deps.json) was not found: package: 'Marklio.Metadata', version: '1.2.20-beta' path: 'lib/netstandard2.0/Marklio.Metadata.dll' npm " xxx-api@0.0.1 build:docs C:\Code\xxxx-api > tsc --sourcemap --lib es2017 src/_doc/index.ts --outDir doc && node doc/index.js Error: An assembly specified in the application dependencies manifest (func.deps.json) was not found: package: 'Marklio.Metadata', version: '1.2.20-beta' path: 'lib/netstandard2.0/Marklio.Metadata.dll' npm ERR! code ELIFECYCLE npm ERR! errno 2147516556 npm ERR! xxxx-api@0.0.1 install:extensions: `npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir` npm ERR! Exit status 2147516556 npm ERR! npm ERR! Failed at the xxx-api@0.0.1 install:extensions script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\user\AppData\Roaming\npm-cache\_logs\2020-08-13T04_37_33_194Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 2147516556 npm ERR! panthera-api@0.0.1 install:extensions: `npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir` npm ERR! Exit status 2147516556 npm ERR! npm ERR! Failed at the xx-api@0.0.1 install:extensions script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\xx\AppData\Roaming\npm-cache\_logs\2020-08-13T04_37_33_194Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 2147516556 npm ERR! xx-api@0.0.1 prestart: `npm run install:extensions` npm ERR! Exit status 2147516556 npm ERR! npm ERR! Failed at the xxx-api@0.0.1 prestart script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\xx\AppData\Roaming\npm-cache\_logs\2020-08-13T04_37_33_241Z-debug.log My package.json file scripts are as follows: "scripts": { "build": "npm run clean && tsc && npm run build:configFiles && npm run build:docs", "build:production": "npm run prestart && cross-var rimraf $npm_package_config_azureFunctions_outDir/local.*.json && cross-var copyfiles package.json $npm_package_config_azureFunctions_outDir && cd dist && npm install --production", "build:configFiles": "cross-var copyfiles -u 1 \"$npm_package_config_azureFunctions_rootDir/**/*.json\" $npm_package_config_azureFunctions_outDir", "build:docs": "tsc --sourcemap --lib es2017 src/_doc/index.ts --outDir doc && node doc/index.js", "prestart": "npm run install:extensions", "start": "npm-run-all -p start:host watch watch:config", "start:doc": "npm run install:extensions && npm run start:host", "start:host": "cross-var func host start --prefix $npm_package_config_azureFunctions_outDir", "watch": "tsc --w", "watch:config": "cross-var onchange \"$npm_package_config_azureFunctions_rootDir/**/*.json\" -- npm run build:configFiles", "clean": "cross-var rimraf $npm_package_config_azureFunctions_outDir", "install:extensions": "npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir", "install:extensions:force": "npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir --force", "test": "jest", "precommit-msg": "echo 'Pre-commit checks...' && exit 0", "fix": "eslint --ext .ts --fix ", "fix-dry-run": "eslint --ext .ts --fix-dry-run", "lint": "eslint . --ext .ts" }, Finally, the contents of the log file mentioned above: 1 verbose cli [ 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'install:extensions' 1 verbose cli ] 2 info using npm@6.14.5 3 info using node@v12.18.1 4 verbose run-script [ 4 verbose run-script 'preinstall:extensions', 4 verbose run-script 'install:extensions', 4 verbose run-script 'postinstall:extensions' 4 verbose run-script ] 5 info lifecycle xxx-api@0.0.1~preinstall:extensions: xxx-api@0.0.1 6 info lifecycle xxx-api@0.0.1~install:extensions: xxx-api@0.0.1 7 verbose lifecycle xxx-api@0.0.1~install:extensions: unsafe-perm in lifecycle true 8 verbose lifecycle xxx-api@0.0.1~install:extensions: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Code\xxxAPI\xxx-api\node_modules\.bin;C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Code\xxxAPI\xxx-api\node_modules\.bin;C:\Users\xxx Sharma.STATEMERCANTILE\AppData\Roaming\npm;C:\Program Files\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files\Microsoft MPI\Bin\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Seq\;C:\Program Files\Seq\Client\;C:\Program Files\dotnet\;C:\Program Files\nodejs\;C:\Program Files\Microsoft\Azure Functions Core Tools\;C:\Program Files (x86)\GitExtensions\;C:\Program Files (x86)\dotnet\;C:\Users\xxx Sharma.STATEMERCANTILE\AppData\Roaming\npm;C:\Users\xxx Sharma.STATEMERCANTILE\AppData\Local\Microsoft\WindowsApps;C:\Users\xxx Sharma.STATEMERCANTILE\.dotnet\tools;C:\Users\xxx Sharma.STATEMERCANTILE\AppData\Local\Programs\Microsoft VS Code\bin; 9 verbose lifecycle xxx-api@0.0.1~install:extensions: CWD: C:\Code\xxxAPI\xxx-api 10 silly lifecycle xxx-api@0.0.1~install:extensions: Args: [ 10 silly lifecycle '/d /s /c', 10 silly lifecycle 'npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir' 10 silly lifecycle ] 11 silly lifecycle xxx-api@0.0.1~install:extensions: Returned: code: 2147516556 signal: null 12 info lifecycle xxx-api@0.0.1~install:extensions: Failed to exec install:extensions script 13 verbose stack Error: xxx-api@0.0.1 install:extensions: `npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir` 13 verbose stack Exit status 2147516556 13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16) 13 verbose stack at EventEmitter.emit (events.js:315:20) 13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14) 13 verbose stack at ChildProcess.emit (events.js:315:20) 13 verbose stack at maybeClose (internal/child_process.js:1021:16) 13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5) 14 verbose pkgid xxx-api@0.0.1 15 verbose cwd C:\Code\xxxAPI\xxx-api 16 verbose Windows_NT 10.0.18363 17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "install:extensions" 18 verbose node v12.18.1 19 verbose npm v6.14.5 20 error code ELIFECYCLE 21 error errno 2147516556 22 error xxx-api@0.0.1 install:extensions: `npm run build && cross-var func extensions install --prefix $npm_package_config_azureFunctions_outDir` 22 error Exit status 2147516556 23 error Failed at the xxx-api@0.0.1 install:extensions script. 23 error This is probably not a problem with npm. There is likely additional logging output above. 24 verbose exit [ 2147516556, true ] |
Need to handle uncaught exception and send log file Posted: 22 Jun 2022 10:34 AM PDT When my app creates an unhandled exception, rather than simply terminating, I'd like to first give the user an opportunity to send a log file. I realize that doing more work after getting a random exception is risky but, hey, the worst is the app finishes crashing and the log file doesn't get sent. This is turning out to be trickier than I expected :) What works: (1) trapping the uncaught exception, (2) extracting log info and writing to a file. What doesn't work yet: (3) starting an activity to send email. Ultimately, I'll have yet another activity to ask the user's permission. If I get the email activity working, I don't expect much trouble for the other. The crux of the problem is that the unhandled exception is caught in my Application class. Since that isn't an Activity, it's not obvious how to start an activity with Intent.ACTION_SEND. That is, normally to start an activity one calls startActivity and resumes with onActivityResult. These methods are supported by Activity but not by Application. Any suggestions on how to do this? Here are some code snips as a starting guide: public class MyApplication extends Application { defaultUncaughtHandler = Thread.getDefaultUncaughtExceptionHandler(); public void onCreate () { Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException (Thread thread, Throwable e) { handleUncaughtException (thread, e); } }); } private void handleUncaughtException (Thread thread, Throwable e) { String fullFileName = extractLogToFile(); // code not shown // The following shows what I'd like, though it won't work like this. Intent intent = new Intent (Intent.ACTION_SEND); intent.setType ("plain/text"); intent.putExtra (Intent.EXTRA_EMAIL, new String[] {"me@mydomain.example"}); intent.putExtra (Intent.EXTRA_SUBJECT, "log file"); intent.putExtra (Intent.EXTRA_STREAM, Uri.parse ("file://" + fullFileName)); startActivityForResult (intent, ACTIVITY_REQUEST_SEND_LOG); } public void onActivityResult (int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_REQUEST_SEND_LOG) System.exit(1); } } |
No comments:
Post a Comment