Posts

Showing posts from October, 2022

define anagram Python

Could anyone help? Need to define words on being Anagrams. But exactly the same words are not anagram. For example: cat - kitten The words aren't anagrams; cat - act The words are anagrams; cat - cat should be The same words. What should l do in this code to include The same words: s1 = input("Enter first word:") s2 = input("Enter second word:") a = sorted(s for s in s1.lower() if s.isalpha()) b = sorted(s for s in s2.lower() if s.isalpha()) if sorted(a) == sorted(b): print("The words are anagrams.") else: print("The words aren't anagrams.")

Spring Boot / Spring Data Jpa: Where is the property "spring.jpa.properties.hibernate.generate_statistics" read in the java code?

I have gone through the Common Application Properties reference page. This contains the list of commonly used spring props and the values of these properties can be defined in application.properties or application.yml. So, just to explore and find out the convention regarding how and where the above props are declared (read) in java code, I started to search the code for spring-data-jpa related properties. From this SOF answer I could see that spring.datasource.driverClassName property is located at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties i.e at source Similarly I want to locate the code for other properties like - spring.jpa.properties.hibernate.cache.use_query_cache props and spring.jpa.properties.hibernate.generate_statistics . I looked at spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm but could not find any. Any suggestions are highly appreciated. I am Just trying to understand spring boot a little deeper. No...

Use logger in custom classes in my console application with Dependency Injection

