Posts

Showing posts from November, 2020

How to execute a Cloud Function after Dataflow job has succeeded?

I want to trigger Cloud Function only if Dataflow job execution completed successfully. Cloud Function should not be triggered if Dataflow job is failed. I am running a Dataflow job using a Dataflow template (jdbc to BigQuery) from the the Dataflow UI. There is no option to trigger any Cloud Function or something after job execution. Also, I can't make changes in template code. What's the way to trigger Cloud Function? from Recent Questions - Stack Overflow https://ift.tt/2KGD9KP https://ift.tt/eA8V8J

How can you optimize linear search if applied on an ordered list of items?

In an unordered list of items, you must check every item until you find a match. How can you optimize linear search if applied on an ordered list of items? from Recent Questions - Stack Overflow https://ift.tt/39etKoe https://ift.tt/eA8V8J

How to install Azul JDK 16 on Apple Silicon M1 Mac?

I understand I can run Java under emulation with Rosetta 2, but I've read that with Azul Open JDK 16 that I can get native performance. I downloaded the file, but have no idea what to do. Azul's help page is not helpful. If someone can give some basic steps on how to get the JDK running natively that would be awesome! from Recent Questions - Stack Overflow https://ift.tt/37hmxRv https://ift.tt/eA8V8J

How can I get the boundaries of a regular expression?

Lets say I have a string that I need to split into an array based on a pattern. Many language split methods will remove the things matched by the pattern causing a split of a string testtestt on the regular expression .{2} ending up with a result of t This is not the result I wanted so how can I use a regular expression only to capture the borders of what is matched with the same scenario above being matched as te|st|te|st|t and as a result being split into an array of ['te','st','te','st','t'] ? Note: This is not language specific and the ideal answer would be a regular expression instead of a piece of code exclusive to certain languages. from Recent Questions - Stack Overflow https://ift.tt/2Jby6lv https://ift.tt/eA8V8J

Understanding Types Merging in The Typescript

I am new to typescript and I have seen in many projects they are using the following type TypeA | TypeB TypeA & TypeB TypeA | (TypeB & TypeC) | TypeD (TypeA | TypeB)[] What is difference between each of them. Also please share the documentation link for further reference Also please let me know what this technique actually called in typescript from Recent Questions - Stack Overflow https://ift.tt/36i14Zq https://ift.tt/eA8V8J

What status should I use for Sentry performance in case of System Exception?

Testing bot 123. what performance status should I use for System Exceptions? so far I am only aware of HTTP request status. from Recent Questions - Stack Overflow https://ift.tt/2VdcnvE https://ift.tt/eA8V8J

how change date weekly

