Posts

Showing posts from March, 2023

is there a way to exclude some words from being translated when using google cloud API on javascript?

is there a way to exclude some words from being translated when using google cloud API? As an example lets say we are trying to translate to spanish the following sentence: On my "playbook" the dogs where funny. In which everything gets translated with the exception of "Playbook". Extra notes: only javascript can be used here -in the example i tried to add the words "playbook" and ricky to not be translated. -i dont have the choice to add an exeption glossary Hope you guys can help, been trying to find a proper solution to exclude some specific words. // Check if the text contains the words "playbooks" or "ricky" if (text.indexOf("playbooks") === -1 && text.indexOf("ricky") === -1) { var xhr = new XMLHttpRequest(); xhr.open("POST", "https://translation.googleapis.com/language/translate/v2"); xhr.setRequestHeader("Content-Type", "application/x-ww...

how to run Valgrind with python process?

We have docker containers which use python services. We want to check for memory leaks in some of the python processes. We tried attaching valgrind with our python process after setting ENV variable PYTHONMALLOC=malloc in our docker file, but we are not able to get proper stack trace. Command used: /usr/bin/valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all --trace-children=yes --track-origins=yes Any idea what needs to be done to use valgrind with python process inside docker containers?

React app deployment on GitHub Pages displays a blank page

