Posts

Showing posts from June, 2022

GORM .Save don't save "has one" relation to the database

I have struct: type Book struct { gorm.Model Title string `json:"title"` Author string `json:"author"` Description string `json:"description"` Category string `json:"Category"` Publisher string `json:"publisher"` AuthorsCard AuthorsCard `gorm:"foreignKey:BookID" json:"authorscard"` } type AuthorsCard struct { //gorm.Model // I purposely Don't want to use gorm.model ID uint `gorm:"primarykey"` BookID uint Name string `json:"name"` Age int `json:"age"` YearOfBirth int `json:"year"` Biography string `json:"biography"` } And I'm trying to make update function: // controller.go func UpdateBook(ctx *gin.Context) { enableCors(&ctx.Writer) id := ctx.Param("ID") var updateBook = &models.Book{} ...

chokidar works in VS code debugger, but not able to load when Electron app is built

I am using chokidar to monitor file changes in directory. The following works if the app is started in VS code debugger. const chokidar = require('chokidar'); But, after building the app, and start the app by clicking the app icon, it has following error in a popup dialog Uncaught Exception: Error: Cannot find module 'chokidar' This is Electron and Electron-builder version: electron-builder version=22.13.1 os=20.2.0 writing effective config file=dist/builder-effective-config.yaml packaging platform=darwin arch=x64 electron=11.5.0 appOutDir=dist/mac How to solve it?

AWS Pinpoint SDK - How to import a segment and create campaign

I am working on a pinpoint integration that will hopefully use the java sdk to create a segment and launch a campaign in one shot. I am having trouble determining how to do this. If I use ImportJobRequest to import a CSV/JSON file from S3 and use the segment id when creating the campaign then I get an error Segment specified in Segmented is not found I have verified that the segment is created with the id I am attempting to use. This may be the same as this unanswered question: Python: Passing a variable to another function Is there a way to import a segment and create a campaign at once is a single lambda function? Polling for the imported segment in a separate function seems like bad design.

How to do a SUMX on a GroupBy table in Webi?

I have a DAX code in PowerBI that displays how many "check-ups" have been done in a particular location. I am currently trying to transfer this over to SAP Web Intelligence Rich Client. 1.2_FrequenciedDay- = var minDate=MIN(Datekey[ModifiedDate]) var maxDate=MAX(Datekey[ModifiedDate]) var summarizedTable=SUMMARIZE('x','x'[Datekey],"count",distinctcount('x'[DivisionKey])) var Cumulativesum=SUMX(FILTER(summarizedTable,[Datekey]>=minDate&&[Datekey]<=maxDate),[count]) return Cumulativesum Is there a SUMX and SUMMARIZE translations for Web Intelligence?

Achieve Hexdump in python

How can I achieve the following in Python 3? cat file | sigtool –hex-dump | head -c 2048 I’m attempting to read a .ndb database which I have created in order to check for malicious PHP files, however I need to be able to create hex signatures of files in python in order to check against this database.

How can I fix the Content Security Policy error to make 3rd party API requests in my Stripe App UI extension?

Image
When making a http request to "https://example.com/api" - the console throws an error Refused to connect to...because it violates the following Content Security Policy directive: "connect-src http://localhost:*... How can I resolve this error?

Unit test Apache Camel specific routes by filtering (Model#setRouteFilter)

How to include only certain routes in my unit test. For example, how do I enable only my-translation-route . public class TestRoute extends RouteBuilder { @Override public void configure() { from("ftp://my-ftp-server:21/messages") .routeId("my-inbound-route") .to("direct:my-translation-route"); from("direct:my-translation-route") .routeId("my-translation-route") .bean(MyBean.class) .to("direct:my-outbound-route"); from ("direct:my-outbound-route") .routeId("my-translation-route") .to("http://my-http-server:8080/messages"); } } I tried with Model#filterRoutes but this did not work. All routes were loaded. class TestRouteTest extends CamelTestSupport { @Override protected RoutesBuilder createRouteBuilder() { return new TestRoute(); ...

Can use public ip adress to connect to webserver but only when connected to the same internet

Introduction I have a simple node.js WebServer which just contains a simple express example. It hosts at my private ip adress 192.168.1.155 at port 80. I can use that adress to connect to the server and everything works fine. Then I went to my router to add port forwarding and I can now use my public ip adress to connect to the server (too). Problem But the connection with the public ip adress only works when I am connected to the same internet. I tried to connect with the public ip with my iPhone with mobile data instead of the same wifi and it didn't work. Solution? Has anyone discovered the same problem and is there a solution to it? Edit... Thanks to @robertklep who mentioned about CGN or CGNAT (Carrier Grade Network Address Translation) I visited https://www.remoterig.com/wp/?page_id=3494 and I found out this: "CGN makes communication in the other direction, from outside Internet and in to LAN impossible"

variable background colour for gnuplot

I'd like to colour the background of my timeseries (a few 10^5 s, so several days) plot depending on the time of day. White for the day regions, a, say, dark blue for the night, and perhaps some transition inbetween. Continously changing colour would be nice, but a more "blocky" design is also fine. The dataset has a resolution of ten seconds (and many columns), so the plot is already a bit slow. I'll figure out the math myself (length of day changes over the year), for the moment a sinus (or 0/1 rectangle) with frequency of 1 d is fine, but how do I plot it so the ordinate becomes a background colour instead of vertical screen coordinate? And, of course there is a hitch, I want everything, the actual graph and background colour, in one plot command so I can still zoom. This set multi gamma = 2.2; color(gray) = gray**(1./gamma) set palette model RGB functions color(gray), color(gray), color(gray) set pm3d map; splot [0:20] sin(x); unset pm3d plot .... looks supe...

crabbly / Print.js Print not working, Print Preview not showing

Image
We are using 1.6 of crabbly/Print.js https://github.com/crabbly?tab=repositories https://printjs.crabbly.com/ It works just fine until this setting in edge is turned on. This is our code. const bytes = convertBase64ToUint8Array(json.contentBase64) const blob = new Blob([bytes], { type: json.contentType }); const url = window.URL.createObjectURL(blob); showMessage.success('Sucessfully downloaded the report as pdf', url) print({ printable: url, type: 'pdf', showModal: true }) This is the error we are getting. I cannot reproduce this in development.

How to Fix CORS error with ngrok in SpringBoot

Image
Introduction Tried to access spring boot server using ngrok url but getting CORS error. the allow origin has already the url from which i am trying to access the apis. but still no good. Any suggestion is appreciated. Spring Boot Project - POM <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>crostest003</arti...

How to create nested training and testing sets?

I'm working with the ChickWeight data set in R. I'm looking to create multiple models, each trained for an individual chick. As such, I am nesting the data so that a dataframe is created for each individual chick and stored within the list column. Here is the start: library(tidyverse) library(datasets) data("ChickWeight") ChickWeightNest <- ChickWeight %>% group_by(Chick) %>% nest() From here, training a linear regression model on all dataframes simultaneously is very easy by simply building the model as a function then mutating a new column and mapping. However, building a more sophisticated model (e.g. xgboost) requires first splitting the data into testing and training sets. How can I split my all nested data frames at once to create training and testing sets so that I can train multiple models simultaneously? As a side note, info on training/tuning multiple models seems to be relatively sparse in my research, any related resources or past stac...

Can't load components using VueJS

I'm trying to use dynamic import but nothing is happening this is my code : <component :is="state.name"/> <button @click="onClick">Click me !</button> setup() { const state = reactive({ name: computed(() => isShow.value == true ? import('./b.vue'): import('./a.vue')) }); const isShow = ref(false); const onClick = () => { console.log(5) isShow.value = true; } return { state, onClick } }, and here is my b & a components b <script> export default { data(){}, created(){ alert('lol') } } </script> Please I need a help to load my components programatically

PHP str_ireplace same word with accent or not

Hope this is a better... I set "mysqli_set_charset($conn,"utf8");" before doing a standard query SELECT-FROM-WHERE. This query performs an accent insentive compare. str_ireplace(search, replace, text) search does an accent sensitive compare. I would need search to do an accents insentive compare. I want to highlight the word "Français". I replace "Français" by <mark>Français</mark> but at the same time I want to replace "Francais" by <mark>Francais</mark> older post: I use a simple way to highlight some text: $markReplace = "<mark>" . $wordToSearch . "</mark>"; $fullText = str_ireplace($wordToSearch, $markReplace, $fullText); echo $fullText; It works fine, the problem is that sometimes the same $wordToSearch can have a accent or not. For example "huître-huitre", "Francais-Français", "echo-écho" because of typo errors. And contrary to MySql, ...

Jackson-databind deserializes JSON with missing property as "null" instead of default value

When deserializing a JSON string, missing properties are being set as "null" when they shouldn't be. Below is a POJO class: @Builder @Getter @Setter @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor @ToString @EqualsAndHashCode static class MyPojo { @JsonProperty(value = "OptionalProp", required = false, defaultValue = "") @Builder.Default @Nullable @JsonSetter(value = "", nulls = Nulls.AS_EMPTY) private String optionalProp = ""; @JsonProperty(value = "RequiredProp", required = false, defaultValue = "") @Builder.Default @Nullable @JsonSetter(value = "", nulls = Nulls.AS_EMPTY) private String requiredProp = ""; } JSON String to deserialize: { "RequiredProp" : "test" } Here is the deserialization: private ...

Why doesn't OnPlayerEnteredRoom() method work?

i make room in unity with photon pun. When i join the room, OnPlayerEnteredRoom() doesn't get call. MonoBehaviourPunCallbacks and IInRoomCalbacks already inherited. Code: using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using Photon.Pun; using Photon.Realtime; public class RoomServer : MonoBehaviourPunCallbacks, IInRoomCallbacks { public TMP_Text p1, p2, p3, p4; public Sprite p1i, p2i, p3i, p4i; public Sprite p1is, p2is, p3is, p4is; public GameObject playerPrefab; // Start is called before the first frame update void Start() { PhotonNetwork.AutomaticallySyncScene = true; Debug.Log("ao"); } // Update is called once per frame void Update() { } public void OnPlayerEnteredRoom() { PhotonNetwork.Instantiate(playerPrefab.name, new Vector3(0,0,0), Quaternion.identity); Debug.Log("Player has joined!"); } public void OnPlayerLeftRoom(Player newPlayer) { } public void OnRoomProperties...

How to set parameters before simuliting to make it more consist to the real road net? (in SUMO)

In order to make the simulation more consist to the real road, we should reset some traffic parameters in SUMO,such as max vehical speed, Max acceleration, minGAP e.t. Which parameters need to be set in SUMO? And how?

How to display data order by time not in the same bloc with laravel?

I'm working on reactJs and Laravel chat. Actually the problem is that when I try to display data for specifc two users (sender and reciever) I got them bloc by bloc not message by message . I got a bloc of messages for the sender and then a bloc of messages for the reciever this is the code : function getChats($id){ $c= chat::all()->where('id', $id); //$types= chat::all()->where('id', $id); foreach ($c as $q) { $q=chat::where('senderId', $q->userId) ->where('userId', $q->senderId)->get(); foreach ($q as $a) { $a=chat::where('userId', $a->senderId) ->where('senderId', $a->userId)->get(); $finalResult = $a->merge($q); // return ['chat' => $s]; } } return ['chat' => $finalResult]; } I merge the two queries to get the mssges of the sender (s...

selenium / seleniumwire unknown error: cannot determine loading status from unknown error: unexpected command response

Here's the error: selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status from unknown error: unexpected command response (Session info: chrome=103.0.5060.53) I'm using proper webdriver and chrome version: Here is the script, its job is too open a webpage from the normal suer data directory and provide a response. from seleniumwire import webdriver # Import from seleniumwire chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("user-data-dir=C:\\selenium") driver = webdriver.Chrome(chrome_options=chrome_options) driver.get('https://katalon.com/ ') for request in driver.requests: if request.response: print( request.response.status_code, )

Invalid ARN error while creating S3 Bucket Policy using Policy generator

Im trying to create Amazon S3 Bucket Policy using the Policy Generator Though this is very basic, but not sure why Im getting "Resource field is not valid. You must enter a valid ARN." for any ARN, eg for this "arn:aws:s3:::s3-demo-bucket-2022" I have tried with multiple s3 bucket, aws accounts, all giving same problem. Any help/suggestion?

Python virtual environment does not have a scripts folder and cannot be activate

I am new at programming and I want to work with Python and meanwhile with the Django Framework. For installing a venv I use python3 -m venv ./venv/drf and insert this in a terminal in VS code. I found this on my research about my problem. But when I installed the venv there is not a script folder in the venv folder. For activating my venv I tried source .venv/drf/bin/activate but this is neither working. I am working on a mac and I installed Python previously. I even installed Django on VS code. What can I do to implement the scripts folder and activate my venv?

pandas vectorized lookup without depreciated loockup()

My problem concerns lookup() , which is to be depreciated. So I'm looking for an alternative. Documentation suggests using loc() (which does not seem to work with a vectorized approach) or melt() (which seems quite convoluted). Furthermore, the documentation suggests factorize() which (I think) does not work for my setup. Here is the problem: I have a 2-column DataFrame with x,y-values. k = 20 y = random.choices(range(1,4),k=k) x = random.choices(range(1,7),k=k) tuples = list(zip(x,y)) df = pd.DataFrame(tuples, columns=["x", "y"]) df And I have several DataFrames in crosstab-format of df . For example one called Cij : Concordance table (Cij): x 1 2 3 4 5 6 RTotal y 1 16 15 13 NaN 5 NaN 108 2 NaN 12 NaN 15 NaN NaN 87 3 NaN NaN 6 NaN 13 14 121 I now want to perform a vectorized lookup in Cij from xy-pairs in df to generate a new col...

How to batch the app events with max of 1000 events per second when using Splunk HTTP Event Collector (HEC)

I need to send the batched events to Splunk HTTP Event Collector, say 1000 events per second. Below is the example of 5 log events that are sent to Splunk HEC - % curl "https://splunk-example.com:8088/services/collector/raw?channel=093DCD-BC98-8UET-8AFE-8413C3825C4C&sourcetype=test_type&index=test_index" -H "Authorization: Splunk ******-****-****-****-*********" -d '<log line 1> <log line 2> <log line 3> <log line 4> Output: {"text":"Success","code":0}% So how do I configure to send the application logs as 1000 events/seconds to Splunk HEC?

How to compare float in logstash?

It's the pipeline config for test: input { file { path => "/tmp/test1.log" } } filter { json { source => "message" } } output { if [a] == 1.1 { stdout {} } } I echo some test log to logfile: echo '{"a": 1.1,"b": "test"}' >> /tmp/test1.log But there isn't any output in console, and I try use the condition if [a] == "1.1" either not work. Somebody know how to compare float? thanks!

Iterate through fields using array Django

Image
I have this model: class Some_model(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: # create a function to upload a model object given a json object def upload_object_values(model, json_values, keys=None): if json_values: # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object has keys to check if keys: # check if exists using the keys when called like this: upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2']) It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter). Some_model.objects.get_or_create(field_2='val_2') UPDATE...

Django 4.x - Conditional QuerySet for Pagination and a many-to-many relationship

Disclaimer: I have searched and a question tackling this particular challenge could not be found at the time of posting. The Requirement For a Class Based View I need to implement Pagination for a QuerySet derived through a many to many relationship. Here's the requirement with a more concrete description: Many Library Records can belong to many Collections Web pages are required for most (but not necessarily all) Collections, and so I need to build views/templates/urls based on what the client identifies as required Each Collection Page displaying the relevant Library Records requires Pagination, as there may be 100's of records to display. The First Approach And so with this requirement in mind I approached this as I normally would when building a CBV with Pagination. However, this approach did not allow me to meet the requirement. What I quickly discovered was that the Pagination method in the CBV was building the object based on the declared model, but the many to...

Pass a value in document.write

I have a <script> that creates a tagId value. Currently, it will display as document.write(tagId); I want to place tagId in a <form> as: <input type="text" name="" value="tagId"> Example, something like: document.write(< input type="text" name="" value="tagId" >); How can I place the tagID value to insert in the text form?

Create a view on small screens when clicking on a link

Currently, I have a table and page built using Bootstrap. Here is the code: <div class="row my-2"> <div class="col-12 col-md-8"> <div class="d-md-flex justify-content-between"> <div> <h1 class="text-uppercase">Clients</h1> </div> <div> <input class="form-control-sm bg-dark text-light border-dark me-4" type="text" id="criteria" placeholder="Rechercher" onkeyup="showCustomers();"> </div> </div> </div> <div class="row"> <div class="col-12 col-md-8"> <table class="table table-dark table-borderless table-lines"> <thead> <tr> <th scope="col">Login</th> <th scope="col">Num. Client</th> <th scope="col">Date inscri...

How to improve a variable lens blur in Python OpenCV?

Image
I want to emulate the blur of a cheap camera lens (like Holga ). It's not the same as standard Gaussian blur with constant kernel size . So I'm not sure that I have to use GaussianBlur or 2D filter. I wrote the code and it works in general. Input: Result: But I feel that it can be done better and faster. I've found a similar question but it still has no answer. How to implement different variable kernel shapes and avoid a black border? import cv2 import numpy as np import requests url = r'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png' resp = requests.get(url, stream=True).raw img = np.asarray(bytearray(resp.read()), dtype="uint8") img = cv2.imdecode(img, cv2.IMREAD_COLOR) img_lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(img_lab) # make blur map height, width = l.shape[:2] center = np.array([height/2, width/2]) diag = ((height / 2) ** 2 + (width / 2) ** 2) ** 0.5 blur_map = np.linalg.norm( np....

Python XML Parse errors with Invalid Token

I am moving code from Python 2.7 to Python 3.10. One section of the code creates XML which is 'prettyfied' and written to a file. But parsing in Python 3.x is throwing an error. In one case the problem seems to be with an encoded en-dash character. <?xml version='1.0' encoding='utf8'?> <properties> <entry key="name">AB&amp;R - RFA #3 \xe2\x80\x93 Alignment</entry> </properties> The parsing is done as follows: xml_parsed = xml.dom.minidom.parseString(xml_string) return xml_parsed.toprettyxml(" ", "\n") The error thrown is: not well-formed (invalid token): line 2 I don't think this problem happened with Python 2.7. There is a nice description about en-dash here (although I think my problem is not limited to en-dash). What can be done to fix this?

Not able to run Android app || 'Gradle-aware make' is missing in app configuaration

Image
I have cloned a private repo that I can't share. that project is built successfully and I can create debug/release apk as well. But I am not able to run it from the run button in android studio. When I click on the run button, It is not launching in mobile/emulator. Immediately, It says 'launch successfully' Even if it is not starting Gradle run. So I compared many settings with a sample app that is running as expected, So I found one difference which is in the app configuration(select the app [near run icon] -> Edit configuration). That 'Gradle-aware Make' is not there in the 'Before launch' section in the 'General' tab of app configuration. check the screenshot below: In the working sample, It is present and we can remove/add it again and again normally. Check the screenshot below: So How to generate it, Can Someone please help me?

React Native: Problem with dependencies and archiving my project

Image
I have returned to a project which I haven't worked on in a little while. I added a delete account feature and planned to release it to the apple store that day. I ran npm install --legacy-peer-deps && cd ios && pod install . This all worked fine (my packages are a little out of date since I haven't worked in this project for a while so I had to user legacy-peer-deps instead). Next step, I went to XCode and tried to archive my project as usual but got a build failed with the error being Undefined symbol: _swift_stdlib_isStackAllocationSafe - after some research I found a solution on this post: Symbol(s) not found for architecture arm64 - XCode There was a really helpful approved answer. I added the suggested code to my podfile and tried to run npm install react-native-purchases@latest as suggested. BUT, I am presented with the following error: At this point I'm thinking hmmm conflicting dependency let me try to install with npm install react-native-f...

Kafka Schema Registry - block messages that aren't accepted in the schema registry in kafka

Image
I have a schema in kafka and I need that every time I post a post in this topic, the schema that I registered checks if it is in the same pattern that is being sent. My schema is: Curl post: curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" --data '{"schema": "{\"type\":\"record\",\"name\":\"Operacao\",\"namespace\":\"data.brado.operacao\",\"fields\":[{\"name\":\"id_operacao\",\"type\":\"string\"},{\"name\":\"tipo_container\",\"type\":\"string\"}, {\"name\":\"descricao_operacao\",\"type\":\"string\"},{\"name\":\"entrega\",\"type\":\"string\"},{\"name\":\"coleta\",\"type\":\"string\"},{\"name\":\"descricao_checklist\",\"type\":\"strin...

Twitter DM API not returning all messages

Image
I’m calling the 1.1 direct messages events list endpoint as an authenticated user, I’ve send a few messages to the accompanying account from two different other twitter accounts. However I’m only getting the message_create results for the messages from one of the senders. Not both. When I’m signed in in the browser on Twitter, I do see the DM’s from both accounts. Since the number of direct messages this account has is < 20, I also do not get a next_cursor property. So there is no "next page" which contains the messages. All messages have been send within the last week, so it’s not that the 30 day limit is in play here. The (shortened) response I get back: { "events": [{ "type": "message_create", "id": "1537138057991884809", "created_timestamp": "1655317246326", "message_create": { "target": { "recipient_id...

Can I print pie charts using a for loop in Jupyter?

I need to use for loops to print multiple pie charts within a function, preferably horizontally. My assumption was, if I use a for loop to print pie charts, all the charts will be produced but the results would be shown vertically. However, only the very last figure is shown. import matplotlib.pyplot as plt for i in range(3): labels = ['part_1','part_2','part_3'] pie_portions = [5,6,7] plt.pie(pie_portions,labels=labels,autopct = '%1.1f%%') plt.title(f'figure_no : {i+1}')

importing Amplify throws error "null is not an object (evaluating 'keys.filter)" in react native app

Image
Any time I import Amplify into my React Native project's App.js file, I get the following error: TypeError: null is not an object (evaluating 'keys.filter') Here is how I'm importing it: I run the project using Expo only. If I comment the import Amplify line out, any other files which use anything related to Amplify cause the same error to occur. Initially, when I was loading this project for the first time, I had other errors to deal with like first needing to create the aws-exports.js file. I copied this over from an old project (Because this is meant to be a re-do of another project that's already set up). Once I included that file I had to update a few lines in that file because of an improper reference to Linking from expo. Once I fixed that, it throw this error I'm referencing here. Now, even if I delete the aws-exports file it will throw this error as soon as Amplify is imported into the App.js file. -- Update I've found where the error is o...

Save content of multiple div's as a PDF file by clicking HTML button

I have a button 'Generate PDF', and I want it to save some div elements as a PDF file. From what I read, I best use JavaScript, but I have zero experience with JS. I already tried third party solutions like html2pdf, pdfmyurl, jsPDF, etc., but I didn't manage to get it to work like I want it. This is the structure of the HTML file: <!DOCTYPE html> <html> <head> <title>This is my title</title> </head> <body> <!-- HEADER --> <div class="header"> <img src="../logo/logo_17.png" width="320" height="100" /> </div> <!-- MENU --> <div class="topnav" id="myTopnav"> Menu... </div> <!-- KOLOMMEN --> <div class="row"> <!-- LINKSE KOLOM --> <div class="prodtitle" id="htmlContent...

Issues with Excel Textjoin, need a work around

Image
I am trying to figure out how to setup a couple excel sheets that combs through ALOT of information. I can not display the actual excel sheet due to what's in it but I have recreated an excel that would do the same thing. I am trying to get the dates to populate automatically when the CountIF finds something... Say, Blake shows up multiple times in the data range I need it to look through, I need all the dates or at least the most recent date to populate on its own in 1 cell next to the CountIf number or in the same cell as the CountIf. The cell should display 06/22/2022, 06/29/2022 . I am using Excel 2016, I do not have a built in TEXTJOIN. @scott, Thank you for responding, I added your TEXTJOIN UDF and I am getting a #VALUE! message in the cell. I tried with a cell that would return 1 date, no date, and multiple dates. The date format in the excel I can not show is 20220623, so I am not sure if that matters or not. I got it to work on the test excel sheet I made for the scre...

PyQt5: Scaling QLabel to image size

Image
I want to scale my label, because it acts like the frame for the picture. Like you can see in the picture, the frame is just too big. I tried adjustsize() but it didnt work. Maybe its because Im using a layout? I would really appreciate your help.

Views vs Materialize Vs Materialized View in Kusto

Scenario: Data in kusto table is updated after 5 hours. Task: Call query from .net API In query , create a subquery and use that subquery to perform join on a bigger table let table1=materialize( Customer|where CustomerId=="cust-reg-aabb-cc232"|distinct CustomerId,City); CustomerPurchase |where CustomerId=="cust-reg-aabb-cc232" //perform join with table1 and other things or let table1=view(){ Customer|where CustomerId=="cust-reg-aabb-cc232"|distinct CustomerId,City}; CustomerPurchase |where CustomerId=="cust-reg-aabb-cc232" //perform join with table1 and CustomerPurchase CustomerPurchase and Customer data is being updated after every 5 hours(new rows being added). What is more optimized : create a view or use the materialize method. I went through the documentation but could not understand the different between both. Also since I am implementing an API, is it possible to use materialized view instead of table1?

The d-neighborhood of the k-mer Pattern is the collection of all k-mers that are at most Hamming distance d from Pattern

The d-neighborhood of the k-mer Pattern is the collection of all k-mers that are at most Hamming distance d from Pattern. How many 4-mers are in the 3-neighborhood of Pattern = ACGT? Note that the d-neighborhood of Pattern includes Pattern.

How to do a performance test for a mocha library?

I need to do performance testing for the below Mocha unit test. describe("simple test", async() =>{ it("first test" , async()=>{ assert.equal( 1 , 1); }) }) But I do not know which open source tool to use. Can anyone introduce me to some open source performance testing tools for the Mocha Library?

How to modify ImageFolder in pytorch to return a tensor of a different shape?

How to extend torch.datasets.ImageFolder in pytorch to return a tensor of a different shape? It currently returns: torch.Size([1, 3, 256, 256]). I want to return [1, 10, 3, 256, 256]. I have a directory with multiple images separated into folders. Each folder has up to 3000 images. I would like to modify the getitem function so that it returns bags of images, where each bag contains 10 images. Thank you!

Linux kernel module reference counter is always zero

I am implementing a kernel module that exposes some data to userspase using mmap interface. I create a file in /proc file system passing struct file_operations with pointers to needed functions: static struct file_operations module_file_ops = { .owner = THIS_MODULE, .open = module_open, .mmap = module_mmap }; proc_create(THIS_MODULE->name, 0444, NULL, &module_file_ops); Userspace application is able to open and read from the file (mmap contents) as expected. When I do lsof I see the file is opened by the userspace app. However, lsmod always gives zero as usage counter despite I set .owner to THIS_MODULE, so that I can easily remove the module with rmmod and lead the system to crash. Please advise. module.c #include <linux/fs.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> static struct proc_dir_entry *proc_file; static const struct file_operations test_file_ops = { ...

Find all JS classes used in web page [duplicate]

Image
Is there a way to find every unique class definition used in a WebPage? For example, if a web page has three unrelated JS classes Dog , Cat, and Mouse , but I do not know that these classes exist, how would I discover them? //returns all the JS classes in a document function getAllDocumentClasses(){ } This would be a function I would run in the chrome console. Context: I'm preparing some documentation on extracting data from web pages using javascript. One approach to do this is to investigate the classes used in a library, for example, to see all the instances of a Highcharts and then extract the data used in that Highcharts instances. But if we do not know which libraries a web page is using, then this is more difficult. Edit: Seems like this might not be possible with javascript. But if you go to Chrome Developer Tools and type window. , then you can browse through available classes in the window.

Declaring runtime exceptions

What is the guideline for methods declaring runtime exceptions? Let's say I call a 3rd party routine that throws SQLException . Is it permissible/standard/acceptable for that routine to be able to throw RuntimeException s without declaring that it does so? As always, I am surprised by the confusion my questions cause :-D This is probably because I am confused. In the following, the callable is a lambda that issues a commit , and this throws SQLException. callable.call throws Exception. private doThis(Callable<T> callable) throws SQLException { try { return callable.call(); } catch (SQLException e) { // do stuff throw e; } catch (Exception e) { break; // Eats any exception from call() which makes me scream internally. } } What I surmise from this is that the coder wanted doThis to throw a SQLException. However, the nature of using the Callable meant that the routine had to throw an Exception unless the coder did something....

How can I fix the Cmake link problem in macOS

I have installed the latest cmake in my MacBook.I also input "brew link cmake". But it still display : zsh: command not found: cmake How can I fix it?

Why does cin.fail() ignore periods and commas in "while" loop? What's a simple way to error check input?

Sorry it sounds stupid, but I'm just getting started in C++ programming... My input checking loop works fine if I want it to accept 'float' numbers, but outputs some weird results if it has to accept only 'int' numbers. EDIT: Tutorials I read/watched assumed that user wouldn't input things like that, which is dumb... #include <iostream> #include <limits> using namespace std; // input with check int num(int i) { int x=0; cout<<"Enter #"<<i+1<<": "; cin>>x; while(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout<<"Enter INTEGER #"<<i+1<<": "; cin>>x; } return x; } int main() { int i, min=0, max=0, n=3; int arr[3]; // save input into array for(i=0; i<n; i++) { arr[i] = num(i); } // find 'max' & 'min' max =...

How can I read the color of autoshape in python-pptx?

Image
Colorful circles are the autoshape type in python-pptx, Now I want to read the color(RGB or whatever) of them What I got in documentation is use shape.fill.solid() shape.fill.fore_color.rgb But It pops AttributeError: no .rgb property on color type '_NoneColor' Any idea to access the color of autoshape? (BTW, Best to post the color change method cause I read color for change it by HSV adjustment)

Webelement input not interactable (when choosing a specific one from list)

I'm trying to find a specific input and sendkeys to it on this website . I have no problem locating it in the browser's console with for example (//input)[4] . However, when I'm trying to find it and sendkeys in my IDE (using Java with Selenium) I got the org.openqa.selenium.ElementNotInteractableException: element not interactable * exception. I tried to do it with following methods: With simple findelement and sendkeys: WebElement ebookAddInput = driver.findElement(By.xpath("(//input)[4]")); ebookAddInput.clear(); ebookAddInput.sendKeys("4"); Using list of items to choose specific one: List<WebElement> allInputs = driver.findElements(By.xpath("//input[@name='commerce-add-to-cart-quantity-input']")); System.out.println(allInputs.size()); allInputs.get(4).sendKeys("4"); In both cases I got the mentioned error. The only way it works is through not specifying which input i want to choose and then there is no erro...

How do I put the focus on the QuickFix window after automatically opening the QuickFix list?

I have the following in my .vimrc to automatically open/close the QuickFix window after running :make : augroup quickfix autocmd! autocmd QuickFixCmdPost [^l]* cwindow autocmd QuickFixCmdPost l* lwindow augroup END It works fine, but when the autocmd opens the QuickFix window, it does not put the focus on the window. Is there any way to automatically put the focus on the QuickFix window after the autocmd opens it?

Does SML provide an efficient immutable list implementation for very large collections, or should arrays and mutation be used for this optimization?

Every time we do cons and destructuring and similar operations on lists, we create copies of the original lists. This can become a performance issue with very large collections. It's my understanding that to improve this situation, some programming languages implement lists as data structures that can be copied much more efficiently. Is there something like this in SML? Perhaps in the language definition, or as a feature that is implementation dependent? If there's no such data structure, are arrays and mutability one pattern that optimizes on large lists? As long as the state is local to the function, can the function still be considered pure? SML is multi-paradigm, but idiomatic SML is also functional-first, so both "lists with efficient copying" and "mutable arrays" approaches should make sense, depending on what the core language offers. Is there an immutable data structure that is more efficient than the normal singly linked list for very large coll...

Using numpy.where to calculate new pandas column, with multiple conditions

I have a problem with regards as to how to appropriately code this condition. I'm currently creating a new pandas column in my dataframe, new_column , which performs a subtraction on the values in column test , based on what index of the data we are at. I'm currently using this code to get it to subtract a different value every 4 times: subtraction_value = 3 subtraction_value = 6 data = pd.DataFrame({"test":[12, 4, 5, 4, 1, 3, 2, 5, 10, 9]} data['new_column'] = np.where(data.index%4, data['test']-subtraction_value, data['test']-subtraction_value_2) print (data['new_column'] [6,1,2,1,-5,0,-1,3,4,6] However, I now wish to get it performing the higher subtraction on the first two positions in the column, and then 3 subtractions with the original value, another two with the higher subtraction value, 3 small subtractions, and so forth. I thought I could do it this way, with ...

Git suddenly won't authenticate to GitHub automatically

I'm relatively new to git. I've been working on projects, pushing to and pulling from my GitHub repos. After I set everything up, all I needed to do was type git push origin main in the bash terminal and everything worked. Earlier today, I wanted to push to a remote repo on GitHub. I typed git pull origin main exactly as I have a hundred times, but suddenly I get the error "fatal: Unable to persist credentials with the 'wincredman' credential store." I've tried everything I could find. I unset my credential manager, deleted old credentials in Windows Credential Manager, tried creating a PAT. I finally managed to successfully pull/push using the PAT, but now I have to manually input my username and PAT every single time. I have no idea what happened, but I would love to be able to push/pull from remote without needing to login.

OsmDroid: User agent doesn't work with Fragments

Every example available on the internet tells us to use this line of code to get the user agent (without it the map won't load). osm.osmdroid.config.Configuration.getInstance() .load(applicationContext, this.getPreferences(Context.MODE_PRIVATE)) The problem is that applicationContext yields "Unresolved reference". Same goes for this.getPreferences() . I've tried to put that code into MainActivity (no fragments) and it works. Is there any way to replace it in this context?

How to close an element by clicking outside of it?

I'm currently trying to close an element when its style is different than "display = none". I'm having an error in the console telling me that lists. some aren't a function so I may not have understood well the "some" method. More Infos on what I want : Given that I have 3 lists (in lists), when I click outside of it or its elements I want to close all the lists) Thanks in advance const lists = document.querySelectorAll(".list"); function closeList() { document.addEventListener("click", () => { if(lists.some((list) => list.style.display != "none")) { return lists.style.display = none; } else return; }); };

Dynamic group by list data indexes

I want to group by dynamically according to more than one index in a list. Model public class MyModel { public string baseTableName { get; set; } public List<object> columns { get; set; } public List<List<object>> rows { get; set; } } I need to find the indexes of the pk columns list in this model. Then I want to group the data in the rows list by pk columns. Sample Request { "tableName": "fooTable", "columns": [ "c1", "c2", "c3" ], "rows": [ [ "1", "a", "kobe" ], [ "2", "a", "lebron" ] ] } In this sample request, columns c1 and c2 are pk. Codes // Returns indexes of pk columns. var pkColumnIndexes = GetPkIndexes(columns); var gp = requestObject.rows.GroupBy(gp =...

CSS file linking issue [closed]

Why is my CSS file not linked when the HTML file is inside a folder within the folder that contains both folders? I tried deleting the main folder address from the link and it still persists. https://imgur.com/a/BLfHYaj *The CSS file is OK and works only when the HTML file is not in a separate folder.

Loop error while converting Text to Number across all sheets with VBA

Image
I'd like your help to repeat the below code to all file sheets to convert "Column B" from text to number. I have tried next for function but it gives me error every time I run it. Screen shot from the file sample Sub convert () [B:B].Select With Selection .NumberFormat = "General" .Value = .Value End With End Sub Screenshot:

Quickbase: Query multiple table to fetch data in single API

I am looking for body format in quickbase /records/query where i can query mutiple table in single API. Right now, i have to use 4 api in quering 4 different table. Is there any way to do that in single api call?

Proper way to pre-fill a sender's signature in bulk?

I currently have a working DocuSign integration going using embedded signing. An administrator logs in, provides consent once (auth code grant, extended scope) and the app can generate sign requests in their name to different users without them needing their own DocuSign accounts. What I'm trying to build now though is for the administrator to sign as well, and preferably only once for the same document which is then sent to different users. So I'd like to make an embedded signing view for the admin to sign once, then use this same half-signed document/template to create multiple embedded signing views for different users. My client would like the DocuSign audit trail to show that the administrator signed each document, so just pre-filling it with an image won't do. I've been looking at templates, but haven't been able to find examples of or methods for including a sender signature in a template, or embedded template editing. I'm using the eSign package for C#...

Strikethrough text in a Manim Table

Here is the source code of the documentation page of Table in Manim: class TableExamples(Scene): def construct(self): t0 = Table( [["This", "is a"], ["simple", "Table in \n Manim."]]) t1 = Table( [["This", "is a"], ["simple", "Table."]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")]) t1.add_highlighted_cell((2,2), color=YELLOW) t2 = Table( [["This", "is a"], ["simple", "Table."]], row_labels=[Text("R1"), Text("R2")], col_labels=[Text("C1"), Text("C2")], top_left_entry=Star().scale(0.3), include_outer_lines=True, arrange_in_grid_config={"cell_alignment": RIGHT}) ...

Infinitiy NumberFormatException when creating BigDecimal

I have a function that formats a float value into USD currency format, but when the values are fractions of a dollar they get formatted to the last two non-zero decimals. public static String currency(float number) { NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(); currencyFormatter.setCurrency(Currency.getInstance("USD")); String[] floatParts = new BigDecimal(number).toPlainString().split("\\."); if(number < 1 && floatParts.length == 2) { String decimalPortion = floatParts[1]; int numDecimalPlaces = 0; while (decimalPortion.charAt(numDecimalPlaces) == '0') numDecimalPlaces++; if(numDecimalPlaces > 2) currencyFormatter.setMaximumFractionDigits(numDecimalPlaces + 2); else currencyFormatter.setMaximumFractionDigits(2); } else { currencyFormatter.setMaximumFractionDigits(2); } return currencyFormatter.format(n...

SUM and multiply values in one row based on text in 1st column in excel

My goal is simple, but I can't find the solution as I'm not sure how to call it in general. I have a table with names of teams ( column 1 ) and amount of items ( column 3 ) which are assigned to them. Table is some kind of 'outcome' list: Team A Date 200 pcs 2 Team B Date 300 pcs 4 Team A Date 20 pcs 6 and so on. I would like to ask what function should I use if I require advanced return as example: if <A1:A> "Team B" then in <C1:C> * <D1:D> (which is also filtered only for current team). Function SUMIF (range, criteria, sum range) is something that is suitable for my request, but multiplying messed this up . Is there anything where I can set range and criteria and just be sure I'm working only with Team A in my formula?

How to customize barchart in plotly R?

Image
On barchart: 'sale' and 'share' variables are visualized via bars, while 'cost' by a red line. Now I want to drop/remove this red line and keep only numbers into boxes and add corresponding variable in the legend map. Moreover I want to add average value of 'share' as a horizontal line on the Y axis df <- data.frame (model = c("A", "B", "C","D","E","F"), share = c(12,20,15,9,60,20), sale = c(16,25,18,14,67,28), cost = c(14,19,28,24,57,28)) #set levels of model by cost df$model <- factor(df$model, levels = arrange(df, desc(df$cost))$model) library(tidyverse) df_long <- df %>% pivot_longer( cols = -model ) df_long %>% filter(name != "cost") %>% plot_ly(x = ~model, y = ~value, color = ~name, type = "bar", customdata = ~name, colors = c("blue", "gr...

Functional composition of Optionals

I have 2 Optionals ( potentially containing objects ) that I would like to combine so that I get the following results: || first operand second ++-------------+------------- operand || empty | optional(x) ============||=============|============= empty || empty | optional(x) ------------++-------------+------------- optional(y) || optional(y) |optional(x+y) In other words, a non-empty Optional always replaces/overwrites an empty one, and two non-empty Optionals are combined according to some + function . Initially, I assumed that the standard monadic flatMap() method would do the trick, but (at least in Java) Optional.flatMap() always returns an empty optional when the original Optional was already empty (and I'm not sure if any other implementation would comply with the Monad Laws). Then, as both operands are wrapped in the same monadic type, I figured that this might be a good job for an Applicative Functor. I tried a couple...

How to optimize the performance of the following SQL query?

For the following query , I tried creating index on table tmp.req_index_cont_t with columns indcont_key_1 and ind_no but still optimizer is performing full table scan , I am not getting how to resolve this issue , please guide : CREATE INDEX tmp.REQ_CONT_T_IDX ON tmp.req_index_cont_t (ind_no, indcont_key_1); select distinct rit.item_no as item_no, rit.item_type as item_type, rit.ind_no as ind_no, rit.delete_date as req_ind_delete_date, indcnt.delete_date as req_ind_cont_delete_date from tmp.req_index_cont_t indcnt, tmp.req_index_t rit where rit.ind_no = indcnt.ind_no and indcnt.indcont_key_1 <> 'DN' and rit.ind_state = 'Approved' group by rit.item_no, rit.item_type, rit.ind_no, indcnt.delete_date, rit.delete_date ;