DOM is not ready in mounted hook? Posted: 26 Nov 2021 11:02 AM PST Did I get an error for DOM in the mounted hook, how to fix it? I found a dirty fix with the set timeout method, but that is not the solution. setTimeout(() => { ... // VanillaJS DOM is ready! // This is extrenal file }, 1000); mounted() { ... call imported function from above } Help me, how to solve this problem, I want to have DOM ready for vanilla JS DOM manipulation :) |
Firebase - How to extend FirebaseError? Posted: 26 Nov 2021 11:02 AM PST I am implementing a cloud function for signing up with unique username and password. In order to throw exceptions, I was previously doing the following: signUpValidation.js if (!validateUsername(username)) { throw new functions.https.HttpsError( "invalid-argument", "Invalid username.", { status: "error", code: "auth/invalid-username", message: "Username must be between 3 and 30 characters, including numbers, letters, hyphens, periods, or underscores.", } ); } signUp.function.js try { await validateSignUpData( username, email, password, repeatPassword, name, birthday, clientIp ); } catch(err) { if (err instanceof functions.https.HttpsError) { throw err; } // An unknown error has occurred console.error(err); throw new functions.https.HttpsError( "unknown", "Unexpected error.", { status: "error", code: err.code ?? "unknown", message: err.message ?? "The registration request could not be processed. Please, try again later." } ); } But, I don't really like this way of throwing the exceptions in the signUpValidation module... it makes more sense to me to throw "AuthErrors" instead of "HttpsErrors". So, as it seems not possible to extend the default Firebase Errors, I have decided to create my own util/authErrors module: class AuthError extends Error { constructor(code, message) { super(message); this.code = code; this.name = "AuthError"; } } const authErrors = Object.freeze({ usernameAlreadyExists(message = "The username is already in use by an existing account") { return new AuthError('auth/email-already-exists', message); } ... more errors }); module.exports = authErrors; as you can see, I have created my custom Error and some factory functions for every error type. Then, in my signUpValidation.js, I just do: if (!(await isUsernameUnique(username))) { throw authErrors.usernameAlreadyExists(); } Is it possible to extend a FirebaseError? If not, why? Is it considered a bad practice to work this way in order to throw custom exceptions in Cloud Functions? I mean, should I just throw HttpsErrors? |
Issues with git branches in pycharm Posted: 26 Nov 2021 11:02 AM PST I've struggling with branches in pycharm: I create a new branch, let's say 'new-branch'. Then, I write some additional code and when I switch (checkout) back to master branch, the files reflects the same code on 'new-branch', without I have not made a merge. Is it a bug or I have to commit before to checkout back to master? PyCharm version: 2021.2.3 (community) running on Win10 |
Arduino is freezing even with watchdog enabled Posted: 26 Nov 2021 11:02 AM PST I have made a hardware development based on an ATmega328P and programmed with the Arduino IDE. The board has one relay output that switchs an AC load. From time to time, the microcontroller is restarted when the load is switched ON or OFF. No mystery so far. It is probably some EMI interference that is causing the reboot. BUT, sometimes the microcontroller freezes completely. I can´t figure out why, as I have enabled the watchdog timer. There shouldn't be any freezing. As far as I know, the watchdog timer should restart the microcontroller after 2 seconds. I would need help understanding WHY I am getting this behaviour and of course, if there could be any software fix. This is a simple code to show this behaviour. I already tried to change some fuses configurations (brownout, wdton, etc) but no luck so far. Any help would be much appreciated Thanks in advance #include <avr/wdt.h> #define R0 3 #define R1 4 #define R2 5 unsigned int delayTime = 200; unsigned int counter = 0; //-------------------------------------------------------------------- void setup() { MCUSR = 0; wdt_disable(); Serial.begin (9600); delay (1000); Serial.println ("********************RESTARTING*****************"); pinMode (R0, OUTPUT); pinMode (R1, OUTPUT); pinMode (R2, OUTPUT); delay (2000); wdt_enable (WDTO_2S); } //-------------------------------------------------------------------- void loop() { wdt_reset(); digitalWrite (R1, HIGH); counter++; Serial.print ("R1 activated, counter = "); Serial.println (counter); delay (delayTime); digitalWrite (R1, LOW); Serial.print ("R1 deactivated, counter = "); Serial.println (counter); delay (delayTime); } |
Microsoft Support Chat $85×59×15×6O×5O "help".microsoft.com™ talk❞❞ to a person Posted: 26 Nov 2021 11:01 AM PST This Help.microsoft.com ++1-855-915-6050 rebuilds the data utility but doesn't fix the eCOIN.BASEor. This is often a complicated issue and has required fixing as soon as possible. When this Help.microsoft.comoccurs users generally get the message, 'Recover data file' or 'Your HELP.MICROSOFT.COMisn't working. For this eCOIN.BASEor, the HELP.MICROSOFT.COMfile must fix and recovered. To stop this Help.microsoft.comfrom doing any damage, restore a backup copy, and then condense the company file. It's a really Support software issue that needs immediate HELP.MICROSOFT.COMmention and will be fixed as soon as possible. How does HELP.MICROSOFT.COM ++1-855-915-6050 Support Number affect? As mentioned earlier they skipped 111 Help.microsoft.comis one of the most occuCOIN.BASEing eCOIN.BASEors in MS OFFICE. So it means the business or user is at constant risk of Contact of HELP.MICROSOFT.COMSupport Number HELP.MICROSOFT.COMSupport Phone Number mostly occurs within the application system because of file damage. The file must be repaired by either restoration or by replacing it with an earlier saved backup copy of the stored data. HELP.MICROSOFT.COMTECHNICAL Support phone number - However, this is often HELP.MICROSOFT.COMCustomer Support phone number software within the end and that's why HELP.MICROSOFT.COMCustomer Support phone number sometimes it does face issues affecting the business operations of its users. An issue that's quite common has the HELP.MICROSOFT.COM ++1-855-915-6050 Support Phone Number. This Help.microsoft.comcode recovers the data that has been founded and again rebuilds the data section. losing their financial and operational data. Then they need storing in MS OFFICE. It's imperative to make a backup of the data to stop problems in the future. Steps to resolve HELP.MICROSOFT.COMCustomer Support Phone Number Wherever there's a problem there's always a resolution. A similar is that the case with HELP.MICROSOFT.COM ++1-855-915-6050 Support Number. Below mentioned are some steps that may help to repair can pass few tests and if your file passes these tests, then the backup of the file has automatically been created in the ADR folder. After this, the logging program of ADR transactions will invoice all the transactions quickly also as automatically. It'll invoice all the transactions that have integrated with the file from a specific instance on HELP.MICROSOFT.COM ++1-855-915-6050 Software. Once the recovering process is complete, HELP.MICROSOFT.COMaccounting software will create a duplicate of that file. But if your application is open, you'd not find any backup created. This may produce two backup duplicates and also the latest one would be 12 hours old while another would be 24 hours old. This way the oldest file would get deleted.fhfhfh |
Freezed files are added to the commit, ignoring gitignore Posted: 26 Nov 2021 11:01 AM PST These are the lines in my .gitignore concerning the files generated by flutter pub run build_runner build --delete-conflicting-outputs *.freezed.dart *.g.dart I tried git rm -rf --cached . git add . and still *.freezed.dart and *.g.dart get added again |
What would be a better way to implement this if else logic? Posted: 26 Nov 2021 11:02 AM PST I honestly couldn't come up with a better title since it's a scenario-based question: We have a Battleships game, and we want to ask the player for a pair of coordinates to set one of their ships on the grid (more specifically, the starting point and the ending point of the ship). Assuming that the coordinates were properly given and that the ship is in bounds of the grid plane, we only need to check if the ship collides with any other ship currently on the grid plane. Context: A Grid has a Content property, and it's either ShipContent or EmptyContent. The CollisionChecker() method loops through the space between the pair of coordinates that were previously given (mind that these can't be diagonal, this is also assumed to be checked prior). The player wants to put their battleship between A1 and A4. Since the letters are equal, we loop through 1 to 4, simple enough. However, the player could've entered A4 and A1 respective to their order. Both of these scenarios are expected to work as they are logically sound, but they can cause OutOfBound exceptions and/or improper loops if they are not handled accordingly. Last bit of context, CoordinateLetter is an enum that has the entire English alphabet in it. static bool CollisionChecker(Grid[][] gridPlane, CoordinateLetter coordinateLetter1, CoordinateLetter coordinateLetter2, int coordinateNumber1, int coordinateNumber2) { bool lettersEqual = coordinateLetter1 == coordinateLetter2; bool cL1Bigger = coordinateLetter1 > coordinateLetter2; bool cN1Bigger = coordinateNumber1 > coordinateNumber2; if (lettersEqual && cN1Bigger) for (int num = coordinateNumber2; num <= coordinateNumber1; num++) { // Assume that if it collides, it returns false } else if (lettersEqual && !cN1Bigger) { for (int num = coordinateNumber1; num <= coordinateNumber2; num++) { // Assume that if it collides, it returns false } } else if (!lettersEqual && cL1Bigger) { for (int num = (int)coordinateLetter2; num <= (int)coordinateLetter1; num++) { // Assume that if it collides, it returns false } } else { for (int num = (int)coordinateLetter1; num <= (int)coordinateLetter2; num++) { // Assume that if it collides, it returns false } } return true; } This block of code sends shivers down my spine. I don't like chaining if else's like this. What would be a better way to implement this? |
Import CSV with missing columns into MS SQL Server table Posted: 26 Nov 2021 11:02 AM PST Suppose I got a csv file like this: field1 field3 0 1 1 2 The corresponding table looks like this: field1 field2 field3 null null null ... ... ... Suppose all the fields are nullable, how could I import the csv file into the table? I know I could BULK INSERT with a formatter, but I cannot generate formatter by bcp cuz the connection to the local SQL server failed (weird!) Is there any better way to solve this problem? |
How to create a shared navigation bar to inter-navigate among multiple views in SwiftUI? Posted: 26 Nov 2021 11:02 AM PST I would like to navigate among screens A, B, and C by tapping the corresponding button in a shared navigation bar at the bottom of every screen. How can I create such a toolbar to achieve this inter-navigability among screens? |
How do i take user input from discord and store it as a variable to use in an equation? Discord.py Posted: 26 Nov 2021 11:03 AM PST Ok so im not intierly fluent in discord.py but heres the code im trying to use: from discord import channel from discord.embeds import Embed import discord from discord.ext import * import os import random import string from discord.ext import commands from dotenv import load_dotenv from discord.ext import commands import requests import sys import threading from discord.utils import get import discord import asyncio from threading import Thread from keep_alive import keep_alive load_dotenv() bot = commands.Bot(command_prefix = '.') def init(): loop = asyncio.get_event_loop() loop.create_task(bot.run(token)) Thread(target=loop.run_forever).start() @bot.event async def on_ready(): print('Bot is up and running') @bot.command() async def p(ctx): # MESSAGE 1, should have user input stored in variable "place" embed=discord.Embed() embed.add_field(name="Where did you place?", value="** **") sent = await ctx.send(embed=embed) # MESSAGE 2, should have user input stored in variable "kills" embed=discord.Embed() embed.add_field(name="How many kills did you get?", value="** **") sent = await ctx.send(embed=embed) # MESSAGE 3, should have combined input of place + kills AFTER running PLACEMENT CALC in variable "total"" embed=discord.Embed() embed.add_field(name="Total Points:", value=total) sent = await ctx.send(embed=embed) bot.run("OTA0MDc5MzY5NzU1MDU4MjA2.YX2Thg.S4A2e9SqZUvYZpyTzBW44W4Vumk") keep_alive() init() I want to take the user response from the first and second msgs from discord.py and input them into the first 2 questions of this code so i can claculate the total: import sys # Placement input, should be response to MESSAGE 1 In discord.py print ("Where did you place? ") place = int(input('| \n')) #Checking if place is in range from 20-1, Should respond with the message in an embed in discord if place >20 or place <1: place = 0 # Kill input, response to MESSAGE 2 In discord.py print ("How many kills did you get?") kills = int(input('| \n ')) # Assigning total / final variable total = 0 tplace = 0 # ranges for placement variables top20 = (18,19,20) #Top 20 top17 = (16,17) #Top 17 top15 = (13,14,15) #Top 15 top12 = (11,12) #Top 12 top10 = (6,7,8,9,10) #Top 10 #Total kills calculations kills = kills * 10 #Total placement calculations if place in top20: #Top 20 tplace = 10 if place in top17: #Top 17 tplace = 20 if place in top15: #Top 15 tplace = 35 if place in top12: #Top 12 tplace = 50 if place in top10: #Top 10 tplace = 60 if place == 5: #Top 5 tplace = 80 if place == 4: #Top 4 tplace = 90 if place == 3: #Top 3 tplace = 100 if place == 2: #Top 2 tplace = 125 if place == 1: #Top 1 / vic roy tlace = 175 #Output, should be MESSAGE 3 In discord.py total = kills + tplace print ("Total Points: ") print (total) and after calculating the total I just send the variable "total" inside of an emebd, i just dont know hwo to store the response to 2 separate discord message inside of the variables i need. It should run as Bot: "Where did you place?" you: 10 (Stored in variable "place") Bot:"How many kills did you get?" you: 1(Stored in variable "kills") ---------calculating the total points (should be 70)------- Bot: "Total points: 70" |
(C++) Why is the code written in the description/body of this question giving 10(all) 0's as the output? Posted: 26 Nov 2021 11:02 AM PST int main() { vector<int> g1; for (int i = 1; i <= 10; i++) { g1.push_back(i * 10); cout << g1[i] << " "; } } The above written code is giving me output as "0 0 0 0 0 0 0 0 0 0" that 10 0's with a space after each 0 of them, as written in the code. But in the code, it is written to add at the end of the vector the iterator*10: g1.push_back(i * 10); and the output code cout << g1[i] << " "; is giving 0 for every iterations(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) when it should be giving: 10 20 30 40 50 60 70 80 90 100 as the output Output: 0 0 0 0 0 0 0 0 0 0 Expected output: 10 20 30 40 50 60 70 80 90 100 |
What exactly is REST API call? Posted: 26 Nov 2021 11:02 AM PST Somebody in my team pointed that Post on the URL : https://localServer/api/rest/version/docs/docid (get document metadata) is Rest API call, but Get on URL https://localServer/account/docs (get document) is not a REST API call.I am new to REST API, so wanted to know why is that so? Apart from naming in the URL how do I know which is a REST API call and which is not? I was under impression that in REST architecture, the calls made by client to server are REST API calls. |
Sort an array in java with a designated starting value Posted: 26 Nov 2021 11:03 AM PST Say I have an array of Strings [1, 2, 3, 4, 5]. and I have a separate value of int that equals 3. Let's just call that int j. I want to sort the array descending, but starting from the value of whatever j is. The array would count down to 1, and leave the rest of the values alone. So the finished product would look like this: [3, 2, 1, 4, 5] How would I go about this? |
Constraint Handling Rules in SWI Prolog: What's the order of puting a constraint to the store? Posted: 26 Nov 2021 11:01 AM PST I am learning Constraint Handling Rules (CHR) in swi-prolog. I started with the tutorial from Tom Schrijvers' Constraint Handling RulesA Tutorial for (Prolog) Programmers. The confusion part is that what's the order of putting a constraint to the constraint store? p.69 shows that when a rule fires, add the body to (front of) query. p.104 - p.106 show that normally, the order of putting a constraint to the store follows the query order. That is the second constraint (piggy(1) ) will be placed at the right of the first constraint (piggy(5) ) in the store. p.107, according to 1, piggy(6) be added to the front of query and then be put to the store. p.108, the strange thing happen, why piggy(4) be put to the front of the store (left to piggy(6) ) ? p.109 - p.110, more strange thing is that after the rule fired, piggy(10) be added to the store and then piggy(2) be added to the end of the store (right to piggy(10) )? My first question is what's exactly the order of putting a constraint to the constraint store? For example, :- use_module(library(chr)). :- chr_constraint philosophers_stone/0, lead1/0, lead2/0, gold1/0, gold2/0. philosophers_stone \ lead1 <=> gold1. philosophers_stone \ lead2 <=> gold2. ?- lead1, lead2, philosophers_stone. Why the result of the query in swi-prolog is: philosophers_stone, gold1, gold2 instead of philosophers_stone, gold2, gold1 The slow motion is (in my understanding): query: lead1, lead2, philosophers_stone. store: query: store: lead1, lead2, philosophers_stone. query: gold1 store: lead2, philosophers_stone query: gold2, gold1 <---- added to (front of) query store: philosophers_stone query: store: philosophers_stone, gold2, gold1 It seems that when a rule fires, the body should be added to (end of) query? Is that right? query: lead1, lead2, philosophers_stone. store: query: store: lead1, lead2, philosophers_stone. query: gold1 store: lead2, philosophers_stone query: gold1, gold2 <---- added to (end of) query store: philosophers_stone query: store: philosophers_stone, gold1, gold2 <--- then correct My second question is the order sensitive? I mean that even if the putting orders are different, the result will eventually confluent up to reordering the stable store? Can I safely ignore this order? I know that the order of rules is very sensitive in swi-prolog's CHR implementation and they can not be ignored. Thanks. |
How to properly use run_detached() and stop() in pystray? Posted: 26 Nov 2021 11:01 AM PST I'm trying to use pystray without blocking the main thread. Based on the pystray docs we can use the function run_detached() to start without blocking. I'm using pystray on windows so, apparently I don't need to pass any argument to run_detached() to work. The first thing I tried is to run this code: import pystray from pystray import MenuItem as item from PIL import Image, ImageTk def show_window(icon): print('Test') def quit_window(icon): icon.stop() icon = 'icon.ico' image=Image.open(icon) menu=pystray.Menu(item('Show', show_window, default=True), item('Quit', quit_window)) icon=pystray.Icon("name", image, "My System Tray Icon", menu) icon.run_detached() But I received this error: Exception in thread Thread-2: Traceback (most recent call last): File "...\lib\threading.py", line 973, in _bootstrap_inner self.run() File "...\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "...\lib\site-packages\pystray\_base.py", line 384, in <lambda> threading.Thread(target=lambda: self.run(setup)).start() NameError: name 'setup' is not defined So I tried to bypass this error by changing the line 384 in _base.py removing the setup variable #threading.Thread(target=lambda: self.run(setup)).start() threading.Thread(target=lambda: self.run()).start() The code worked like expected and created the tray icon with the menu buttons working properly. The problem is when I press quit because the stop() function is not working like when I use icon.run() . The the thread appears to keep running and the tray icon stay frozen and the program don't end. Is there another way to make this work properly? |
Linq to datatable with unknown columns Posted: 26 Nov 2021 11:01 AM PST I am having SQL query like this (will be parametrized once I make this work): using (FbCommand cmd = new FbCommand("SELECT MAGACINID, ROBAID, SUM(KOLICINA) AS GOD" + godina.ToString() + " FROM STAVKA WHERE VRDOK = 13 OR VRDOK = 15 GROUP BY MAGACINID, ROBAID ORDER BY ROBAID", con)) { using (FbDataAdapter da = new FbDataAdapter(cmd)) { DataTable tempDT = new DataTable(); if (dt.Rows.Count == 0) { da.Fill(dt); continue; } da.Fill(tempDT); var result = dt.AsEnumerable() .Join(tempDT.AsEnumerable(), x => new { field1 = x["MAGACINID"], field2 = x["ROBAID"] }, y => new { field1 = y["MAGACINID"], field2 = y["ROBAID"] }, (x, y) => new { x, addYear = y["GOD" + godina.ToString()] }); dt = LINQResultToDataTable(result); } } And here is LINQResultToDataTable() method private DataTable LINQResultToDataTable<T>(IEnumerable<T> Linqlist) { DataTable dt = new DataTable(); PropertyInfo[] allColumns = null; if (Linqlist == null) return dt; foreach (T Record in Linqlist) { if (allColumns == null) { allColumns = ((Type)Record.GetType()).GetProperties(); // Record at position 0 is whole object and needs to be broke into pieces // Record at position 1 is new column foreach (PropertyInfo GetProperty in allColumns) { Type colType = GetProperty.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(new DataColumn(GetProperty.Name, colType)); } } DataRow dr = dt.NewRow(); foreach (PropertyInfo pinfo in allColumns) { dr[pinfo.Name] = pinfo.GetValue(Record, null) == null ? DBNull.Value : pinfo.GetValue (Record, null); } dt.Rows.Add(dr); } return dt; } First datatable fill is okay and it fills it with these columns: MagacinID RobaID God2021 Now when I try to join new table using linq I should only add God2020 as new column. Problem is that when I am creating output of linq I cannot tell it to break x object into columns but I need to take it whole so linq result looks like this: x (this one have ItemArray with all columns) God2020 And new datatable looks same. What I tried doing is inside LINQResultToDataTable method to take 0th element of Result and break it into columns, add to datatable, add new one (1st element) and populate it (see comment in that method) but I am stuck and do not know how to do that. Anyone have any solution? Edit: I made it not clear so here is more explanation. I have foreach loop which loops through 5 databases and inside that foreach loop is this code. First database returns these columns MagacinID RobaID God2021 Second MagacinID RobaID God2020 Third MagacinID RobaID God2019 Fourth MagacinID RobaID God2018 Fifth MagacinID RobaID God2017 I want all this merged into one datatable on columns MagacinID AND RobaID like this: MagacinID RobaID God2021 God2020 God2019 God2018 God2017 |
What can function named ReadWrite do in SPI communication? Posted: 26 Nov 2021 11:01 AM PST I'm using MPSSE library to have SPI communication via PC. There are 3 main functions which handle communcation via SPI: SPI_Read - for reading SPI_Write - for writing and the third one SPI_ReadWrite described as this function reads from and writes to the SPI slave simultaneously. Meaning that one bit is clocked in and one bit is clocked out during every clock cycle. and I can't get the difference between them like in SPI signals... What's the purpose of using it, if in SPI we need to serially do writing and reading |
Negate a character group to replace all other characters Posted: 26 Nov 2021 11:03 AM PST I have the following string: "Thu Dec 31 22:00:00 UYST 2009" I want to replace everything except for the hours and minutes so I get the following result: "22:00" I am using this regex : (^([0-9][0-9]:[0-9][0-9])) But its not matching anything. This would be my line of actual code : println("Thu Dec 31 22:00:00 UYST 2009".replace("(^([0-9][0-9]:[0-9][0-9]))".toRegex(),"")) Can someone help me to correct the regex? |
Style inherittance between different target types Posted: 26 Nov 2021 11:02 AM PST I don't know if I am just not understanding right. I am trying to make 2 different button styles for my application: BlueOnWhiteButton and WhiteOnBlueButton. Both these buttons should be identical, but the foreground and backgrounds are reversed. So far, oh so simple. Here is the catch: I need my buttons to have rounded corners. This simple requirement doesn't seem to be so simple after all. Also there maybe a little border of a different color on both versions. Using some things I found on google and stack, I came up with this style for the first one, and it looked promising: <Style x:Key="WhiteOnBlueButton" TargetType="Button"> <Setter Property="Background" Value="{StaticResource MainBlue}" /> <Setter Property="Foreground" Value="White" /> <Setter Property="FontWeight" Value="bold" /> <Style.Resources> <Style TargetType="Border"> <Setter Property="CornerRadius" Value="5" /> <Setter Property="BorderThickness" Value="2" /> <Setter Property="BorderBrush" Value="{StaticResource LightBlue}" /> </Style> </Style.Resources> </Style> So far so good, my button looks how I want it. But then, when I try to make a second style underneath, I get an error at runtime because of the Style.Resources redefine. I'll save you the code block, figure the same with a different name and reversed colors. I am trying to keep the use of the style as simple as possible, I have tried versions with templates, but it made the style a lot more complicated, and I even lost the button text... What I would like to have is something like this: <Style x:Key="RoundedButtonCornersNoBorder" TargetType="Border"> <Setter Property="CornerRadius" Value="4"/> <Setter Property="BorderThickness" Value="0" /> </Style> <Style x:Key="RoundedButtonCorners" TargetType="Border"> <Setter Property="CornerRadius" Value="4"/> <Setter Property="BorderBrush" Value="{StaticResource LightBlue}" /> <Setter Property="BorderThickness" Value="2" /> </Style> <Style x:Key="WhiteOnBlueButton" TargetType="Button"> <Setter Property="Background" Value="{StaticResource MainBlue}" /> <Setter Property="Foreground" Value="White" /> <Setter Property="FontWeight" Value="bold" /> <!-- Somehow tell the borders should be taken from the style RoundedButtonCornersNoBorder--> </Style> <Style x:Key="BlueOnWhiteButton" TargetType="Button"> <Setter Property="Background" Value="White" /> <Setter Property="Foreground" Value="{StaticResource MainBlue}" /> <Setter Property="FontWeight" Value="bold" /> <!-- Somehow tell the borders should be taken from the style RoundedButtonCorners--> </Style> Is there any way to code that without writing 300 lines of incomprehensible code? The final goal is to apply the style by simply doing: <Button Style="{DynamicResource WhiteOnBlueButton}" Content="CLICK ME!" /> |
Is Cron Expression 5 or 6 or 7 field string? Posted: 26 Nov 2021 11:01 AM PST While learning about Cron expressions for the purpose in azure functions timer trigger, I came across a confusion about length of cron expression. - According to this blog, cron expression is 6 or 7 field string where last field is optional.
- According to this blog, cron expression is 5 field string.
To understand cron expression clearly, I'm using this site to convert the expression to readable format where it is allowing only 5 fields here. So, I was bit confused to understand whether it is a 5 or 6 or 7 field expression. Could anyone help me about the length of cron expression and if possible, any best document about this cron expression learning? Thank you in advance! |
Spring Boot fails to start up: Could not generate CGLIB subclass of class BasicErrorController Posted: 26 Nov 2021 11:01 AM PST I'm upgrading our Spring-Boot application (2.5.6) to use Java 17 and we are going from amazoncorretto:11-al2-jdk to amazoncorretto:17-al2-jdk which uses distribution of OpenJDK 17. After bumping our Docker base image to amazoncorretto:17-al2-jdk and wrap all up in a docker image, the application fails to start up due to: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$aee9141f. Based on the error message it seems that Spring tries to generate a subclass of BasicErrorController but fails due to attempted duplicate class definition . (The BasicErrorController comes from a Spring-Boot library). I have tried reading up on the CGLIB logic but I can not figure out whats wrong/duplicated class (and I can not find any final classes as the error message suggestion implies). Any ideas what I can do to resolve this issue? When I run the application directly from the IntelliJ IDE using the same jdk17 as in the docker image, it works fine. edit: some more logs with stacktraces and DEBUG level enabled DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration' via constructor to bean named 'org.springframework.web.context.support.AnnotationConfigWebApplicationContext@5b40de43' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration' via constructor to bean named 'spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration' via constructor to bean named 'spring.web-org.springframework.boot.autoconfigure.web.WebProperties' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'errorAttributes' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'basicErrorController' DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'basicErrorController' via factory method to bean named 'errorAttributes' WARN org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'basicErrorController' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'basicErrorController' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') ... suppressed 17 lines at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183) ~[?:?] at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[?:?] at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[?:?] at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:276) ~[?:?] at java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:3215) ~[?:?] at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[?:?] at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[?:?] at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150) ~[?:?] at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173) ~[?:?] at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:?] at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596) ~[?:?] ... suppressed 9 lines at java.lang.Iterable.forEach(Iterable.java:75) [?:?] ... suppressed 8 lines at xxx.xxx.Application.main(Application.java:62) [classes!/:?] ... suppressed 8 lines Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') ... suppressed 8 lines ... 54 more Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') ... suppressed 22 lines ... 54 more Caused by: java.lang.LinkageError: loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') at java.lang.ClassLoader.defineClass0(Native Method) ~[?:?] at java.lang.System$2.defineClass(System.java:2307) ~[?:?] at java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2439) ~[?:?] at java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2416) ~[?:?] at java.lang.invoke.MethodHandles$Lookup.defineClass(MethodHandles.java:1843) ~[?:?] ... suppressed 25 lines ... 54 more org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'basicErrorController' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170) at javax.servlet.GenericServlet.init(GenericServlet.java:203) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1164) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1013) at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.load(TomcatEmbeddedContext.java:82) at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183) at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:276) at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:3215) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150) at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173) at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596) at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.lambda$deferredLoadOnStartup$0(TomcatEmbeddedContext.java:65) at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.doWithThreadContextClassLoader(TomcatEmbeddedContext.java:106) at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.deferredLoadOnStartup(TomcatEmbeddedContext.java:64) at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.performDeferredLoadOnStartup(TomcatWebServer.java:305) at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:216) at org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle.start(WebServerStartStopLifecycle.java:43) at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) at java.base/java.lang.Iterable.forEach(Iterable.java:75) at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) at xxx.xxx.application.Application.main(Application.java:62) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:209) at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:478) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:342) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1808) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ... 54 more Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:580) at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:363) at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:585) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108) at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134) at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319) at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:572) at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:419) at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57) at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:206) ... 61 more Caused by: java.lang.LinkageError: loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2 attempted duplicate class definition for org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57. (org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController$$EnhancerBySpringCGLIB$$3b1a7b57 is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @17a7cec2, parent loader 'app') at java.base/java.lang.ClassLoader.defineClass0(Native Method) at java.base/java.lang.System$2.defineClass(System.java:2307) at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2439) at java.base/java.lang.invoke.MethodHandles$Lookup$ClassDefiner.defineClass(MethodHandles.java:2416) at java.base/java.lang.invoke.MethodHandles$Lookup.defineClass(MethodHandles.java:1843) at java.base/jdk.internal.reflect.GeneratedMethodAccessor39.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:577) ... 75 more ... WARN org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server DEBUG org.springframework.data.redis.listener.RedisMessageListenerContainer - Stopped RedisMessageListenerContainer INFO org.springframework.scheduling.quartz.SchedulerFactoryBean - Shutting down Quartz Scheduler DEBUG org.springframework.scheduling.quartz.LocalDataSourceJobStore - JobStore background threads shutdown. DEBUG org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Shutting down ExecutorService 'taskScheduler' DEBUG org.springframework.security.web.FilterChainProxy - Securing GET /ping DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - Set SecurityContextHolder to empty SecurityContext DEBUG org.springframework.security.web.FilterChainProxy - Secured GET /ping DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - Cleared SecurityContextHolder to complete request INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'web' |
Avalonia ReactiveUI RoutedViewHost not creating embedding appropriate view Posted: 26 Nov 2021 11:03 AM PST I was following this tutorial, which I do see is based on the .net core 2.1 framework , but adapted for the .net 5 avalonia.mvvm template. I followed the code line for line with the exception of the Program.cs file given the fact that the avalonia.mvvm template in .net 5 implements the ViewLocator.cs class so I don't believe I have to use Locator . Yet, when I run the app while the Router.NavigationStack.Count increments, the view remains on its default content. Here is the code /// MainWindow.axaml <Design.DataContext> <vm:MainWindowViewModel/> </Design.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <rxui:RoutedViewHost Grid.Row="0" Router="{Binding Router}" PageTransition="{x:Null}"> <rxui:RoutedViewHost.DefaultContent> <TextBlock Text="Main Window" HorizontalAlignment="Center" VerticalAlignment="Center" /> </rxui:RoutedViewHost.DefaultContent> </rxui:RoutedViewHost> <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="15"> <StackPanel.Styles> <Style Selector="StackPanel > :is(Control)"> <Setter Property="Margin" Value="2"/> </Style> <Style Selector="StackPanel > TextBlock"> <Setter Property="VerticalAlignment" Value="Center"/> </Style> </StackPanel.Styles> <Button Content="Go next" Command="{Binding GoNext}" /> <Button Content="Go back" Command="{Binding GoBack}" /> <TextBlock Text="{Binding Router.NavigationStack.Count}" /> </StackPanel> </Grid> //MainWindowViewModel.cs public class MainWindowViewModel : ViewModelBase, IScreen { public RoutingState Router { get; } = new RoutingState(); public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; } public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack; public MainWindowViewModel() { GoNext = ReactiveCommand.CreateFromObservable( () => Router.Navigate.Execute(new CommandCenterViewModel(this)) ); } } //CommandCenterView.axaml <UserControl xmlns="https://github.com/avaloniaui" xmlns:vm="using:GuiClient.ViewModels" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="GuiClient.Views.CommandCenterView"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock x:Name="PathTextBlock" Text="Hi, I'm the first view!" /> <TextBlock Text="{Binding UrlPathSegment}" /> </StackPanel> </UserControl> ///CommandCenterViewModel.cs public class CommandCenterViewModel : ViewModelBase, IRoutableViewModel { public string UrlPathSegment { get; } = Guid.NewGuid().ToString().Substring(0, 5); public IScreen HostScreen { get; } public CommandCenterViewModel(IScreen screen) => HostScreen = screen; } //ViewLocator.cs in case this is relevant public class ViewLocator : IDataTemplate { public IControl Build(object data) { var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { return (Control)Activator.CreateInstance(type)!; } else { return new TextBlock { Text = "Not Found: " + name }; } } public bool Match(object data) { return data is ViewModelBase; } } Tried digging around online and couldn't find anyone who'd ran into the same issue. I'd appreciate help/being pointed in the right direction. Thanks! |
Registering a face in the system of the project made with opencv [closed] Posted: 26 Nov 2021 11:01 AM PST How do I register certain faces in opencv system? |
In Progress Telerik Fiddler Web Debugger is there a way to adjust Content-Length automatically in AutoResponder? Posted: 26 Nov 2021 11:03 AM PST I am using fiddler autoresponder to return a different JS file than the one loaded from my server originally. The adjusted file uses: HTTP/1.1 200 OK Cache-Control: private, max-age=31536000 Content-Type: application/javascript ...other headers Content-Length: 37010 ...the javascript code At the top of the file, this Content-Length header is not automatically adjusted to the edited file though. So I have to try and load my changes, my app will crash because the Content-Length is wrong, but then I check fiddlers 'transformer' tab to see how many bytes my request body actually is, update that in my modified file, refresh again and then it works. I have tried to change the encoding to chunked, so that I could leave out the Content-Length header, but I don't think my app knows how to decode chunked for some reason. So my question is, is there any way to automatically update the Content-Length in the auto-responder? |
Can JNA be used for a complex Windows DLL like IMAPI Posted: 26 Nov 2021 11:02 AM PST I've managed to get COM4J to use some functionality in the windows IMAPI (CD writing). However I've failed to get any of the calls that return SAFEARRAYs working, but this project doesn't appear to be currently active ... The DLL is usually in C:\Windows\System32\imapi2.dll, and using it also requires using C:\Windows\System32\imapi2fs.dll Looking around for a JAVA-COM bridge project that is active led me to JNA. The remit of the project to simplify JAVA-COM bridging intrigued me .... however I fell at the first hurdle, and am hoping someone can help. So far I've taken the Microsoft IMAPI examples and written a Powershell application, from which I have the series of calls I need to make to the API.[CDInterface][1] The first thing you need to do with IMAPI is create an Instance of IDiskMaster2, so I've declared that via an Imapi2 interface, like so public interface Imapi2 extends Library { Imapi2 INSTANCE = (Imapi2) Native.load("C:/Windows/System32/imapi2.dll" , Imapi2.class); public static class IDiscMaster2 extends Structure { int getCount; public int getCount() { return getCount; } } IDiscMaster2 createMsftDiscMaster2(); } Then in the main code Imapi2.IDiscMaster2 recorderList = Imapi2.INSTANCE.createMsftDiscMaster2(); System.out.println("Found " + recorderList.getCount() + " Recorders"); Just putting 'imapi2' in the call to Native.load() didn't work either. I'm guessing I'm doing something fundamentally wrong, but it's not clear how you get JNA to 'see' a new dll you want to interface to ..... and also I am kind of afraid there is something very different about this API from the othe APIs that people are using JNA to talk to, so may not be worth trying! public interface Imapi2 extends Library { Imapi2 INSTANCE = (Imapi2) Native.load("C:/Windows/System32/imapi2.dll" , Imapi2.class); public class IDiscMaster2 extends Dispatch { public static final CLSID CLSID_MsftDiscMaster2 = new CLSID("2735412F-7F64-5B0F-8F00-5D77AFBE261E"); public IDiscMaster2() { } private IDiscMaster2(Pointer pvInstance) { super(pvInstance); } public static IDiscMaster2 create() { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT hres = Ole32.INSTANCE.CoCreateInstance(CLSID_MsftDiscMaster2, null, WTypes.CLSCTX_ALL, null, pbr); if (COMUtils.FAILED(hres)) { System.out.println("ERROR: Failed to create instance"); return null; } return new IDiscMaster2(pbr.getValue()); } public WinNT.HRESULT _getCount(Pointer count ){ return (WinNT.HRESULT) _invokeNativeObject(2, new Object[]{count}, WinNT.HRESULT.class); } public long getCount() { try { long count = -1; Pointer ptr = new Pointer(count); WinNT.HRESULT result = _getCount(ptr); COMUtils.checkRC(result); return count; } catch ( Exception e ) { System.out.println("Error : " + e.getMessage()); } return -1; } } Then invocation in main changed to Imapi2 imapi2Lib = Imapi2.INSTANCE; Imapi2.IDiscMaster2 recorderList = new Imapi2.IDiscMaster2(); System.out.println("Found " + recorderList.getCount() + " Recorders"); IntelliJ shows up uninvoked methods, so it doesn't look like create() is getting called. Not sure if this is because I need to call it, or down to the function implementing IDispatch not IUnknown. [1]: https://github.com/nosdod/CDInterface |
In Blazor, is there a way to undo invalid user input, without changing the state? Posted: 26 Nov 2021 11:02 AM PST In Blazor, how can I undo invalid user input, without changing the state of the component to trigger a re-render? Here is a simple Blazor counter example (try it online): <label>Count:</label> <button @onclick=Increment>@count times!</button><br> A: <input @oninput=OnChange value="@count"><br> B: <input @bind-value=count @bind-value:event="oninput"> @code { int count = 1; void Increment() => count++; void OnChange(ChangeEventArgs e) { var userValue = e.Value?.ToString(); if (int.TryParse(userValue, out var v)) { count = v; } else { if (String.IsNullOrWhiteSpace(userValue)) { count = 0; } // if count hasn't changed here, // I want to re-render "A" // this doesn't work e.Value = count.ToString(); // this doesn't work either StateHasChanged(); } } } For input element A, I want to replicate the behavior of input element B, but without using the bind-xxx -style data binding attributes. E.g., when I type 123x inside A, I want it to revert back to 123 automatically, as it happens with B. I've tried StateHasChanged but it doesn't work, I suppose, because the count property doesn't actually change. So, basically I need to re-render A to undo invalid user input, even thought the state hasn't changed. How can I do that without the bind-xxx magic? Sure, bind-xxx is great, but there are cases when a non-standard behavior might be desired, built around a managed event handler like ChangeEvent . Updated, to compare, here's how I could have done it in React (try it online): function App() { let [count, setCount] = useState(1); const handleClick = () => setCount((count) => count + 1); const handleChange = (e) => { const userValue = e.target.value; let newValue = userValue ? parseInt(userValue) : 0; if (isNaN(newValue)) newValue = count; // re-render even when count hasn't changed setCount(newValue); }; return ( <> Count: <button onClick={handleClick}>{count}</button><br/> A: <input value={count} onInput={handleChange}/><br/> </> ); } Also, here's how I could have done it in Svelte, which I find conceptually very close to Blazor (try it online). <script> let count = 1; const handleClick = () => count++; const handleChange = e => { const userValue = e.target.value; let newValue = userValue? parseInt(userValue): 0; if (isNaN(newValue)) newValue = count; if (newValue === count) e.target.value = count; // undo user input else count = newValue; } }; </script> Count: <button on:click={handleClick}>{count}</button><br/> A: <input value={count} on:input={handleChange}/><br/> Updated, to clarify, I simply want to undo whatever I consider an invalid input, retrospectively after it has happened, by handling the change event, without mutating the component's state itself (counter here). That is, without Blazor-specific two-way data binding, HTML native type=number or pattern matching attributes. I simply use the number format requirement here as an example; I want to be able to undo any arbitrary input like that. The user experience I want (done via a JS interop hack): https://blazorrepl.telerik.com/wPbvcvvi128Qtzvu03 Surprised this so difficult in Blazor compared to other frameworks, and that I'm unable to use StateHasChanged to simply force a re-render of the component in its current state. |
What should we have as output for model.evaluate Posted: 26 Nov 2021 11:02 AM PST I started tensorflow not long ago and I am currently working on CNNs and particularly on sign-language mnist to recognize sign language. After creating and running my model I evaluate it with model.evaluate with 7172 images. The problem is that at the output of the evaluator I have 7172/1 which in my opinion should be 7172/7172. In addition, I have a much too long verbose in my opinion. I've tried changing several settings in my model but nothing works. Can someone help me understand this problem better? 1.here is a portion of my code training_images = np.expand_dims(training_images, axis = 3) testing_images = np.expand_dims(testing_images, axis = 3) train_datagen = ImageDataGenerator(rescale = 1./255, horizontal_flip = True, rotation_range = 40, width_shift_range=0.2, height_shift_range=0.2, shear_range = 0.2, fill_mode ='nearest', zoom_range = 0.2) validation_datagen = ImageDataGenerator(rescale = 1./255) model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation = tf.nn.relu), tf.keras.layers.Dense(26,activation = tf.nn.softmax)]) model.compile(optimizer=tf.optimizers.Adam(),loss = 'sparse_categorical_crossentropy', metrics =['accuracy']) history = model.fit_generator(train_datagen.flow(training_images, training_labels, batch_size = 32), steps_per_epoch=len(training_images) / 32, epochs = 15, validation_data = validation_datagen.flow(testing_images, testing_labels,batch_size = 32), validation_steps=len(testing_images) / 32) model.evaluate(testing_images, testing_labels) 2.And here the exit that I get 7172/1[=====================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================] - 2s 218us/sample - loss: 277.3631 - accuracy: 0.4357 |
Override the default icon from mat-stepper angular material Posted: 26 Nov 2021 11:01 AM PST |
Visual Studio 2013 Web Deploy fails Posted: 26 Nov 2021 11:01 AM PST I just installed VS 2013, upgrading from VS 2010. Creating a web deployment package zip file used to work in 2010. using VS 2013's Publish Web feature to publish to a Web Deploy Package, I getting the following error: Web deployment task failed. (Object of type 'manifest' and path 'D:\dev\DMWeb\DMWebClient\obj\Test\Package\DMWebClient.SourceManifest.xml' cannot be created. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_EXCEPTION_WHILE_CREATING_OBJECT.) The details in the Web Publish Activity tab shows the following: Transformed Web.config using D:\dev\DMWeb\DMWebClient\Web.Test.config into obj\Test\TransformWebConfig\transformed\Web.config. Auto ConnectionString Transformed Views\Web.config into obj\Test\CSAutoParameterize\transformed\Views\Web.config. Auto ConnectionString Transformed obj\Test\TransformWebConfig\transformed\Web.config into obj\Test\CSAutoParameterize\transformed\Web.config. Copying all files to temporary location below for package/publish: obj\Test\Package\PackageTmp. Packaging into D:\dev\DMWeb\DMWebClient\obj\Test\Package\DMWebClient.zip. C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(3883,5): Error ERROR_EXCEPTION_WHILE_CREATING_OBJECT: Web deployment task failed. (Object of type 'manifest' and path 'D:\dev\DMWeb\DMWebClient\obj\Test\Package\DMWebClient.SourceManifest.xml' cannot be created. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_EXCEPTION_WHILE_CREATING_OBJECT.) Package failed. In VS 2010, I've had to run it as Administrator for deploy to work, and I'm doing so here as well. I've also tried giving Full Control permissions to the project folder to NETWORK SERVICE, LOCAL SERVICE, Authenticated Users, and myself. In the Package folder, there is the PackageTmp folder (which looks good), and the DMWebClient.SourceManifest.xml file, and that's it. In VS 2010, there's more files there. DMWebClient.SourceManifest.xml contains: <?xml version="1.0" encoding="utf-8"?> <sitemanifest> <IisApp path="D:\dev\DMWeb\DMWebClient\obj\Test\Package\PackageTmp" /> <setAcl path="D:\dev\DMWeb\DMWebClient\obj\Test\Package\PackageTmp" setAclResourceType="Directory" /> <setAcl path="D:\dev\DMWeb\DMWebClient\obj\Test\Package\PackageTmp" setAclUser="anonymousAuthenticationUser" setAclResourceType="Directory" /> <setAcl path="D:\dev\DMWeb\DMWebClient\obj\Test\Package\PackageTmp\App_Data" setAclResourceType="Directory" setAclAccess="Write" /> <setAcl path="D:\dev\DMWeb\DMWebClient\obj\Test\Package\PackageTmp/DMWeb.config" setAclResourceType="File" setAclAccess="Read,Write" /> </sitemanifest> In VS 2010, the last line containing DMWeb.config doesn't exist. On top of that, the path to it is wrong. It should be under the App_Data folder. DMWeb.config is specified in Web.config like this: <appSettings file="DMWeb.config"> Any help would be greatly appreciated. |
how to change the collate to all the columns of the database? Posted: 26 Nov 2021 11:01 AM PST I would like to change the collation of all the columns of all the tables of my database. In stack overflow, I have found this script: (post) SELECT 'ALTER TABLE [' + SYSOBJECTS.Name + '] ALTER COLUMN [' + SYSCOLUMNS.Name + '] ' + SYSTYPES.name + CASE systypes.NAME WHEN 'text' THEN ' ' ELSE '(' + RTRIM(CASE SYSCOLUMNS.length WHEN -1 THEN 'MAX' ELSE CONVERT(CHAR,SYSCOLUMNS.length) END) + ') ' END + ' ' + ' COLLATE Latin1_General__CI_AI ' + CASE ISNULLABLE WHEN 0 THEN 'NOT NULL' ELSE 'NULL' END FROM SYSCOLUMNS , SYSOBJECTS , SYSTYPES WHERE SYSCOLUMNS.ID = SYSOBJECTS.ID AND SYSOBJECTS.TYPE = 'U' AND SYSTYPES.Xtype = SYSCOLUMNS.xtype AND SYSCOLUMNS.COLLATION IS NOT NULL AND NOT ( sysobjects.NAME LIKE 'sys%' ) AND NOT ( SYSTYPES.name LIKE 'sys%' ) GO However, when I see the collation of the columns I see that the collation is the old collation. The actual collation is AS, so I can have "ANIMAL" and "ÁNIMAL". When I execute the script, I don't get any error. I think that I would get an error because the new collation is AI. So this makes me think that the script does nothing. How can I change the collation of all the columns of all my tables in the database? Thanks. |
No comments:
Post a Comment