I've developed a react app that is running fine locally. I'm now trying to deploy it using GitHub Pages. Despite following this tutorial , I get a blank page, and several 404 errors in the logs. Here is my index.js : import React from 'react'; import ReactDOM from 'react-dom/client'; import {HashRouter} from "react-router-dom"; import './index.css'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <HashRouter> <App /> </HashRouter> </React.StrictMode> ); And the Route defined in App.js return ( <> <Navbar/> <Routes> <Route path='/' element={<CoinsTable coins={coins}/>}/> <Route path='/coin' element={<CoinDetails/>}> <Route path=':coinId' element={<CoinDetails/>}/> ...

memory leak of virtual memory

I run tensorflow on linux (ubuntu20). TF executes my c++ functions for graph compilation/destruction. The consumption of the process virtual memory grows until out-of-memory (>40GB) and the process is killed. I track malloc / free and mmap / munmap with LD_PRELOAD hook and compare with the process virtual memory consumption from /proc/self/status (VmSize). Each graph compilation increases both malloc-allocated and the process virtual memory by almost the same size. Graph destruction decreases malloc-allocated size but not the process virtual memory. So in spite of malloc-allocated memory staying overall stable, the process virtual memory grows fast. e.g.: before compile: 41MB[mmap]/3320MB[malloc]/12428MB[process] after compile: 46MB[mmap]/7434MB[malloc]/16529MB[process] before destroy: 46MB[mmap]/7436MB[malloc]/16593MB[process] after destroy: 46MB[mmap]/3250MB[malloc]/16593MB[process] graphDestroy does not destroy everything by design so a small leftover is expected. I...

remove stripes / vertical streaks in remote sensing images

Image
I have a remote sensing photo that has bright non continuous vertical streaks or stripes as in the pic below, my question is there a way to remove them using python and opencv or any other ip library? ,

How to fetch user data?

firestore contents I am trying to fetch my user data from firestore I set up a model class that’s an observable object to fetch the document data from Firestore to appear on the user interface but I been receiving this error. How do I fix this code to get user data from Firebase ? Cannot convert value of type 'String' to expected argument type 'URL' class NewUserData: ObservableObject { @Published var datas = [UserModelFile]() func fetchUser() { let db = Firestore.firestore() let ref = db.collection("user") ref.getDocuments { snapshot, error in guard error == nil else { print(error!.localizedDescription) return } if let snapshot = snapshot { for document in snapshot.documents { let data = document.data() let username = data["username...

Change User Email in MongoDB via Web App created with Node, Express, EJS, and Mongoose

I have a simple blogging web application. I have set up the ability for users to log in and I am now working on account management. The first part of the account management will be for users to change their email. I have an account.ejs page that includes a nav.ejs , displays the email of the currently logged in user, and then a form for which the user can update their email. The form is simple, it asks for the new email and then includes a second text box to confirm their changed email, and these text boxes must match to proceed. Here is where I am having trouble - I have a signup.ejs page with a form.addEventListener that handles input into a form, and if all is well, I use a res = await fetch() to send to an authRoutes.js which in turn, is handled by an authController.js I am trying to adjust my account.ejs page such that it contains a form allowing a user to update their email in my MongoDB. I am never able to move from the form inside account.ejs to my accountPost meth...

CS50W - Network - Like Button working but Like count is not updating

I am currently working on Project4 from CS50W. The task is to write a social media like site where users can post, follow and like. I have implemented a like button to every post (which is wokring fine) unfortunately I have to refresh the page for the like to show. I whould rather want the like to update directly after clicking the like button. I am creating the div for the posts via Javascript and calling the like_post function onclick function load_posts() { // get posts from /posts API Route fetch('/all_posts') .then(response => response.json()) .then(posts => { // create a div element for each post posts.forEach(post => { let div = document.createElement('div'); div.className = "card post-card"; div.innerHTML = ` <div class="card-body"> <h5 class="card-title">${post['username']}</h5> <h6 class="card-subtitle mb-2 text-mute...

Remove comments from SQL/PLSQL blocks

I was looking for a way to remove comments from SQL/PLSQL blocks. It should follow the following criteria: Single line comments (--) should be removed. Multi line comments (/**/) should be removed. But most importantly if these comments come inside strings (single or double quotes) they should be ignored. I have tried several regexes but non of then are able to capture what I need. like for example: --(?!.*(['""])[^'""]*\1)[^'\n\r]* -> for single line comments (''.*?''|".*?")|/\*.*?\*/|--.*?(?=$|\Z) -> for all cases The second regex I found from here , this does not for all the cases. Can someone please provide a sample using the regex in c# regex engine. PS : should I be proceeding with a Regex matching approach?

How to adjust SameSite

I am heavily a beginner and I'm very confused as to how to implement changing the SameSite attribute. There does seem plenty of similar posts , I understand I need to change the SameSite to sameSite: 'none', secure: true - I'm just not sure where to place it within my code. I am building a website using html and javascript, testing on a local server using Node.js. I understand there is an example that shows me the adjustment, I'm just confused as to where in my code to make such an adjustment. This is a result of the following error: Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery. Resolve this issue by updating the attributes of the cookie: Specify SameSite=None and Secure if the cookie should be sent in cross-site requests. This enables th...

LocalDateTime add millisecond

I want to increase the millisecond value with LocalDateTime. I used plusNanos because I didn't have plusmillisecond. I wonder if this is the right way. I'm using JDK 1.8. I also want to know if there is a plus millisecond function in later versions. DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); LocalDateTime ldt = LocalDateTime.parse("2022-01-01 00:00:00.123",f); System.out.println(ldt.format(f)); ldt = ldt.plusNanos(1000000); System.out.println(ldt.format(f)); 2022-01-01 00:00:00.123 2022-01-01 00:00:00.124

C++ HashTable Read access violation

I am building a HashTable in C++ which takes a name of a person as the key and stores his/her favorite drink, the hashtable is defined as below: class HashTable { private: static const int m_tableSize = 10; struct item { std::string name; std::string drink; item* next; }; item* Table[m_tableSize]; I am using the constructor to fill every bucket in the hashtable as "empty": HashTable::HashTable() { for (int i = 0; i < m_tableSize; i++) { Table[i] = new item; Table[i]->name = "empty"; Table[i]->drink = "empty"; Table[i]->next = NULL; } } This code as it is works but, here's the question: As far as I know, Table[i] = new item; is supposed to allocate each first item of the bucket in the heap instead of allocating in the stack, but if I try to supress this line, in other words, if I want the first item of each bucket to be allocated in the stack, the com...

PySpark add rank column to large dataset

I have a large dataframe and I want to compute a metric based on the rank of one of the columns. This metric really only depends on two columns from the dataframe, so I first select the two columns I care about, then compute the metric. Once the two relevant columns are selected, the dataframe looks something like this: score | truth ----------------- 0.7543 | 0 0.2144 | 0 0.5698 | 1 0.9221 | 1 The analytic that we want to calculate is called "average percent rank" and we want to calculate it for the ranks of data where truth == 1 . So the process is to compute the percent rank for every data point, then select the rows where truth == 1 , and finally compute the average percent rank of those data points. However, when we try to compute this, we get OOM errors. One of the issues is that using the pyspark.sql function rank requires using Window , and we want the window to include the entire dataframe (same fore percent_rank ). Some code: w = Window.orderBy(...

Yet another

I'm using EasyPhp DevServer with Apache 2.4.25 , PHP 5.6.30 , and PHP 7.1.3 installed. For times, I usually switch between those two PHP versions, without changing any configuration element anywhere, and it works fine. Now I just added PHP 8.1.2 , and when I switch to it I get the well known error message: PHP Warning: PHP Startup: Unable to load dynamic library 'openssl' (tried: C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x230327010135\ext\php_openssl (Le module spécifié est introuvable), C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x230327010135\ext\php_php_openssl.dll (Le module spécifié est introuvable)) in Unknown on line 0 Obviously I read a lot of answers about that, but no one seem to be of help in my case, since the php.ini for 8.1.2 includes the same needed specifications than the two other ones: extension_dir = "C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x23...

How to prevent Bootstrap collapse from overflowing inside an overflow-y-scroll container?

Image
I have a container and an overflow-y-scroll CSS property. Inside it, there's a Bootstrap collapse button that expands and shows additional content when clicked. However, when the content expands, it overflows outside of the container, making it hard to read, and it messes up the page. I've tried setting the height of the collapse feature and its parent div to 100%, but it didn't solve the issue. I expected the collapse feature to expand without overflowing outside of the container, so that users can scroll down to see the entire content. A visualization of the issue I'm experiencing. <div class="container mw-25"> <div class="text-start text-white px-4">Knowledge Requirements</div> <!-- Outer box --> <div class="bg-white w-100 h-75 mt-2 mx-3 border rounded-2 rounded-end-0 p-2 overflow-y-scroll"> <!-- Inner box --> <div class="form-check"> <!-- ...

Not able to Install Mongo Db on AWS Linux 2023

I'm trying to install mongodb in Amazon Linux with below configuration NAME="Amazon Linux" VERSION="2023" ID="amzn" ID_LIKE="fedora" VERSION_ID="2023" PLATFORM_ID="platform:al2023" PRETTY_NAME="Amazon Linux 2023" ANSI_COLOR="0;33" CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2023" HOME_URL="https://aws.amazon.com/linux/" BUG_REPORT_URL="https://github.com/amazonlinux/amazon-linux-2023" SUPPORT_END="2028-03-01" I tried to install using Tarball and repo. However it got failed with below error [root@ip ~]# mongod --version mongod: /lib64/libcrypto.so.10: version `OPENSSL_1.0.2' not found (required by mongod) mongod: /lib64/libcrypto.so.10: version `libcrypto.so.10' not found (required by mongod) mongod: /lib64/libssl.so.10: version `libssl.so.10' not found (required by mongod) [root@ip ~]# openssl version OpenSSL 3.0.8 7 Feb 2023 (Library: OpenSSL 3.0...

cbind/join complex dataframes of different lengths without identifier

Thank you so much in advance for any help-- I am trying to rbind/join two dataframes that do not have a unique identifier- the format is complex because of how they were webscraped. df1 contains assay results, with 1 row for each assay occurring on a day, and a row (ID, Name, Concentration) separating out assays that happened on different days. df2 contains 1 row for the date of the assays. I need to bind the relevant assay date (df2) to each of the assay results (df1). df1 = data.frame(matrix(0, 13, 3)) df1$X1 = c("ID","1","2","3","4","5","ID","1","2","3","ID","1","2") df1$X2 = c("Name","Jose","Mary","Doug","Luisa","Pam","Name","Jose","Doug","Lou","Name","Luisa","Pam") df1$X3 = c("Concentration","4.2",...

How can I configure AMQ broker on Openshift 4 to ensure messages are consumed by only one pod in a publish-subscriber model?

I am using Openshift 4 to deploy multiple microservices which are connected via an AMQ broker using a publish-subscribe messaging model. However, when I increase number of pod to 2, I am running into an issue where all pods are consuming the same message, rather than just one. Can someone suggest how to configure java code below or the AMQ broker to ensure that messages are consumed by only one pod in a publish-subscriber model? Are there any specific settings I should be aware of or changes I need to make to my configuration? Thank you. Configuration: @Bean public JmsListenerContainerFactory<DefaultMessageListenerContainer> jmsListenerContainerPublisherFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setErrorHandler(t...

COGNOS SQL: COLUMN 1+'|'+COLUMN 2 +'|'+COLUMN 3 keeps only first row information instead of concatenating just columns for each row

I have a database with 3 columns and I want to generate a report with only one column, that is the concatenation of column 1-ID, column 2-DATE and column 3-LOCATION separated with pipeline: ID DATE LOCATION 10 20230325 UK 11 20230325 UK 11 20230325 US 12 20230323 PT I have tried concatenating the columns with '+' into a new column 4 like so: DATE+'|'+ID+'|'+LOCATION However, when I prepare a report and only select column 4, I am only getting one row instead of the 4 rows of data in the database: Current output of column 4 --> 1 row only with the following value: 10|20230325|UK Expected output of column 4 --> 4 rows with the following values: 10|20230325|UK 11|20230325|UK 11|20230325|US 12|20230323|PT How can I concatenate the 3 columns with pipeline delimiter and generate a report where all rows are shown instead of just the first row?

C++ multithread joining only working on the first thread but not working for other threads

I was curious as to why the code below works and executes fine for the n = 1 case, but when I make n anything greater than 1 I get a system error most of the time. I also know there is joinable() for checking if a thread is done but it is terrible since it blocks the main thread. If there is a more elegant solution to checking when a thread is done than passing a boolean pointer to a method, that would be appreciated. #include <iostream> #include <thread> #include <atomic> #include <array> void my_function(bool* is_thread_done) { std::cout << "Thread started" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "Thread finished" << std::endl; *is_thread_done = true; } int main() { const int n = 1; std::array<std::thread, n> arr; std::array<bool, n> is_thread_done; for (int i = 0; i < n; i++) { is_thread_done[i] = false; ...

Transform Excel table into lists below each table parameter (and skip blanks)

Image
I know there are similar questions, and I've tried to use all of the codes mentioned in them - but something isn't working for me. Please help. My input is an excel table set up like this: VISITCODE dm1 dm2 dm3 dm4 thing1 B A A thing2 A B B thing3 A B A thing4 B B A I'd like the output to look something like this:

toString and function issue

class Addresses { var streetname: String var streetnumber : Int var suburb: String var postcode:Int init( streetname:String, streetnumber:Int, suburb:String, postcode:Int ) { self.streetname = streetname self.streetnumber = streetnumber self.suburb = suburb self.postcode = postcode } func toString( streetname:String, streetnumber:Int, suburb:String, postcode:Int ) -> (String) { return (streetnumber),streetname, suburb, postcode } } I'm trying to create class named Address which stores the postcode, suburb, street name and street number of a building. An initialiser as well as a toString method which returns a String of a human-readable version of the class. This error message keeps popping up Cannot convert return expression of type 'Int' to return type 'String'

Network interface drop 1518 bytes Ethernet frame received from direct Ethernet link cable sent by tcpreplay. why?

I have two server linked to each other. I tried to send a pcap from one of the servers via direct link using tcpreplay command. The pcap contains an HTTP POST session which size of some frames is 1518 bytes [Ethernet header(14 bytes)][payload(1500 bytes)][fcs(4 bytes)] , but the receiver server's interface drops packets with size over 1514 bytes. Everything works correctly when I remove last 4 bytes(FCS) of all packets and send pcap. Or when I change MTU of the sender and receiver interface from 1500 to 1504. I can understand why the sender's interface MTU needs to be 1504. But why does the receiver's interface MTU need to be 1504? I expect the receiver's interface doesn't consider FCS bytes just like Ethernet header, because This is what is happening when the actual Ethernet frame of size 1518 is coming toward receiver's interface from internet. Is there any difference between when the receiver consumes Ethernet frames from internet and when two servers are l...

Install fontawsome on Rails 7.0.4.3

How can I install fontawsome for icons on Rails 7.0.4.3 and ruby 3.2.1 I tried three methods: 1. yarn add @fortawesome/fontawesome-free + import "@fortawesome/fontawesome-free/js/all" 2. ./bin/importmap pin @fortawesome/fontawesome-free + import "@fortawesome/fontawesome-free" 3. gem "font-awesome-sass", "~> 6.3.0" + bundle install + @import "font-awesome" But when I test with an icon it is not rendering.

How Can I Write An Integration Tests For A Rust CLI Tools That Use Inquire?

Here is an example of some code I would like to test: fn main() { let ans = Confirm::new("Yes or no?") .with_default(false) .with_help_message("(It's not a trick question)") .prompt(); let res = match ans { Ok(true) => "You said yes!".to_string(), Ok(false) => "You said no...".to_string(), Err(_) => "Error with questionnaire, try again later".to_string(), }; println!("{}", res); } I am trying to use the "Command" library to write a test, but I have having some problems. My first problem is sending the different types of user input when prompted (eg. enter with no input, y, Y, yes, Yes, YES, n, no, No, NO, nO, false, foo) and then asserting that the appropriate response is logged to the console. I would also like to assert that the correct initial prompt message and help message are logged to the console. How can I do this? Here' m...

Google Map Custom Markers from URL slow to load

Problem, markers take about 10 seconds to load despite the fact that they are very small icons. I'm sure there's a problem with the way I am calling them to load. I would expect them to be nearly instant. I have a working Google Maps example linked here. You'll see the markers download slowly. I have another example of this in FlutterMap which works fine and loads everything immediately. What do I have to do to get my markers to load all at once on the Google Map? import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:custom_marker/marker_icon.dart'; import '../../models/marker_collect_model.dart'; class PhotoCustomMap extends StatefulWidget { @override _PhotoCustomMapState createState() => _PhotoCustomMapState(); } class _PhotoCustomMapState exten...

TIMEOUT no longer waits as stated

I originally posted this on Microsoft Answer Community website but got told they don't deal with this sort of question (funny, as I suspect it's a bug in one of their CMD.EXE commands or some related thing). ..... Here's my question... Suddenly Windows 11 cmd.exe command TIMEOUT is failing for me in a CMD file - it doesn't wait the prescribed time. e.g. TIMEOUT /T 8 reports the starting seconds for countdown and immediately exits. In debugging things, I found that this does not occur if I manually enter it into a CMD.EXE window prompt. Further testing shows that it actually the first call of TIMEOUT in a CMD file that fails .. subsequent ones work as documented. My current circumvention is to code a TIMEOUT /T 1 at the start of the CMD file to ensure the 'real' ones behave. A simple batch file demonstrates the effect (on my machine at least). Batch file (saved as "test.CMD" in my case)... NB editor seems to want to combine some lines shown belo...

Rails: Two Applications using the same database (WebService <--> API)

Here on Stack has the same question that I wanted to do but my question has one different aspect. Today I have a rails application that's managing the web application and API but wanna separate it to manage the server resources more efficiently. The question is: How App1 could know when App2 inserts a new record? Rpush? Sql Trigger? Or transform Api into a gem? App1 - WebService Port 80 using DB1 class Post < ActiveRecord::Base belongs_to :user before_save :do_stuff_when_app2_insert_record #I know this doesn't work in this environment def do_stuff_when_app2_insert_record ... end end App2 - API connection - Port 8080 using DB1 class Post < ActiveRecord::Base belongs_to :user end Post.create(name: 'post')

Update randomly indexed database columns in PHP [closed]

I am pushing a hidden field into the database that will be updated as tickets get bought; this is the field that inserts the column: <input type="hidden" class="other-bookable-tickets-sold" name="_other_tickets[-1][sold]" value="0"> What I have tried: In the database it creates columns for each field added e.g _other_tickets[0][sold], _other_tickets[1][sold], _other_tickets[2][sold] e.t.c How do I access and update these random columns? // update tickets sold function update_ticket_sold( array $tickets, $listing_id ) { $other_tickets = get_post_meta( $listing_id, '_other_tickets', true ); if (isset($tickets) && is_array(($tickets))) { $i = 0; foreach ($other_tickets as $key => $ticket) { if (in_array(sanitize_title($ticket['name']), array_column($tickets,'ticket'))) { $ids = array_keys($ticket); $column = '_other_tickets[' . ...

Problem with redux-toolkit (createAsyncThunk) in react native expo app

Hello and thank you in advance for your help. My problem is on redux-toolkit on a react-native application with Expo. To put you in the context I am quite a beginner. Here is my code : export const fetchStationsInformations = createAsyncThunk( "stations/fetchStationsInformations", async () => { console.log(process.env.NODE_ENV); if (process.env.NODE_ENV === "test") { return require("@data/stationsInformations.json"); } const response = await api.get("/stationsInformations"); return response.data; } ); export const fetchStationsStatus = createAsyncThunk( "stations/fetchStationsStatus", async () => { console.log(process.env.NODE_ENV); if (process.env.NODE_ENV === "test") { return require("@data/stationsStatus.json"); } const response = await api.get("/stationsStatus"); return response.data; } ); I would like to understand why, when in ...

Angular Cannot read properties of undefined in html

Image
I'm an angular rookie and working on getting better at it. I have the three files where I'm using a service( Studentservice.ts ) which emits an observable( ShowBeerDetails method ) and I later subscribe to it in my component( Beer-details.component.ts ). I made sure that I'm receiving the observable values by console logging in my components onInit method and the value of beerObj prints just fine. The issue is I get the below error in my HTML when the view is loaded. I think the reason is shared service isn't resolving beerObj variable before view tries to reach it.(I may be wrong about this). I tried adding <div *ngIf="beerobj"> statement which prevents the console error but since beerObj still remains undefined I'm not seeing my values(name, price, and Id) printed. I'm not sure to fix this. I have read multiple SF questions but none helped me. ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl') Angular materia...

Apple Metal lineStrip how to draw thicker lines

Image
I am developing an iOS application using XCode 14.2, and my deployment target is iOS 16.2. I have a list of X,Y, and Z values that I want to draw with Metal using lineSrip. This works, however the line that is drawn is too thin for my purposes. I've read about various strategies on how to thicken the line and I've decided to attempt to draw the same line many iterations with a small amount of noise each time to give the appearance of a thicker line. I generate 3 random floats each time through the render loop and send them to my vertex shader with a uniform. The issue is that the resulting line seems to be more periodic than random and more iterations does not seem to give the appearance of a thicker line. How can I draw thicker lines using this strategy? Thank you. Draw many iterations: // Draw many iterations for iteration in 1...1024 { scene.track?.draw(encoder: commandEncoder, modelMatrix: accumulatedRotationMatrix, proj...

Stack and explode columns in pandas

I have a dataframe to which I want to apply explode and stack at the same time. Explode the 'Attendees' column and assign the correct values to courses. For example, for Course 1 'intro to' the number of attendees was 24 but for Course 2 'advanced' the number of attendees was 46. In addition to that, I want all the course names in one column. import pandas as pd import numpy as np df = pd.DataFrame({'Session':['session1', 'session2','session3'], 'Course 1':['intro to','advanced','Cv'], 'Course 2':['Computer skill',np.nan,'Write cover letter'], 'Attendees':['24 & 46','23','30']}) If I apply the explode function to 'Attendees' I get the result Course_df = Course_df.assign(Attendees=Course_df['Attendees'].str.split(' & ')).explode('Attendees')...

UseLazyLoadingProxies with EF core loads whole list when adding a new child entity

I'm using UseLazyLoadingProxies with EF core, postgresql and DDD architecture. I have Parent and Child objects lets say they look something like this: public class Parent { public int Id { get; private set;} public string Name {get; private set} public virtual ICollection<Child> Children {get; private set} public void AddChild(Child child) { Children.Add(child); } } public class Child { public int Id { get; private set;} public string Name {get; private set} } when I use parent.Add(child) proxy does its thing and pulls whole list of child elements before adding new child in the list, is there a way to work around it? because child elements can be 50 000 and right now its pulling all the rows from database for no reason other than to add a new child entity

Troubleshooting Google Domains hosting with Amazon Route 53 -> Application Load Balancer

I have a domain managed on Google Domains and would like it to point to an Amazon route 53. I've configured the custom name servers on Google to point to the ones for my public hosted zone, and using WHOIS can confirm that these are the name servers being returned when I try to access the domain. The problem is that when I navigate to this domain in my browser it says "Server not found." I have an alias record set up in Route 53, of type A, that points to the Application Load Balancer running my application (and another alias for www.domain.com ). When I hit "test record", and select type A it returns an IP address that I can go to and verify that it is running my app. TLDR: WHOIS shows the Amazon name servers, testing the records in Route 53 returns IPs from an alias'd A record that are indeed hosting my app, but when I navigate to domain.com in my browser nothing happens. Thanks! I've tried updating the type of the record in Route 53 to both AAAA an...

Can I initialize 2 Flutter apps?

I have a site, mysyte.com, where I have two Flutter apps, one in the root folder mysite.com/ and the other at mysite.com/second/. I wanted to know if by going directly to mysite.com/second/, instead of only uploading the second app, is it possible to upload also the app in root folder? So if I switch from the second to the first via url_launcher I don't have to wait for flutter to load... I don't have much web skills so maybe it's a problem there. I searched the documentation and online but couldn't find anything

microprofile-openapi-api 2.0 switches off hibernate-jpamodelgen

I have a java microservice-project with theese two dependencies defindes in my gradle.build file: implementation(group: 'org.eclipse.microprofile.openapi', name: 'microprofile-openapi-api', version: '1.2') annotationProcessor('org.hibernate.orm:hibernate-jpamodelgen:6.1.6.Final') This works, meaning that i get my JPA metamodels created. But as soon as i bump microprofile-openapi-api to 2.0 or above, jpamodelgen no longer gets run (no errors, it just does not run). It is like clockwork, that going above 1.2 creates the problem. Any ideas as to what is causing this behavior and what can be done ?

RuntimeError: GET was unable to find an engine to execute this computation when I using Trainer.train() from hungingface

RuntimeError Traceback (most recent call last) Input In [46], in <cell line: 1>() ----> 1 train_results = trainer.train() 2 wandb.finish() File /opt/conda/lib/python3.10/site-packages/transformers/trainer.py:1543, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs) 1538 self.model_wrapped = self.model 1540 inner_training_loop = find_executable_batch_size( 1541 self._inner_training_loop, self._train_batch_size, args.auto_find_batch_size 1542 ) -> 1543 return inner_training_loop( 1544 args=args, 1545 resume_from_checkpoint=resume_from_checkpoint, 1546 trial=trial, 1547 ignore_keys_for_eval=ignore_keys_for_eval, 1548 ) File /opt/conda/lib/python3.10/site-packages/transformers/trainer.py:1791, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval) 1789 tr_loss_step = self.training_step(model, i...

Fit Next/Image component inside div whilst maintaining aspect ratio and border rounding

Image
I've been trying to style a NextJS image with rounded corners whilst also growing to fit it's containing div (Blue on image, difficult to see but there) and maintaining aspect ratio (unknown until runtime). All that is broken with what I currently have, is the image not getting the border-radius but the box surrounding it does (Black on image). I cannot find a way to get the border radius to work without hard coding the image size, as that must be dynamic. The only other vector to consider is that this is all contained inside another fixed positioned div (Red on image) that contains the whole popup. I have tried the below from sugguestions in other threads and it almost works, the only issue I have found is that the image does not recieve the rounded corners due to it's box being larger than the content and thus rounding that box and not the image. {/* Card that shows on click */} <div className='fixed z-10 w-full h-full left-0 top-0 invisible bg-bla...

Use Greasemonkey to change URL links within a given domain

I'm new to Greasemonkey (Tampermonkey actually), and I'd like to write a very short script that: Is valid within a given domain (e.g. "mydomain.com") Parses all button-related URL links within the active tab Replaces them as follows : Original URL link: [string_1]/[useful_part]?[string_2] To be replaced with: [replacement_1]/[useful_part] So everything after the "?" can be discarded, including the "?" itself. More specifically, URL links are as follows: http://127.0.0.1:6878/webui/player/[useful_part]?autoplay=true So string 1 = "https://ift.tt/JuzOUHN" and string 2 = "autoplay=true" I've seen a similar question here: Rewrite parts of links using Greasemonkey and FireFox But I'm not good enough at RegEx, so I couldn't adapt the script to my own needs. I've also looked for Firefox extensions, but the available extensions don't seem to allow the level of text replacement that I'm seeking...

Random numbers between -1 and 1 summing to 0

With R, how to generate n random numbers x_1 , ..., x_n that lie between -1 and 1 and that sum to 0 ? What about the generalization to another sum and another range?

Getting rid of unwanted commits

Image
My branch was behind master, I used git pull origin master and now I have 44 commits not mine and I don't want to push them along with my changes. How do I fix this?

What is the name of the Master Stencil used by the Organization Chart Wizard in Visio?

I've looked everywhere to see what the Master Stencil is called that the Organization Chart Wizard uses, in order to reference it in some VBA but I can't find it anywhere. Anyone know what it's called?

foreach in powershell to retrieve processes

The output of processes does not show in the results. I'm logging into each server and pulling the processes. If I do just one server without the foreach it outputs the processes, however when I add a for each with a list of servers, it doesn't show the results $serverListFile = "servers.csv" $global:ServerLists = Import-Csv -Path $global:ScriptPath\$ServerListFile -Delimiter "," | ForEach-Object { $_.servers $currentServer = $_.servers Write-Host $currentServer Write-Host "Getting first 5 Processes on" $currentServer Invoke-Command -ComputerName $_.servers -Credential $Cred -ScriptBlock { Get-Process | Select-Object -First 5 } } Here are the results: Server1 Getting first 5 Processes on Server1 Server2 Getting first 5 Processes on Server2 Server3 Getting first 5 Processes on Server3

error is always displayed on Azure AD B2C, why?

I am trying to display a custom error, idea is user may have several MFA setup, user introduces login, then goes to a screen where he needs to select the MFA that he wants to use, if the MFA is in a list, then he can proceed, if it is not, then we need to display an error. This is my code: ... <OrchestrationStep Order="3" Type="ClaimsExchange" ContentDefinitionReferenceId="api.selfasserted"> <ClaimsExchanges> <ClaimsExchange Id="MFAConfigChecks" TechnicalProfileReferenceId="SelfAsserted-GettingSelectedMFAParameter" /> </ClaimsExchanges> </OrchestrationStep> ... <TechnicalProfile Id="SelfAsserted-GettingSelectedMFAParameter"> <DisplayName>Getting selected MFA Parameter</Displa...

fetch() POST request returns "Error 415 Unsupported Media Type"

When trying to upload a PDF file using fetch(), I keep getting a 415 error. The PDF file is saved in the same directory as the js file, and the name is definitely correct. async function uploadFile(filePath, extension, timestamp) { const url = "https://api.hubapi.com/files/v3/files"; // const url = "https://api.hubapi.com/filemanager/api/v3/files/upload"; // also doesn't work. var filename = `${filePath}.${extension}`; var fileOptions = { access: 'PRIVATE', overwrite: false, duplicateValidationStrategy: 'NONE', duplicateValidationScope: 'ENTIRE_PORTAL' }; var formData = { file: fs.createReadStream(filename), fileName: `${filename} (${timestamp}).${extension}`, options: JSON.stringify(fileOptions), folderPath: 'Quotations' }; try { const response = await fetch(url, { "method": "POST", ...

Replace empty values with values of other records in a dataframe

I have the following problem I need to replace the empty cel values in dataframe with the values of the costs of CustomerNr of other records df1 = pd.DataFrame([[1004,''], [1004, 'D'],[1005, 'C'], [1010,'A'], [1010,''],[1010,''],[1010,''],[1004, '']], columns=['CustomerNr','Costs']) CustomerNr Costs 1004 1004 D 1005 C 1010 A 1010 1010 1010 1004 Desired output: CustomerNr Costs 1004 D 1004 D 1005 C 1010 A 1010 A 1010 A 1010 A 1004 D

Move custom attribute below product title on shop page in WooCommerce

Afternoon Stack Overflow, I've been trying to move the custom div I've created which displays a custom attribute on the shop grid for products. I want the small text which says '2% Nic Salt, 600 Puffs, Inhale Activated' below the product title. I'm using this code to display the attribute. // Fail Safe add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes'); function display_shop_loop_product_attributes() { global $product; // List the correct Attributes via pa_ $product_attribute_taxonomies = array( 'pa_grid-attributes', 'pa_grid', 'pa_styling', 'pa_number' ); $attr_output = array(); // Initializing // Loop through foreach( $product_attribute_taxonomies as $taxonomy ){ if( taxonomy_exists($taxonomy) ){ $label_name = wc_attribute_label( $taxonomy, $product ); $term_names = $product->get_attribute( $taxonomy ); ...

Create Performance Score, by Month using Switch with Multiple Conditions

Image
novice PBI/DAX user here. I'm trying to add a SCORING assessment for this KPI using IF statements. The KPI is calculated based on MONTH date bins. It doesn't seem to be working. Any ideas appreciated? Here is a sample of what I am receiving. I've circled SOME of the values that should be either Successful or Outstanding. Snippet PBI Report Here is the measure that calculates Avg Calls / AE (Person) / Month which is referenced in the IF statement. Avg Calls / AE / Month Calculation The expected results should show some SUCCESSFUL and OUTSTANDING results. UPDATE: I created a NEW TABLE (New Opportunities Created - SUMMARIZED TABLE) from the original table which contains row level detail (New Opportunities Created). Then I created a new column to calculate SCORE: Score = SWITCH(TRUE(), 'New Opportunities Created - SUMMARIZED TABLE'[Segment] IN {"Field Sales", "LTL"} && 'New Opportunities Created - SUMMARIZED TABLE'[#Opps]...

.Net test multiple connections for AD authentication using system.web.security (membership)

Most of our .net IIS webapps use the System.Web.Security in .net to validate user logins in AD. However, during a company transition period, we currently have 4 AD domain controllers. I am looking for a way to test the AD user login against other AD connection strings in the event that one is down or that a user is using a different domain password. Our code is just: bool isValidAdUser = Membership.ValidateUser(model.UserName, model.Password); And the connection string is set inside the Membership tag in web.config. How I can I add more connection strings?

Metrics to compare two sets of 1D points

I'm training an AI model to predict where to place train stations along a train track . I want to feed my model some information about the train track, which generates a series of points A , B , C , ... that correspond to stations that I should place on the train track. A prediction P could look like: =====A========================B===============================C========== I also have a ground truth T for my training examples. For instance, that could look like: =========A====================B=========C=============================D== Now, what I want is a metric to measure my model. I've been thinking about possible solutions, but none of the usual candidates seem to fit this problem. Some ideas I've considered are: Creating a custom F1 score To do so, get the distance of each point in P with respect to the closest point in T (precision). Likewise, get the distance of each point in T with respect to the closest one in P (recall). Duplicates are allowed ( f...