I am trying to use this code ( Change week in a calendar when a button is clicked ) to display the date of a whole week from Sunday to Saturday. But the problem is that for example November 2020 ends on the 30th, but the script continues to count 31, 32, 33, 34, 35 .. function renderCalender(d){ let t = d.getDay(); let weekday = document.querySelectorAll(".weekday"); for (let i = 0, j = 1; i < weekday.length; i++) { let x = t-i; if (t > i) { weekday[i].innerHTML = `${d.getMonth()+1}/${d.getDate()-x}/${d.getFullYear()}`; } else if (t < i) { weekday[i].innerHTML = `${d.getMonth()+1}/${d.getDate()+j}/${d.getFullYear()}`; j++ } else if (t === i) { weekday[i].parentNode.style.backgroundColor = "rgb(100, 100, 100)"; weekday[i].innerHTML = `${d.getMonth()...

How to make pictures from database clickable with different HTML?

i have this code: <a href="produkt1.html"><img style="margin-left:30px;" src="<?= $row['zdjecie_produktu'] ?>" class="card-img-top" height="250"></a> But i want each picture to be linked with different HTML (in this case with picture of the product with its’ description)... is there any code for that? from Recent Questions - Stack Overflow https://ift.tt/3fM6a3c https://ift.tt/eA8V8J

Create new VSCode C++ project folder: via Developer Command Prompt or GUI?

I'm new to VSCode and had a question about creating your project folder. This vscode site resource teaches you to create the project via DevCMD. I can't tell what the difference is with creating the folder in your OS (Windows) and then opening the folder as a project via the VSC GUI, but the latter doesn't work. Can you tell me why? P.S., I'm relearning C++ and would like to find a place, chatroom, forum, where I can ask stupid questiolns until I've learned the fundamentals again. If you have any recommendations I'd appreciate a message. from Recent Questions - Stack Overflow https://ift.tt/36hPoFZ https://ift.tt/eA8V8J

Powershell Import/Export-csv group & join cells

I have a csv file which I need to group and join various cells together and have them then separated by a semi-colon in the csv layout is as such CSV Layout I have managed to join the cells 'price' & 'functionnumber' together and separate them with a ';' but for 'datedespatched' and 'username' which just need to display the 1 name or date the cells return with 'System.Object[]' displayed in the condensed cell, the 'referencenumber' cell appears to condense down fine. This is my current code and the output I receive from it Import-Csv 'C:\temp\test.csv' | Group-Object ReferenceNumber |ForEach-Object { [PsCustomObject]@{ ReferenceNumber = $_.Name userName = $_.Group.userName DateDespatched = $_.Group.DateDespatched functionnumber = $_.Group.functionnumber -join '; ' Price = $_.Group.Price -join '; ' } } | Export-Csv 'C:\temp\test-e...

I want to design chat application using firebase firestore as Database with chat bubble message

I really want to create a firebase firestore chat application in Android in which i want to show the message in a chat bubble which inflate Google sign in (i know Google sign in procedure) but i am not able to sort our messages according to time when they created from Recent Questions - Stack Overflow https://ift.tt/3okbuOD https://ift.tt/eA8V8J

update table mariadb from bash script

Trying to write an table update statement in my bash script but gives me a syntax error mysql Ver 15.1 Distrib 5.5.68-MariaDB , for Linux (x86_64) using readline 5.1 mysql -u UserName --password=MyPassword -D MyDatabase -e 'UPDATE MyTable SET name = SomeName WHERE number = someNumber ;' ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SomeName WHERE number = someNumber' at line 1 from Recent Questions - Stack Overflow https://ift.tt/3mkZknH https://ift.tt/eA8V8J

I have a segmentation fault in c++, where did I go wrong?

Trying to traverse a 2d vector in order to find index(es) of a certain key value which is the number 1. I looked up what a segmentation fault was and it said that it happens when you try to access too much memory, but I don't get how I'm doing that. #include<iostream> #include<algorithm> #include <vector> #include <cmath> using namespace std; int main(){ vector<vector<int>> matrix; int n; int i = 0; int j = 0; for (int i =0; i<5; i++){ for (int z = 0; z<5; z++){ cin >> n; matrix[i][z] = n; } } while (matrix[i][j] != 1 && ((i && j) < matrix.size())){ while (i != 5){ i++; while (j != 5){ j++; } } } cout << abs((2-j) + (2-i)) << endl; } from Recent Questions - Stack Overflow https://ift.tt/33nRHWn https://ift.tt/eA8V8J

What is the difference between key and id in React component?

I have this in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={this.state['filter']['provider']} onChange={this.handleChangeProvider} /> <RefreshSelect isMulti cacheOptions id='b' key='b' components={makeAnimated()} options={this.state['filter']['provider']} onChange={this.handleChangeProvider} /> In the definition of this child component, I have the constructor that updates default values depending on the id/key. export default class RefreshSelect extends Component { constructor(props) { super(props); // console.log(props) // console.log(props.key) if (props.key==''){ this.state = { value: [{ value: 'all...

Why is my recursive prolog script not working?

Can anyone help me out with Prolog recursive functions? I have to type in a recursive input and it should give me true, but it gives me an error and I sitll don´t know how to figure it out Bob(Food(X)):- Bob(X). Bob(eat(X)):- Bob(X). Bob(yummy(X)). Is what I have and Input Food(Food(eat(yummy)))should result in true But I get an Error: Unknown procedure: Food/1 (DWIM could not correct goal) this is basically the whole story. from Recent Questions - Stack Overflow https://ift.tt/3fLUU7b https://ift.tt/eA8V8J

Uninitialized local variable c4700

https://www.programiz.com/cpp-programming/structure-function I'm learning how to pass structures to functions using the website above, I spent 2 hours of trying to figure out what was wrong with my program, I decided to copy and paste the code on the website to see if they did it correctly and the same error came up. If anyone could help it would be appreciated, there code below. Warning C6001 Using uninitialized memory 'p'. Structure-Function C:\DEV\C++\Structure-Function\Structure-Function\main.cpp 18 Error C4700 uninitialized local variable 'p' used Structure-Function C:\DEV\C++\Structure-Function\Structure-Function\main.cpp 18 #include <iostream> using namespace std; struct Person { char name[50]; int age; float salary; }; Person getData(Person); void displayData(Person); int main() { Person p; p = getData(p); displayData(p); return 0; } Person getData(Person p) { cout << "Enter Full name: ";...

How do I fix the input prompt in this C code?

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <memory.h> #include <ctype.h> #include <time.h> struct customer { char name[45]; char invoice[4]; char service[2]; char carNo[16]; char fee[3]; bool urgent; time_t date; }; /*********************************************************************************************/ void toFile(char*); // will pass string (char*) to it and it'll write it to record.txt - DONE void displayMenu(void); // will display the menu - DONE void newInvoice(int invoiceNo); /*********************************************************************************************/ int main() { char toContinue; int invoiceNo =1; // format of invoices in txt file do { newInvoice(invoiceNo); invoiceNo += 1; // asking if user wants to continue to another order or close the program ...

Password saving batch file for unlock/login

Is there any way to create a password then have that newly made password stored in the same batch file as the login code and keep it as that new password???? Here's a visual example of what i mean Typing in the incorrect password Typing in the correct password Setting new password Is there any way to do this with 1 batch file entirely without having to make another one to save the data?? I am trying to do this on windows 10. I am trying to do this so I dont have to do a preset password like: if %pass%== 12345 goto Login instead I want it to where every user can create their own special password without needing to edit the code from Recent Questions - Stack Overflow https://ift.tt/39p4n2S https://ift.tt/eA8V8J

Undefined variable in php mysqli connect

I have a problem with mysqli connection. Undefined variable $host, $user and $password PHP: <?php require_once "dbconnect.php"; $polaczenie = mysqli_connect($host, $user, $password) or die ('Nie można połączyć się z MySQL.'); mysqli_select_db($polaczenie, $database) or die ('Nie można połączyc się z bazą.'); dbconnect file: <?php $host="localhost"; // Nazwa hosta $user="root"; // Nazwa uzytkownika mysql $password=""; // Haslo do bazy $database="mieszkancy"; // Nazwa bazy ?> from Recent Questions - Stack Overflow https://ift.tt/2Viv1SZ https://ift.tt/eA8V8J

Styled Components + TypeScript + new fonts Issue

I want to use some font I've downloaded from the Google fonts on my React/TypeScript application. Unfortunatelly, I can not load the font. I went through some articles describing the issue and how to handle it but with no luck. Take a look at the below files and let me know if there is something I'm missing: I want to use the font here: Header.tsx import React from "react"; import styled from "styled-components"; import headerBg from "../assets/pattern-bg.png"; import GlobalFonts from "../assets/fonts/fonts"; const Header: React.FC = () => { return ( <HeaderSection className="header"> <GlobalFonts /> <InputWrapper> <MainHeading>IP Address Tracker</MainHeading> <label htmlFor="ip-input"> <input type="text" id="ip-input" /> </label> </InputWrapper> </HeaderSection> ); }; ...

How to return an Iterator with associated type being generic from a function?

For a function like this: fn generate_even(a: i32, b: i32) -> impl Iterator<Item = i32> { (a..b).filter(|x| x % 2 == 0) } I want to make it generic, instead of the concrete type i32 I want to have any type that is range-able and provide a filter implementation. Tried the formula below without success: fn generate_even(a: T, b: T) -> impl Iterator<Item = T> where T: // range + filter + what to put here? { (a..b).filter(|x| x % 2 == 0) } How can something like this be implemented? from Recent Questions - Stack Overflow https://ift.tt/3lojc89 https://ift.tt/eA8V8J

FixedUpdate doesn't register all keys (unity)

I ordered a book and I've been following it's instructions fully. The only problem is when I put my movements in FixedUpdate it doesn't register every key. I've read many answers to this but they all say put your inputs in Update and put all of the physics in FixedUpdate. I did just that but when I press the spacebar 30 times it only jumps around 5. This is some of my code (I apologize if it's readability is bad, I'm just starting out.): using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerBehavior : MonoBehaviour { public GameObject bullet; public float moveSpeed = 10f; public float rotateSpeed = 10f; public float jumpVelocity = 5f; public float distanceToGround = 0.1f; public float bulletSpeed = 100f; public LayerMask groundLayer; private float vInput; private float hInput; private Rigidbody _rb; private CapsuleCollider _col; private bool isShooting; privat...

Python Plotly - geocoding latitude and longitude - want different symbols depending on type of facility

I am geocoding a list of facilities and I want to the output to symbolize by whether they are a hospital or a clinic. Hospitals I want to appear as squares and clinics as circles. I can get my Plotly map working by mapping just one, but I'm unable to figure out how to have it plot different symbols by the facility type. I'm importing from a dataset that has the population (pop), location of the facility (location), latitude (lat), longitude (lon) and facility type (f_type). My dataset looks like this: pop | location | lat | lon | f_type 20 | Cleveland, OH | 41.4993 | -81.6944 | hospital Any help is appreciated. import plotly.graph_objects as go from plotly.offline import plot from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd df = pd.read_excel(r'D:\python code\data mgmt\listforgeorural.xlsx') df.head() fig = go.Figure(data=go.Scattergeo( locationmode = 'USA-states', lon = df['lon'], ...

Android resize view with pinch

I am making an app that adds stickers on photos and i want to resize the sticker with a pinch gesture. final ImageView newSticker = new ImageView(getApplicationContext()); newSticker.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT)); Bitmap sticker = BitmapFactory.decodeResource(getResources(),galleryList[position]); newSticker.setImageBitmap(sticker); viewGroup.addView(newSticker); I have a Frame Layout with an ImageView and i am adding Views on it. This is the onTouch method for the sticker: newSticker.setOnTouchListener(new View.OnTouchListener() { PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down PointF StartPT = new PointF(); // Record Start Position of 'img' float olddistance; @Ov...

Casting a struct onto variable length buffer

Is it possible to create struct that I can cast to a buffer of variable size? For example if I have some data that looks something like this: 0 1 2 3 4 5 6 7 8 +--+--+--+--+--+--+--+--+ | | / / / DATA / | | +--+--+--+--+--+--+--+--+ | NAME | +--+--+--+--+--+--+--+--+ | TIME | +--+--+--+--+--+--+--+--+ | ETC | +--+--+--+--+--+--+--+--+ Would it be possible to have a struct similar to this typedef struct{ uint8_t data[]; uint8_t name; uint8_t time; uint8_t etc; }Struct; and then resize Struct.data at runtime to I can cast the structure directly onto the buffer? I know I could just make a struct that uses pointers and have them point to parts of the buffer, but I was curious if this is possible because it would simplify my code and make it easier to read/use. from Recent Questions - Stack Overflow https://ift.tt/3o40xAh htt...

Gurobi Python constraint adding

Image
I want to write the following constraint in gurobi python , and I am writing that as the following and having key error. Can anyone help me by saying where I am doing mistake? for (i,j) in road_node: for t in range(1,n_time_horizon+1): m.addConstr(sum([x[v,i,u,j,u+fftt[(i,j)]] for v in vehicle_list for u in range(1,n_time_horizon+1) if u>=0 and u<=t]) - sum([x[v,j,u,i,u+fftt[(j,i)]] for v in vehicle_list for (j,i) in road_node for u in range(1,n_time_horizon+1) if u>=0 and u<=t]) <= l[(i,j)],name = "cont_4") from Recent Questions - Stack Overflow https://ift.tt/3fMaBLr https://ift.tt/2VhhXwU

MATLAB Audio Reformatting: Array dimensions are not consistent

I am working on a deep learning project that identifies words. I am using this as a guide: https://www.mathworks.com/help/audio/ug/Speech-Command-Recognition-Using-Deep-Learning.html However, when I input my own audio into the code and try to reformat it I keep getting this error... Error using vertcat Dimensions of arrays being concatenated are not consistent. Error in PLS (line 109) xPadded = [zeros(floor((segmentSamples-size(x,1))/2),1);x;zeros(ceil((segmentSamples-size(x,1))/2),1)]; This is the code where the error is occuring (I am using 16000 hz): %Sets audio to consistent size x = read(adsTrain); numSamples = size(x,1); numToPadFront = floor( (segmentSamples - numSamples)/2 ); numToPadBack = ceil( (segmentSamples - numSamples)/2 ); xPadded = [zeros(numToPadFront,1,'like',x);x;zeros(numToPadBack,1,'like',x)]; features = extract(afe,xPadded); [numHops,numFeatures] = size(features) if ~isempty(ver('parallel')) && ~reduceDataset pool =...

Understanding greater than equal to integer with decimals

main.js // JavaScript source code var quest = 0; var gold = 0; var maxrandomgold = 10; var minrandomgold = 1; var renown = 0; var renownmultiplier = 0.2; // For each click, add 1 quest number and random gold between 0-9. function questclick(number) { quest = quest + number; if (renown >= (quest / 5)) { renownmultiplier = renownmultiplier * 2; maxrandomgold = Math.ceil((maxrandomgold + (renownmultiplier * 50))/1.5); minrandomgold = Math.ceil(maxrandomgold/2); } renown = Math.round((renown + renownmultiplier) * 100) / 100; gold = gold + (Math.floor(Math.random() * maxrandomgold) + minrandomgold); document.getElementById("quest").innerHTML = quest; document.getElementById("renown").innerHTML = renown; document.getElementById("gold").innerHTML = gold; document.getElementById("minrandomgold").innerHTML = minrandomgold; document.getElementById("maxrandomgold").innerHTML = ma...

How to display content from selected WPF ComboBox item C#

Image
i hope everyone is well I am building a small application in C# and WPF, I am trying to add a functionality where when the combo Box is clicked and a certain element is selected, I want to display the contents of the text, but I cant seem to get it right. I would love some input on how to solve this issue, please take a look at the C# code and if you have a solution to it please post it, thank you, NOTE as you might see from the code, I am a beginner coder. Thanks in advace for the help. namespace WPFDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); textToDisplay.IsReadOnly = true; SaveFileDialog saveFileDialog = new SaveFileDialog(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Import new template"; openFile...

socket.gethostbyaddr raises error when used on localhost

Flask is unable to run in Python 3.6 onwards (works fine in Python 2.7-3.5), and the only change I've made recently is installing Docker. I've fully reinstalled Python and all the modules during testing. The issue is being caused by the socket module, when http attempts to start a local server. At one point it expects get the hostname of "127.0.0.1" , which raises a UnicodeDecodeError . Here's an example of the error: # [Python 3] Test against localhost IP (error) >>> socket.gethostbyaddr('127.0.0.1') UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2: invalid start byte # [Python 3] Test against localhost >>> socket.gethostbyaddr('localhost') ('DESKTOP-XXXXXX', [], ['::1']) # [Python 2] Output of the command >>> socket.gethostbyaddr('127.0.0.1') ('xn\x969q8h', ['api.genuine.autodesk.com', 'ase.autodesk.com', 'mpa.autodesk.com',...

How do I append a file extension to a variable?

I wrote a python application that converts images to PDF's using PIL. The method below takes all images in a given directory, converts them to RGB, then is supposed to save all the images as one *.pdf file. However, I'm unable to figure out how to provide the extension .pdf to the file output. Concatenating does not work, I get error: "Unknown file extension: {}.format(ext)) def multi_convert(file_path: str): for path in Path(file_path).iterdir(): path = Image.open(path) path.convert('RGB') extension = 'file.pdf' final_file = file_path + extension path.save(final_file, save_all=True, append_images=path) from Recent Questions - Stack Overflow https://ift.tt/2Vd6xuh https://ift.tt/eA8V8J

I was testing argv import in python and there is an error

I was reading "Learn Python 3 the Hard Way" and was testing the 'from sys import argv' there is an error occuring here is the sample code of the book: from sys import argv first, second, third = argv print("The scipt is called:", script) print("Your first variable is:", first) print("Your second variable is:,", second) print("Your third variable is:", third) An I got this error: Traceback (most recent call last): File "d:/MyCodes/PythonCodes/jon.py", line 2, in first, second, third = argv ValueError: not enough values to unpack (expected 3, got 1) from Recent Questions - Stack Overflow https://ift.tt/3lfAaFJ https://ift.tt/eA8V8J

Multiply i-th 2-d matrix in numpy 3d array with i-th column in 2d array

Suppose that I have a 3d array A and a 2d array B. A has dimension (s,m,m) while B has dimension (m,s). I want to write code for a 2d array C with dimension (m,s) such that C[:,i] = A[i,:,:] @ B[:,i]. Is there a way to do this elegantly without using a for loop in numpy? One solution I thought of was to reshape B into a 3d array with dimension (m,s,1), multiply A and B via A@B, then reshape the resulting 3d array into a 2d array. This sounds a bit tedious and was wondering if tensordot or einsum can be applied here. Suggestions appreciated. Thanks! from Recent Questions - Stack Overflow https://ift.tt/37i6enx https://ift.tt/eA8V8J

Swift addTarget does not get removed?

The target of nextTrackCommand is called multiple times when I navigate back from a screen and enter the screen again even tho i remove the target in viewWillDisappear . What did I do wrong? override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.beginReceivingRemoteControlEvents() MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in print("go to next track") return .success } } override func viewWillDisappear(_ animated: Bool) { MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(self) } from Recent Questions - Stack Overflow https://ift.tt/39s6WRQ https://ift.tt/eA8V8J

Arrange a file/output in numerical order, based on the first digit

I have developed a program that produces an average value for measurements on a unit circle. The text files I use, that contains the data of the measurements, can consist of several batches (by that I mean several different measurement occasions) that have two measurements in each. The batch number is always the first one in each line, for example the text file can look like this: (1), x, y, 10 (1), x, y, 5 (3), x, y, 70 (3), x, y, 10 (2), x, y, 5 (2), x, y, 70 And the number within () is the number of the batch. And when python gives me these average values it gives them in the order that they are written in the text file. In this case, it would show in the order (1), (3) and (2) but I want python to give me these in numerical order instead. I guess I can somehow code so that when python opens the file it reads it in numerical order after the first digit in each line? But how can i enter this? My current code is: def collect_data(filename): data = [] # Or data = {} #definie...

Why isn't my ... running?

I am trying to create a div where if I click it, it will show an inner div and upon clicking it again it will be hidden. So I added the function and the a href around the div and it doesn't run at all just shows javascript:void(0) upon click at bottom-left corner. <a onclick="openOverviewDiv(this)" href="javascript:void(0);"> if I remove the " at the end of href it will run. It a syntax error(noticed cause i left the " out on accident when i ran on local server) and then I added the " back and it stop running. <a onclick="openOverviewDiv(this)" href="javascript:void(0);> I've tried in the snippet and the same thing occurred. How do I fix this? Update -- To Clarify: I am trying pass this.anchorElement upon clicking the anchor tag as shown above into the function openOverviewDiv(this). onclick="openOverviewDiv(this)" in which it then use jQuery to make the hidden children element of the anchor tag, ...

How do I make PATCH request to work when working with internal API?( Express,React,Node.js)

I am trying to set up the backend API using Express. The DELETE,POSTS,GET request all work except for PATCH. I was getting errors before which I have resolved but now I am stumped because there are no errors and I am not sure what to correct at this point. The request status is 200 instead it GETs the object being edited in its original form. PATCH request in Insomnia On the server side the code looks like const express=require('express'); const router=express.Router(); const fs=require('fs'); // file system module const { Server } = require('http'); const path=require('path'); const { v4: uuidv4 }=require('uuid'); const dataWarehouses=path.join(__dirname, '../data/warehouses.json'); function listWarehouses(){ const data=fs.readFileSync(dataWarehouses); return JSON.parse(data); } *function patchWarehouse(id,body)*{ const listWarehouse = listWarehouses(); const item = NewWarehousesList(body); const change = lis...

How to use dispatch_uid to avoid duplication Signals correctly

Helloo, I am trying to apply using a dispatch_uid="my_unique_identifier" in order to avoid duplicate signals sent in my project. I have searched for several similar answers and read the following documentation but I am not sure what I am missing: https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals In my project there are posts that are written by Author, each post has a like button which when clicked by a user notification is created and sent to the author. Until here everything is fine except that 2 notifications are sent instead of 1. I have tried the following but it did not have any effect and I am still receiving 2 notifications So here it is: Here is the Like model.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def user_liked_post(sende...

machine learning even or odd, with python (scikit-learn)

I'm trying to modify the scikit learn Recognizing hand-written digits so whereafter it's predicted what the image is, to then see if the digit is even or odd. In line 30-38 I separate the predicted into its even and odd components, I do the same for y_test. But my problem, it's the coder who is filtering to what is even and odd, I'm trying to make the machine lifter to see if the number is even or odd. I might be going about this the wrong way, maybe I am thinking it about it correctly, but not sure. After that I want to create a confusion matrix like I have below line 38. import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from sklearn import datasets, svm, metrics from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import pandas as pd import numpy as np digits = datasets.load_digits() # from skleanr tutorial page n_samples = len(digits.images) imshape = digits.images[0].shape # to remember w...

How to return interface from generic class implementing the interface?

I want to make a method that accepts any class (T) that implements any interface (I), do something with the class and return the interface (I) that it implements. Here's what I've tried: class MyLibrary { public static <I, T extends I> I registerImplementation(Class<T> classImpl) { I interfaceImpl = (I) classImpl.newInstance(); return interfaceImpl; } } I'm then creating an interface and a class which implements that interface: interface UserInterface { void doSomethingDefined(); } class UserClass_v1_10_R2 implements UserInterface { @Override public void doSomethingDefined() { System.out.println("What this does is well-defined"); } public void doVersionSpecificStuff() { System.out.println("This is not in the interface, so don't really depend on this"); } } However, when I'm calling the method referencing UserClass , it returns the same class type (T) instead o...

GitHub Repositories (How to Run)

I have read the following answer here about how to run a specific file . However, let's say I want to run every single aspect of code in the entire repository here that uses MathJax without downloading it. How would one figure that out and do that? Is it one JavaScript source code that you script? If so, how do you figure out the URL that you run? from Recent Questions - Stack Overflow https://ift.tt/3o3yT6D https://ift.tt/eA8V8J

It says subquery returns more than 1 row but I'm not sure why?

I've joined around 4 tables in my database and I am trying to get a shortlist of candidates who meet these requirements. It won't display another person who meets these requirements. It for some reason works when there is one candidate that meets them. SELECT job_seeker.seeker_fn ,job_seeker.seeker_ln ,COUNT(DISTINCT job_seeker.position_title) AS 'Required Skills' ,COUNT(DISTINCT quali_name) AS 'Required Qualifications' FROM job_seeker INNER JOIN job_seeker_profile ON job_seeker.seeker_ID = job_seeker_profile.seeker_ID INNER JOIN qualifications ON job_seeker_profile.qualification_ID = qualifications.qualification_ID INNER JOIN skill_types ON job_seeker_profile.skill_type_ID = skill_types.skill_type_ID INNER JOIN skill_areas ON skill_areas.area_ID = skill_areas.area_ID INNER JOIN job_pos ON qualifications.qualification_ID = job_pos.qualification_ID WHERE ( SELECT job_pos.qualification_ID FROM job_pos WHERE job_pos.qualificatio...

Improve query performance in large collection with large documents using indexes or in any other possible way

Image
I am using PyMongo with Flask and I would like to know how to optimize a query, as I am filtering within a large collection (8793 documents) with large documents. This is one of the document structures of the collections: As you can see, it has 4 properties (simulationID, simulationPartID, timePass and status, which stores many arrays). This collection has a size of 824.4MB. The average size of the documents is 96.0KB. Basically, I’m trying to find the documents that have simulationPartID 7 (1256 documents) and filter on them the array index equal to the nodeID value (which I receive as a parameter) within the status property, and take the fourth or fifth element of this array (depending on the case parameter), in addition to append the timePass. def node_history(nodeID, case): coordinates = [] node_data = db['node_data'] db.node_data.create_index([('simulationPartID', 1), ('simulationID', 1)]) if case == 'Temperature': ...

How to build and link Boost.Serialization on MacOS

I'm building a client-server application in C++ using Boost, a colleague of mine is coding the server in Ubuntu and he's using Boost.Serialization but I'm unable to run it because it doesn't find that library, besides I also need the library for the client. To build and link it to the project he's only created a CMAKE file like this: cmake_minimum_required(VERSION 3.16) project(RemoteBackup_Server) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "-pthread" ) add_executable(RemoteBackup_Server User.cpp main.cpp server.cpp server.h connection_handler.cpp connection_handler.h) find_package(Boost REQUIRED COMPONENTS serialization filesystem) include_directories(${Boost_INCLUDE_DIRS}) target_link_libraries(RemoteBackup_Server ${Boost_LIBRARIES}) Which compiles and links the library with no efforts. I'm using MacOS, I've installed Boost using Homebrew and I've tried to follow the guide in the Boost official site: https://www.boost.org/doc/libs/1...

create-react-app is not working since version 4.0.1

I tried installing using npm i create-react-app and even npx create-react-app new-app . I even tried npm init react-app new-app . I'm getting this error message: You are running create-react-app 4.0.0, which is behind the latest release (4.0.1). We no longer support global installation of Create React App. How can I fix this? from Recent Questions - Stack Overflow https://ift.tt/3nPm93u https://ift.tt/eA8V8J

do_sys_open kprobe is always returning the same filename

I wrote a module which registers kprobe on do_sys_open and i am trying to print the filename in the pre_handler #include <linux/kernel.h> #include <linux/module.h> #include <linux/kprobes.h> MODULE_LICENSE("GPL"); static struct kprobe kp; static char *name = "do_sys_open"; module_param(name, charp, 0); static int pre_handler(struct kprobe *p, struct pt_regs *regs) { char *filename = (char *)regs->si; char user_filename[256] = {0}; long copied = strncpy_from_user(user_filename, filename, sizeof(user_filename)); pr_info("eax: %08lx ebx: %08lx ecx: %08lx edx: %08lx\n", regs->ax, regs->bx, regs->cx, regs->dx); pr_info("esi: %08lx edi: %08lx ebp: %08lx esp: %08lx\n", regs->si, regs->di, regs->bp, regs->sp); if (copied > 0) pr_info("%s filename:%s\n",__func__, user_filename); return 0; } static int...

Sql query / VBA - multiple Select / where conditions problem

I'm sorry if this has been answered already, but I couldn't find the right solution for my problem. I have an excel file with user form where users can insert exchange rates and diferent parameters for financial report. I've set up a DB file and I want to select rows based on the values in BV column (book value) and it should be higher than 100.000EUR The problem is that I have 3 other currencies besides EUR and I need to calculate EUR amount based on exchange rate. I've already made exchange rate field in my user form (BVAL is EUR default, and I also have BVGBP, BVPLN and BVRSD, which are 100.000EUR divided with each exchange rate) This works fine: SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency = 'EUR')";" But when I try to combine multiple results,syntax is not working, I've tried a lot of other solutions I've found online, but I cannot seem to get it working. SqlQuery = " SELECT * ...

Vue single file class with member variable - variable is undefined

I have this: export default class EventForm extends Vue { @Prop() eventId?: number | null; private eventAttendees: PersonForMeeting[] = [] addAttendee(person: PersonForMeeting) { this.eventAttendees.push(person); } getPeopleFromStore().forEach( (pfm: PersonForMeeting) => { if( (pfm.type === "contact" && attendee.contact === pfm.id) || (pfm.type === "user" && attendee.user === pfm.id) ) { console.log("Adding", JSON.stringify(pfm)) console.log("THIS", this.eventAttendees) /// <- WHY IS THIS UNDEFINED???? this.addAttendee(pfm) } }) } I get an undefined value at the line noted - why? from Recent Questions - Stack Overflow https://ift.tt/2JnUozP https://ift.tt/eA8V8J

How do I get rid of SNI.dll when publishing as a "single file" in Visual Studio 2019?

I'm trying to publish a very simple C# .Net 5.0 WinForms application (single file output) as a test case for porting from the .Net Framework v4.6.1 (what it was previously) while using Visual Studio 2019 v16.8.2. The Publish options are as follows: Configuration: Release | Any CPU Target Framework: net5.0-windows Deployment Mode: Framework-dependent Target-Runtime: win-x64 Produce Single File: Enabled Enable ReadyToRun Compilation: Disabled Although the build works fine and merges the two source assemblies into a single output executable, it also includes SNI.dll in the output directory. The application will not start without this DLL in the same folder as the executable so my question is: How do I remove the dependency on SNI.dll so it does not get included with the published executable and is not required to run? Any help with this would be most appreciated. Cheers from Recent Questions - Stack Overflow https://ift.tt/3fIQCgT https://ift.tt/eA8V8J

Python.h: No such file or directory, when implementing python into c++, using CLion

I have used "apt-cyg install python3-devel" on my Cygwin terminal. I have included directories in CMake... include_directories(C:/Users/{my_user_name}/anaconda3/include) and importantly in my main.cpp #include <Python.h> and have tried "Python.h", and "fullpath/Python.h". I get back the error "fatal error: Python.h: No such file or directory". Thanks for any help. from Recent Questions - Stack Overflow https://ift.tt/2V9VVw7 https://ift.tt/eA8V8J

UE4 Accessing TMap crashes engine after running without problems for a while

I am having a crash that I have no idea how to trace. I've created an InputManager from GameInstanceSubcomponent and there created a TMap with enums as key and value. Input is being processed over time, so the map is accessed every frame. After running for some time, the game would crash with the following: See image These lines are as follows: 59. m_InputActionScale[m_InputActionTypes[InputActionType]] += Scale; 114. if (!m_InputActionsConsumed[InputActionType] && inputContext->Consume(InputActionType, m_InputActions[InputActionType], GetWorld()->DeltaTimeSeconds)) Any help is welcome! from Recent Questions - Stack Overflow https://ift.tt/39jsa4o https://ift.tt/eA8V8J

How to access data on server side from AJAX post request

I have tried reading a lot of posts on this but none have really helped me. I don't get how to access the data I am sending from a post request. For context, I have a .ejs html file where I am making an asynchronous post request to the server. This is the code for that: $("#commentButton" + thisPostId).click(function () { $.ajax({ type: "POST", url: "/comment", data: { comment: $("#commentInput" + thisPostId).val(), postId: $("#postIdInput" + thisPostId).val() }, success: function (data) { if (data.success) { let asyncComment = "<p>whatsupbro</p>"; $("#li" + thisPostId).append(asyncComment); ...

Change discord bot nickname (discord.py)

I have a simple issue that I'm yet to figure out, how can I change my bot's own nickname, because I want to display information instead of its nickname continuously. tried this : await bot.user.edit(username=price) but this actually changes the username which is not allowed to be done multiple times. async def status_update(): while True: price = str(get_BTC_price(ws)) await bot.user.edit(username=price) await asyncio.sleep (2) @bot.event async def on_ready(): bot.loop.create_task(status_update()) Thanks from Recent Questions - Stack Overflow https://ift.tt/2J5Wi8N https://ift.tt/eA8V8J

Unexpected behavior when appending to a Dict[str, list] - values are appended to all lists [duplicate]

I am iterating through a list and trying to appended values to a Dict[str, list] called plot . I look up the str -type key ( real_key ) to the appropriate list in plot and then I append a value ( value ) to that list. some = x['string'] for od in some: conversion_key = od.get("@alias") real_key = field_conversion[conversion_key] value = od.get("#text") print(f"\nconversion_key: {conversion_key}\nreal_key: {real_key}\nvalue: {value}") # unexpected behavior from line below plot[real_key].append(value) pprint(plot) As you can see, each value gets appended to all the lists in the dict, not just the list that is accessed by real_key . Why does this happen? conversion_key: TemplateResRef real_key: TemplateResRef value: cod_bks_lite_tombs_1 {'PlotFlagEndsPlot': ['cod_bks_lite_tombs_1'], 'PlotFlagJournal': ['cod_bks_lite_tombs_1'], 'PlotFlagMultiReward': ['cod_bks_lite_tombs_1...

Best way to perform large amount of Pandas Joins

I am trying to use two data frames for a simple lookup using Pandas. I have a main master data frame (left) and a lookup data frame (right). I want to left join them on the matching integer code and return the item title from the item_df . I see a slight solution with a key value pair idea but it seems cumbersome. My idea is to merge the data frames together using col3 and name as key columns and keep the value from the right frame that I want which will be title . Thus I decide to drop the key column that I joined on so all I have left is the value . Now lets say I want to do this several times with my own manual naming conventions. For this I use rename to rename the value that I merged in. Now I would repeat this merge operation and rename my next join to something like second_title (see example below). Is there a less cumbersome way to perform this repeated operation without constantly dropping the extra columns that are merged in and renaming the new column between each...