I have a console application, and I added logger builder as follows in Program.cs : using var loggerFactory = LoggerFactory.Create(builder => { builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddConsole(); }); ILogger logger = loggerFactory.CreateLogger<Program>(); Now say I have many classes in the project and all want to use logger. How can I make it available to other classes? For example, I have: internal class Test { public Test() { //use logger here //logger.LogInformation("Calling Test"); } } In certain kinds of projects such as Azure Functions, the logger is readily injected in the functions, is there a similar way I can do it in Console application?

Add a new column with counter to a df based on an existing column

The data frame I have: Column A Column B A 1 na 4 na 5 na 6 B 2 na 4 na 6 na 7 na 8 C 6 na 1 na 5 I am trying to loop through data frame using Python and create a new column C based on Column A's value. Output should look like this; Column A Column B Column C A 1 1 na 4 1 na 5 1 na 6 1 B 2 2 na 4 2 na 6 2 na 7 2 na 8 2 A 6 3 na 1 3 na 5 3 Basically adding a counter in column C when there is a new value in Column A after NAs(even if the value in Column A is same as the previous value; in this eg. A comes twice but the counter gives 1st A value 1 and when it again comes then it gives it a value 3).

Is this the right use-case for on demand ISR in Next.js?

So I am building an app that lets you search for a word and gives you the word in other languages. A clone to this site I just tried Next.js On Demand ISR feature and I did that because fetching from the client using API routes was too slow in my app. I also thought of generating static pages but that would cause hundreds of thousands of static pages. Here's how my code looks like now: export async function getStaticPaths() { console.log("[Next.js] Running getStaticPaths for word page"); return { paths: [{ params: { word: "1" } }, { params: { word: "2" } }], fallback: "blocking", }; } export async function getStaticProps({ params }: GetStaticPropsContext) { const db = await getContainer(); const { resources } = await db.items .query( `SELECT c.language, c.Translation, c.id FROM c WHERE c.PrimaryWord='${params?.word}'` ) .fetchAll(); return { props: { resources, }, }; } I ...

OpenCV with CUDA (Ubuntu 22.04), python import error: "undefined symbol: gst_base_src_new_segment"

I attempted to build OpenCV with CUDA support for my 6.1 compute compatible GPU on my Ubuntu 22.04 OS. After lots of struggle I finally got the installation to complete without errors (but with 4 "harmless" repeating warnings) by using OpenCV 4.2.0, Nvidia Toolkit 11.5, gcc and g++ 10.4.0, and python 3.10.6 (in a virtual environment in anaconda). when I check the installation using "pkg-config --libs opencv" I get an error saying it doesn't exist, and when I try to import opencv in the anaconda environment I get the error /lib/x86_64-linux-gnu/libgstapp-1.0.so.0: undefined symbol: gst_base_src_new_segment , which occurs in cv2/__init__.py when executing bootstrap(). The installation results in lots of promising looking .h, .hpp and .so files. I have not installed packages from scratch like this before so I am not sure how to tell if the installation was successful or not. The error I get is the best-case I was able to achieve by experimenting with various vers...

GMock EXPECT_CALL returns FAILED while comparing two char arguments inside the method [duplicate]

As the tittle, I'm using gmock to test my feature. But one of the issue occurred that EXPECT_CALL always check address of 2 char array instead of their value. Below is my code example: Base.h //Create singleton class class Base { private: static Base* _ptrInstance; public: static Base* getInstance(); void sendString(const char* text, int value); }; Base.cpp #include "Base.h" Base* Base::_ptrInstance = NULL; Base* Base::getInstance(){ if ( NULL == _ptrInstance ){ _ptrInstance = new Base(); } return _ptrInstance ; } void Base::sendString(const char* text, int value){ //do something } Here is the function that need to be tested: test.cpp #include <iostream> #include "Base.h" int Test(){ Base* poBase; char text[] = "hello_world"; poBase->getInstance()->sendString(text, 0); return 0; } my MOCK method: MOCK_METHOD2(sendString, void (const char* text, int value)); here is my test case: TEST_F(myTest, sendStrin...

exact gurobi solver for chromatic number of coloring problem [error in the objective]

I'm trying to solve the coloring problem by using gurobi in a lp setting. However, I do something wrong, but don't what exactly. `!pip install gurobipy' import networkx as nx import gurobipy as gp from gurobipy import * import networkx as nx # create test graph n = 70 p = 0.6 G = nx.erdos_renyi_graph(n, p) nx.draw(G, with_labels = True) # compute chromatic number -- ILP solve m = gp.Model('chrom_num', env =e) # get maximum number of variables necessary k = max(dict(nx.degree(G)).values()) + 1 TEST= range(k) # create k binary variables, y_0 ... y_{k-1} to indicate whether color k is used y = [] for j in range(k): y.append(m.addVar(vtype=gp.GRB.BINARY, name='y_%d' % j, obj=1)) # create n * k binary variables, x_{l,j} that is 1 if node l is colored with j x = [] for l in range(n): x.append([]) for j in range(k): x[-1].append(m.addVar(vtype=gp.GRB.BINARY, name='x_%d_%d' % (l, j), obj=0)) # objective function is minimize ...

Sublime Text 4 sql highlight inside a string [closed]

Image
Currently, if I have sql commands inside a python string, Sublime Text highlights it. However if it's an "f string", it does not recognize the sql inside. Is there any way to make it work the same way as a regular string? This reproduces on builtin Python syntax, which has support for SQL strings highlighting. SQL is detected by non-formatted string starting with uppercase SQL common query identifier ( SELECT , DELETE , UPDATE , INSERT , CREATE TABLE , etc.). However, by design this is not triggered for format strings (with f or F prefix) and raw strings with R prefix (the latter is very weird, given that lowercase r is widely used for regexes, while uppercase - for raw strings in any other context). Is there any way to enable embedded SQL highlight for format strings? Maintainer's position is quite understandable (do not format SQL - use placeholders to be formatted by dedicated library), but it's not always the case: sometimes I'm building queries from...

Find a closest point to another set [closed]

I am trying to create a function to determine which of a set of points (represented as a list of coordinates lists) is closest to another given point. It should return the index in the list where that point appears: Here is the code I've written so far: def sq_dist(p1: tuple[int, int], p2: tuple[int, int]) -> int: """Square of Euclidean distance between p1 and p2 >>> sq_dist([2, 3], [3, 5]) 5 """ x1, y1 = p1 x2, y2 = p2 dx = x2 - x1 dy = y2 - y1 return dx*dx + dy*dy def closest_index(point: tuple[int, int], centroids: list[tuple[int, int]]) -> int: count = 0 soopa_distance = 1000000000000000000000000000000000000000000000000 for p in centroids: distance = sq_dist(point,p) if distance < soopa_distance: soopa_distance = distance else: count = count +1 return count Unfortunately it doesn't return the expected in...

Excel: #CALC! error (Nested Array) when using MAP functions for counting interval overlaps

Image
I am struggling with the following formula, it works for some scenarios but not in all of them. The name input has the data set that is failing, getting an #CALC! error with the description "Nested Array": =LET(input, {"N1",0,0;"N1",0,10;"N1",10,20}, names, INDEX(input,,1), namesUx, UNIQUE(names), dates, FILTER(input, {0,1,1}), byRowResult, BYROW(namesUx, LAMBDA(name, LET(set, FILTER(dates, names=name), startDates, INDEX(set,,1), endDates, INDEX(set,,2), onePeriod, IF(ROWS(startDates)=1, TRUE, FALSE), IF(onePeriod, IF(startDates <= IF(endDates > 0, endDates, startDates + 1),0, 1), LET(seq, SEQUENCE(ROWS(startDates)), mapResult, MAP(startDates, endDates, seq, LAMBDA(start,end,idx, LET(incIdx, 1-N(ISNUMBER(XMATCH(seq,idx))), startInc, FILTER(startDates, incIdx), endInc, FILTER(endDates, incIdx), MAP(startInc, endInc,LAMBDA(ss,ee, N(AND(start <= ee, end >= s...

Mikro Orm with nestjs does not load entities automatically

I'm trying to make a nestjs project with Mikro Orm refrencing load-entities-automatically . But Mikro Orm does not create tables automatically... The following codes are my settings AppModule.ts @Module({ imports: [ MikroOrmModule.forRoot({ type: 'postgresql', host: 'localhost', user: 'test', password: 'test', dbName: 'test', port: 5440, autoLoadEntities: true, entities: ['../entity/domain'], entitiesTs: ['../entity/domain'], allowGlobalContext: true, schemaGenerator: { createForeignKeyConstraints: false, }, }), UserModule, ], controllers: [], providers: [], }) export class AppModule {} UserModule @Module({ imports: [UserEntityModule], controllers: [UserController], providers: [UserService, UserRepository], }) export class UserModule {} UserRepository import { InjectRepository } from '@mikro-orm/nestjs'; impo...

Is it Possible to create one form using PySimpleGUI to fetch data from excel table?

Dears, Is it Possible to create one form using PySimpleGUI to fetch data from excel table ? I need the reverse process of what has been done in Topic : https://github.com/Sven-Bo/data-entry-form-pysimplegui Thanks in advance

plotly: bar stacking graph

I have a Dataframe with data as follows: data={'A': {'2020_01': 3, '2020_02': 3, '2020_03': 1, '2020_04': 3, '2020_05': 1}, 'B': {'2020_01': 0, '2020_02': 0, '2020_03': 3, '2020_04': 0, '2020_05': 2}, 'other': {'2020_01': 0, '2020_02': 0, '2020_03': 3, '2020_04': 0, '2020_05': 2}, 'total': {'2020_01': 3, '2020_02': 3, '2020_03': 7, '2020_04': 3, '2020_05': 5}} df = pd.DataFrame(data) I would like to represent with ploty in X the dates and in y stacked values of A, B, other for one single bar I can do: import plotly.express as px fig = px.bar(df, x=df.index, y='A', text_auto=True, labels={'A':'bananas'}, height=400) fig.show() How to I have to proceed? I checked a bunch of documentation at no avail: https://community.plotly.com/t/plotly-e...

Laravel 9.x proper organization of .mobileconfig file generation through a zsh script for further download

I am refactoring my project using Laravel 9, which was originally written in native PHP. In the past, I have implemented simple method of generating some unsigned.mobileconfig file, then saving it to the download folder, signing it with my certs and creating a link for the user to download it. Then i deleted old configurations via cron once a week. I have following questions: Is it possible to create and simultaneously sign a similar configuration file "on the fly" in Laravel, without saving it on the backend? If not, what is the best way to organize this process so that the link will be available via api routing? Where is the best place to store script files in the standard Laravel project structure? Or is it easier to store them on the server side and run them using, for example, this Symfony package ? Some words about my new project - i'm using default Laravel folder structure with Spatie DTO's and business-logic organized in service layer ('tiny co...

How to handle "curl -XGET http://testdomain.com --request-target example.com:80" with Gorilla

How do I create a Path or PathPrefix in Gorilla http framework if the user forces a URI that does not begin with a slash? This causes a direct to whatever the user specifies, e.g.: # curl -Iv http://testdomain.com --request-target example.com:80 * Added testdomain.com to DNS cache * Hostname testdomain.com was found in DNS cache > HEAD example:80 HTTP/1.1 > Host: testdomain.com > User-Agent: curl/7.79.1 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 301 Moved Permanently HTTP/1.1 301 Moved Permanently < Location: example:80 Location: example:80 < Date: Fri, 28 Oct 2022 18:53:03 GMT Date: Fri, 28 Oct 2022 18:53:03 GMT < * Connection #0 to host REDACTED left intact Currently, it does not match anything in my route setup, yet generates a redirect. Middle-ware is also not catching anything to act on: func filterMW(next http.Handler) http.Handler { logrus.Infof("In filterMW") return http.HandlerFunc(func(w http.ResponseWri...

User prefix, code not working in discord.py rewrite branch

guys! I'm pretty new to dpy btw How do you make a user prefix? For example Asios prefix is ! Which is the default prefix , but i want to give Bsio a different prefix. I'm stuck on how to get the prefix, i couldn't find any tutorial or in the docs. def pr(ctx, message): if message.author == 0000000: prefix = "!" else: prefix = "_" It just doens't work.

How to find the maximum sum of elements of a list with a given minimum distance between them

I have been looking for a way to find the possible combinations of a list, given a minimal distance of 3 between all the numbers. Suppose we have list = [23, 48, 10, 55, 238, 11, 12, 23, 48, 10, 55, 238, 11, 12, 23, 48, 10, 55, 238, 11] The best possible combination would be 23 + 238 + 238 + 238 = 737. I've tried parsing the list and selecting each time the max of the split list[i:i+4], like so : 23 -skip three indexes -> max of [238, 11, 12, 23] : 238 -skip three indexes -> max of [48, 10, 55, 238] : 238 skip three indexes -> max of [48, 10, 55, 238] : 238 This worked with this case, but not with other lists where I couldn't compare the skipped indexes. Any help would be greatly appreciated.

Automation enable "Chat External, Drive Sharing Outside, Sites Creation and Editing" for OU

My organization just switched to Google Workspace, I have created my organization's OUs in Workspace as follows: Example: khanhhoaedu(level 1) | --- school1(level 2) | | | ----- gv(level 3) | ----- it(level 3) | ----- sp(level 3) --- school2(level 2) | | | ----- gv(level 3) | ----- it(level 3) | ----- sp(level 3) --- school3(level 2) | | | ----- gv(level 3) | ----- it(level 3) | ----- sp(level 3) ---- district1(level 2) | | | ----- school4(level 3) | | | ----- gv(level 4) | ----- it(level 4) | ----- sp(level 4) | | | ----- school5(level 3) | | | ----- gv(level 4) | ----- it(level 4) | ----- sp(level 4) ---- district2(level 2) | | | ----- school6(level 3) | | | ----- gv(level 4) | ----- it(level 4) | ----- sp(level 4) | | | ----- school7(level 3) | | | ...

Postgres not using index when ORDER BY and LIMIT when LIMIT above X

I have been trying to debug an issue with postgres where it decides to not use an index when LIMIT is above a specific value. For example I have a table of 150k rows and when searching with LIMIT of 286 it uses the index while with LIMIT above 286 it does not. LIMIT 286 uses index db=# explain (analyze, buffers) SELECT * FROM tempz.tempx AS r INNER JOIN tempz.tempy AS z ON (r.id_tempy=z.id) WHERE z.int_col=2000 AND z.string_col='temp_string' ORDER BY r.name ASC, r.type ASC, r.id ASC LIMIT 286; QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=0.56..5024.12 rows=286 width=810) (actual time=0.030..0.992 rows=286 loops=1) Buffers: shared hit=921 -> Nested Loop (cost=0.56..16968.23 rows=96...

Android Studio Can't Connect to Internet/Download SDK on Windows 11

Image
Really frustrating issue: i'm trying to install and run Android Studio on Windows 11, but every time I open it I get a message that some broken proxy setting is preventing the Android SDK from being downloaded. I'm not using a proxy at all as far as I know. I've read lots of posts explaining that it's a Windows Firewall issue, but nothing I've tried has worked. What I've tried so far: Reinstalled Android Studio Added Android Studio inbound & outbound exceptions to Windows Firewall Disabled Windows Firewall entirely Tried installing on different users on same Machine (same error) Installed Electric Eel Beta version of Android Studio (instead of stable channel's Dolphin, same error) Flushed DNS cache on my PC Closing the first run wizard and trying to manually download the SDK from SDK Manager in Android Studio (always "Unavailable") Nothing has worked. I see this user here faced my exact issue and they said they were able to fix it b...

T test between price and size

kcovkcvxcv xcvxc vxc ksmvsdkvsdm lvsdmv dmmdsm]vsd vsdv sdmlvsdvsd vsdm

ClassCastException: ApiException cannot be cast to RevolvableApiException after updating location library to 21 version

I have updated location services libraries in my App to the latest 21 version: com.google.android.gms:play-services-location:21.0.0 and it breaks the logic for enabling location settings on the users phones. I found updated page with documentation about this process: https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient , and using code below for triggering popup which should ask user to allow enabling location access on the phone: val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10000) .setMinUpdateIntervalMillis(5000).build() val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest) val client: SettingsClient = LocationServices.getSettingsClient(activity) val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build()) task.addOnCompleteListener { try { ...

How to sort time column in jqgrid?

Image
We are binding a table using jqgrid. We have the first column start as a time column with a 12-hour format. We are facing an issue with sorting this data. The data is sorted correctly but it is not taking am/pm into consideration. Below is our code for binding the jqgrid: var newFieldsArray = [ { name: "ID", title: "ID", type: "number", width: "50px", visible: false }, { name: "TimeStart", title: "Start", type: "customTime", width: "100px", validate: "required", sorttype: "date", formatter : { date : { AmPm : ["am","pm","AM","PM"], } }, // datefmt: "m/d/Y h:i A", //sorttype: 'datetime', formatter: 'date', formatop...

Weird rb.velocity.y

When I'm moving left or right rb.velocity.y changes to weird numbers. How can I get rid of this? It really annoing because I want to change the gravity when player is jumping and because of this bug gravity changes even if player is moving left and right. My code: using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class movePlayer : MonoBehaviour { public ParticleSystem dust; public Animator animator; [SerializeField] public float speed; private float moveInput; public float jump; private Rigidbody2D rb; public BoxCollider2D coll; private bool facingRight = true; [SerializeField]private bool isGrounded; public Transform GroundCheck; public LayerMask WhatIsGround; public float fallMultiplier = 3.5f; public float lowJumpMultiplier = 3f; private bool jumped = false; void Start() { rb = GetComponent<Rigidbody2D>(); coll = GetComponent<BoxColl...

SwiftUI - Access List Selection in Another View

I want to access the list selection in another view. import SwiftUI struct ExerciseSelectorView: View { @Environment(\.managedObjectContext) var viewContext @Environment(\.dismiss) var dismiss @FetchRequest(sortDescriptors: []) var exercises: FetchedResults<Exercise> @State var selectedItems = Set<Exercise>() var body: some View { NavigationView { VStack { Button("Add") { createExerciseSet() } List(selection: $selectedItems) { ForEach(exercises, id: \.self) { e in Text(e.exercisename) } } .environment(\.editMode, .constant(EditMode.active)) .navigationBarTitle(Text("Selected \(selectedItems.count) rows")) .toolbar { EditButton() } } } } I'm pretty s...

How to loop through rows of data in .CSV file in Cypress test?

In my Cypress test, I am trying to read data from a CSV file & loop through each row. Below is the contents of my fixtures/logins.csv file: | username | password | | john | pword1 | | james | myPassword | | frank | newPassword | I want to loop through each row of data to log into an application. Here is my latest code, it just logs the CSV file data as a string currently: const csvUploaded = 'cypress/fixtures/logins.csv' it('CSV test', () => { cy.readFile(csvUploaded, 'utf-8').then((txt) => { cy.log(txt) cy.log(typeof txt) }); }); txt is the below string at the moment: username,password john,pword1 james,myPassword frank,newPassword

How to use Update Panel for ASP.Net and Javascript?

I have a textbox with onkeyup event that call JavaScript function GetEmployee() this function gets items from database where full name contains value typed on textbox. Everything is working, but I want to add a button save with server-side functionality which is doing an error on post back . I want to use asp:updatepanel as solution for the error but don't know how to do it . Here is my code <asp:TextBox ID="txtSelectUser" AutoPostBack="true" runat="server" class="InputFormStyle form-control" OnKeyUp="GetEmployee();"></asp:TextBox> <asp:ListBox ID="lstEmployee" runat="server" onchange="SelectUser();"></asp:ListBox> <asp:Button Text="Save" runat="server" OnClick="btnadd_Click" ID="btnadd"/> <script type="text/javascript"> var selectedUserId = 0; $(document).ready(function () { $("...

VS Code - Cannot debug blazor wasm client projetc : Unable to lauch browser "The URL's protocol must be one of ws, wss or ws+inix"

Image
I have downloaded the Samples to accompany the official Microsoft Blazor documentation https://github.com/dotnet/blazor-samples In VS Code then I open the folder ..\blazor-samples-main\6.0\BlazorSample_WebAssembly I let VS Code add the assets in the subfolder .vscode launch.json task.json I have modified the launch.json to be { "version": "0.2.0", "configurations": [ { "name": "Launch and Debug Standalone Blazor WebAssembly App", "type": "blazorwasm", "request": "launch", "cwd": "${workspaceFolder}", "url": "https://localhost:5001" } ]} and I have modified the launchSettings.json located in the Properties folder to be { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": ...

Insert Array Data from File into MYSQL using PHP

I am having trouble trying to connect to a MySQL DB to insert certain JSON values from a .json file. I am still fairly new to working with data, connecting to a DB via PHP and such. The db is in the same cpanel/host/server as where this file is found. Please let me know if I need to change, add or improve anything. What I am trying to do, is read the file.json and then insert those entries into a remote DB that is on my server. What I am looking for is how to insert these values into insert the data into a MYSQL, not print it on a page. This question doesn't answer my question: How to extract and access data from JSON with PHP? <!DOCTYPE html> <html> <body> <h1>Insert Data into DB</h1> <?php $username = "user"; $password = "pass"; // Create connection $con = new PDO('mysql:host=host;dbname=DBNAME', $username, $password); //read the json file contents $jsondata = file_get_contents('http://p...

ValueError: Layer "model_1" expects 2 input(s), but it received 1 input tensors

I am trying to build a text classification model using the Bert pre train model, but I keep getting an error when I try to fit the model. The error says ValueError: Layer "model_1" expects 2 inputs but it received only 1 input tensor. Inputs received: \[\<tf.Tensor 'IteratorGetNext:0' shape=(None, 309) dtype=int32\>\] I am also using TensorFlow and other Python libraries. Here is my code: import numpy as np from data_helpers import load_data from keras.models import Sequential from keras.layers import Dense from tensorflow.keras.layers import Embedding from sklearn.model_selection import train_test_split from keras.layers.convolutional import Conv1D from keras.layers.convolutional import MaxPooling1D from keras.layers import Dropout,Flatten from sklearn.metrics import classification_report from transformers import TFBertModel import tensorflow as tf import tensorflow_hub as hub import tensorflow_text as text from tensorflow.keras.layers import Embedding ...

Double showing a lot of zeros with printf

I wanted to write a little calculator, which I have already done by using cout and cin , and I used double instead of int to not only get integers as an output. At school, I then saw that we're going to use printf() and scanf() . To practice the new commands, I wanted to rewrite my program, but when I run my program I only see a lot of zeros after the comma as an output. Does anybody know why? I wanted to rebuild a calculator with double instead of int to not only get integers as a result. This is the code: #include <stdio.h> using namespace std; int main(){ printf ("Taschenrechner\n\n"); int zahl1, zahl2; char rechop; double erg; printf ("Gib die Rechnung ein: "); scanf ("%d", &zahl1); scanf ("%c", &rechop); scanf ("%d", &zahl2); if (rechop == '+'){ erg = zahl1+ zahl2; printf ("Ergebnis: "); printf ("%f", ...

How to extract configuration or ARM template for Azure App Insights User Flow

I have an Azure App Insights instance and a User Flow has been added to it and shared with others via the "Shared reports" folder. The User Flow was created manually using the Azure Portal UI. I would like to script the creation of this User Flow, but I am struggling to extract the configuration JSON from component. I believe the User Flow is a microsoft.insights/favorites component. But when using Azure resource explorer I do not see such a component under the App Insights resource's microsoft.insights provider. Does anyone know how to export the ARM template for an App Insights User Flow? Or, at least get at the JSON configuration for the User Flow?

Testing strategy for typescript lambda with database dependency

I have a typescript lambda that calls a database. I have written unit tests for the individual components for this (service that takes the db as a constructor argument for mocking etc, that all works fine). I am looking to write a test that calls the lambda handler itselff, however if I do this, I can no longer pass a db mock, therefore it tries to call the real database. Is there an established pattern for doing this other than spinning up a local database in docker/in memory database etc? import { APIGatewayProxyCallback } from "aws-lambda"; import { myService } from "./service/myService"; import { myRepository } from "./repository/myRepository"; export const lambdaHandler = async ( event: any, context: any, callback: APIGatewayProxyCallback, ): Promise<void> => { const service = new myService(new myRepository()); const res = myService.execute(event); // Contains code for interacting with db callback(null, { ...

How to setup 28 different local notifications that repeat every 28 days at 9AM [closed]

I am looking to setup a batch of 28 local notifications (1 each day) that will repeat again after 28 days until cancelled. These have to be set to be triggered at 9:00 AM everyday. I have tried to set these notifications using the UNCalendarNotificationTrigger by giving datecomponents and adding a day by looping thru all the 28 and set repeating as true. The downside is UNCalendarNotificationTrigger sets for the calendar month and not 28 days, so for day 29, 30 & 31 there are no notifications displayed. I need something that will trigger back to back. This question has provided with some idea of how to use UNTimeIntervalNotificationTrigger, this works for one set of recurring notifications, but after that, they trigger at different intervals. To make things easier to test, I have changed interval to 1 message every minute for 5 messages and then schedule 5 recurring messages using intervals. These recurring messages have repeat:true. After the 5 recurring messages, they don...

How to refer to the certificate from windows certificate store for MQ managed client in docker image?

I am trying to connect to MQ using MQ managed client which refers to the certificate from certificate store. I have created the docker image for the code and now wondering how to push the certificate along with it. End goal is to deploy the image to the openshift pod. Hashtable properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, "XXXXXXXXXXXX"); properties.Add(MQC.PORT_PROPERTY, "XXXX"); properties.Add(MQC.CHANNEL_PROPERTY, "XXXXX"); //SSL properties.Add(MQC.SSL_CERT_STORE_PROPERTY, "*USER"); properties.Add(MQC.SSL_CIPHER_SPEC_PROPERTY, "TLS_RSA_WITH_AES_256_CBC_SHA256"); properties.Add(MQC.SSL_PEER_NAME_PROPERTY,"XXXXXX"); properties.Add(MQC.SSL_RESET_COUNT_PROPERTY, 0); queueManager = new MQQueueManager(QueueManagerName, properties); The code is working fine directly without any issues but I am not aware of how to proceed with docke...

Alternative to ParallelForEach That can allow me to kill parallel processes immediately on Application Exit?

I am doing a simple console application that loads files from a database into a hashset. These files are then processed in a parallel foreach loop. This console application does launch a new Process object for each files it needs to process. So it opens new console windows with the application running. I am doing it this way because of logging issues I have if I run parsing from within the application where logs from different threads write into each other. The issue is, when I do close the application, the parallel foreach loop still tries to process one more file before exiting. I want all tasks to stop immediately when I kill the application. Here is code excerpts: My cancel is borrowed from: Capture console exit C# Essentially the program performs some cleanup duties when it receives a cancel command such as CTRL+C or closing window with X button The code I am trying to cancel is here: static ConcurrentDictionary<int, Tuple<Tdx2KlarfParserProcInfo, string>> _curren...

Using roll-forward window to create a training set for ML based on multivariate time series

Based on the simplifed sample dataframe import pandas as pd import numpy as np timestamps = pd.date_range(start='2017-01-01', end='2017-01-5', inclusive='left') values = np.arange(0,len(timestamps)) df = pd.DataFrame({'A': values ,'B' : values*2}, index = timestamps ) print(df) A B 2017-01-01 0 0 2017-01-02 1 2 2017-01-03 2 4 2017-01-04 3 6 I want to use a roll-forward window of size 2 with a stride of 1 to create a resulting dataframe like timestep_1 timestep_2 target_A 0 A 0 1 2 B 0 2 2 1 A 1 2 3 B 2 4 3 To create a dataframe for the training of an ML model that predicts target values based on the values of n previous timesteps, where n=2, in the example above. I.e., for each window step, a data item is created with the two values of A and B in this window and the A value immediatel...

How to apply 1/σ^2 weight matrix to find Weighted Least Squares Solution

Image
I am trying to solve a Weighted Least Squares problem on Python (using numpy) but I am unsure on how to apply the following weight on This is what i have done so far import numpy as np import matplotlib.pyplot as plt X = np.random.rand(50) #Generate X values Y = 2 + 3*X + np.random.rand(50) #Y Values plt.plot(X,Y,'o') plt.xlabel('X') plt.ylabel('Y') W = ?? X_b = np.c_[np.ones((50,1)), X] #generate [1,x] beta = np.linalg.inv(X_b.T.dot(W).dot(X_b)).dot(X_b.T).dot(W).dot(Y)

roboflow yoloV5 training same size problem

i am trying to train model via roboflow yolov5 notebook on colab. i always use pre-labeled roboflow data. and the problem is : the all final pt weight files has the same size (14.6 mb). the big data or tiny data, there is no difference among sizes. i think it's ridiculous. can someone explain it? colab notebook : https://colab.research.google.com/drive/1gDZ2xcTOgR39tGGs-EZ6i3RTs16wmzZQ

How to read /dev/input/mice more accurately?

I'm writing a program to read /dev/input/mice to get relative x,y positions and get the absolute distance the cursor moves. If I move my mouse at a normal speed starting at the center of the screen, the result is pretty accurate(960). However, if I move my mouse really fast, the absolute distance is not accurate. #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/select.h> int main() { signed char x, y; signed char buf[6]; int fd; fd_set readfds; int screen_x = 1920; int screen_y = 1080; int x_total = 0, y_total = 0; // Create the file descriptor fd = open("/dev/input/mice", O_RDONLY); if (fd == -1) { printf("Error Opening /dev/input/mice\n"); return 1; } printf("sizeof(buf): %d\n", sizeof(buf)); // Loop that reads relative position in /device/input/mice while(1) { //...

VS Code: avoid overaggressive parenthesis removal (in Scala / Metals)

Image
I don't think this is a Scala- or Metals-specific issue, but that's where I'm seeing it. VS Code aggressively removes parentheses, but not in a symmetric fashion. For instance, if I type the following: and I want to remove the inside parentheses, I would start by removing the inner closing parenthesis: OK, the highlighting is already suggesting the problem: when I removed the inner parenthesis, it is the outer one that looks unmatched. If I now go ahead and remove the inner opening parenthesis , both the opening and closing parentheses are lost : So maybe there is a right way to remove them that I am missing. Instead of removing the inside closing parenthesis, I will start by removing the inside opening parenthesis: Unfortunately, in this case only the inner opening parenthesis is removed, so it is still mismatched. Ugly Workaround So for now, I either remove the inner closing parenthesis, then the inner opening parenthesis (which removes both, as shown),...

Inherit a custom user models fields from parent class to a child class between two different applications

Image
Hello kings and queens! I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded. I tried to inherit the model fields from the User class in generalpage.models into profilesettings.models by simply writing UserProfile(User). When I did this, a empty forms was created in the admin panel. So basically, the information that was already stored generalpage.models were not inherited into the profilesettings.models, I created an entire new table in the database. my questions are: Is it possible to create an abstract class for a custom user model? Is there a proper way to handle classes and create a method in profilesettings.models that fills the UserProfile form with the data already stored in database created by the User class? Can someone please explain how the informat...

Error while trying to connect with js code and mongodb

So I've been trying to figure this error and I couldn't find any solution everywhere. After sometime I know where the problem is but I don't know why: const savedUser = await newUser.save(); I believe that here is the problem because it keeps catching the consol.log("not working") This is my code: const router = require("express").Router(); const User = require("../models/User"); router.post("/register", async (req, res) => { const newUser = new User({ username: req.body.username, email: req.body.email, password: req.body.password, }); try { const savedUser = await newUser.save(); //I believe here is the problem res.status(201).json(savedUser); } catch (err) { console.log("not working"); res.status(500).json(err); } }); module.exports = router; and I'm using postman I put the boy as raw and Json: { "username":"lama", "email":...

ROI Boxes specified on specific frames using 3D data in Pyqtgraph app

I'm working with 3D data in my application, which I display using the ImageView class. The code below (copied from GeeksForGeeks is a very close example to it, but I have a custom ROI button that displays a custom ROI box in the display. My question: is there a way I can define the ROI Box to exist on only specified frames? For example: I want the ROI box to exist from frames 3 to 10 and 20 to 25. Thanks in advance! # importing Qt widgets from PyQt5.QtWidgets import * # importing system import sys # importing numpy as np import numpy as np # importing pyqtgraph as pg import pyqtgraph as pg from PyQt5.QtGui import * from PyQt5.QtCore import * # Image View class class ImageView(pg.ImageView): # constructor which inherit original # ImageView def __init__(self, *args, **kwargs): pg.ImageView.__init__(self, *args, **kwargs) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWin...