Q: Entity Framework n to n relationship add object to another object I have a Model with Clients:
public class Client

{
    [Key]
    public int id { get; set; }
    [Required]
    public string? Hostname { get; set; }
    public ICollection<Software>? Softwares { get; set; }

}

And a Model with Software:
public class Software
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        public string Name { get; set; }
        public ICollection<Client>? Clients { get; set; }
    }

This is supposed to be an n to n connection. How can I add software to my clients?
What I've tried:
public async void add(Software software)
        {
            using (var repo = new ClientRepository(contextFactory.CreateDbContext()))
            {
                client.Softwares.Add(software);
                await repo.Save(client);
            }

Repository:
public async Task Save(Client client)
        {
            _context.Clients.Update(client);
            _context.SaveChanges();
        }
        }

This works for the first software I add, but gives me the following error if I try to add a second one:

SqlException: Violation of PRIMARY KEY constraint 'PK_ClientSoftware'.
Cannot insert duplicate key in object 'dbo.ClientSoftware'. The
duplicate key value is (7003, 5002).

A: It seems you are adding more than one relation of the same. Before adding software to a client, make sure a relation does not exist yet, then you can go ahead and add software to client.
Also, you can improve your entities. Use better naming for the primary keys and add [Key] attribute to Software class as well.
Client:
public class Client
{
    public Client()
    {
        Softwares = new HashSet<Software>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ClientId { get; set; }
    [Required]
    public string Hostname { get; set; }
    public ICollection<Software> Softwares { get; set; }
}

Software:
public class Software
{
    public Software()
    {
        Clients = new HashSet<Client>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int SoftwareId { get; set; }
    public string Name { get; set; }
    public ICollection<Client> Clients { get; set; }
}

Check if relation already exists:
// Get the client including its related softwares
var client = dbContext.Clients.Include(x => x.Softwares)
    .FirstOrDefault(x => x.Hostname == "Ibrahim");

if (client != null)
{
    // Check with unique property such as name of software
    // If it does not exist in this current client, then add software
    if (!client.Softwares.Any(x => x.Name == software.Name))
        client.Softwares.Add(software);

    dbContext.SaveChanges();
}

Note: If you update your entities, remember to create new migration and database.

A:
Q: Do you make a new one with new() every time?

A: no, its a software that already exists

Then that is the error.
The first SaveChanges() will start tracking it as Existing. You can check: The Id will be != 0.
When you then later add it to the same Client you'll get the duplicate error.
So somewher in your code:
  await add(software);       // existing
  software = new Software(); // add this

Related, change:
public async void add(Software software)

to
public async Task Add(Software software)

Always avoid async void.


Q: List private property names of the class I need to use some subset of class properties names as values in a map to use inside of the class. In following example I've replaced map by array. The problem is that if property is marked private it's not listed in keyof list. How can I specify type of keys if I need to include private names?
var keys: Array<keyof A> = ["x", "y"]; // Error

class A {
  private x = 7;
  public y = 8;

  private keys: Array<keyof A> = ["x", "y"]; // Error
}

There is the same error both for variable outside of the class and for private property inside of it:

Type '"x"' is not assignable to type '"y"'.

A: As you noticed, private and protected properties of a class C do not appear as part of keyof C.  This is usually desirable behavior, since most attempts to index into a class with a private/protected property will cause a compile error.  There is a suggestion at microsoft/TypeScript#22677 to allow mapping a type to a version where the private/protected properties are public, which would give you a way to do this... but this feature has not been implemented as of TypeScript 4.9.
So this doesn't work:
namespace Privates {
  export class A {
    private x: string = "a";
    public y: number = 1;
    private keys: Array<keyof A> = ["x", "y"]; // Error
  }
  var keys: Array<keyof A> = ["x", "y"]; // Error
}
const privateA = new Privates.A();
privateA.y; // number
privateA.x; // error: it's private
privateA.keys; // error: it's private

But maybe you don't actually need the properties to be private, so much as not visible to outside users of the class.  You can use a module/namespace to export only the facets of your class that you want, like this:
namespace NotExported {
  class _A {
    x: string = "a";
    y: number = 1;
    keys: Array<keyof _A> = ["x", "y"]; // okay
  }
  export interface A extends Omit<_A, "x" | "keys"> {}
  export const A: new () => A = _A;
  var keys: Array<keyof _A> = ["x", "y"]; // okay
}

const notExportedA = new NotExported.A();
notExportedA.y; // number
notExportedA.x; // error: property does not exist
notExportedA.keys; // error: property does not exist

In NotExported, the class constructor _A and the corresponding type _A are not directly exported.  Internally, keyof _A contains both the "x" and "y" keys.  What we do export is a constructor A and a corresponding type A that omits the x property (and keys property) from _A.  So you get the internal behavior you desire, while the external behavior of NotExported.A is similar to that of Privates.A.  Instead of x and keys being inaccessible due to private violation, they are inaccessible because they are not part of the exported A type.
I actually prefer the latter method of not exporting implementation details rather than exposing the existence of private properties, since private properties actually have a lot of impact on how the corresponding classes can be used.  That is, private is about access control, not about encapsulation.
Link to code


Q: Get div content and then modify it The scenario is, I want to get a div content and then  modify it in order to insert it in another div.
Code below :
$("#loupe").live("click",function(){
    $('#divBody').empty();
    $('#divTitle').empty();
    var title = $(this).closest('div').find('.stepTitle').text();
    var divContent = $(this).closest('div').html();
    // code to modify the content to be inserted in the modal
    $('#divBody').append(divContent);
    $('#divTitle').append(title);
    $('#div').modal({ dynamic: true });
});

more in detail , the first div contains a title that i want to remove before inserting content into the new div , so the new div must contains content without title

Planing des congés pour le service de <%=service.getNomService() %> au <%=month%> / <%=year%>

//************the div into which content will be inserted

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

            //here the title

        here the other content

        <input type="button" class="btn" class="close" data-dismiss="modal" value="fermer">

A: jQuery allows you to work with fragments of a page (as well as XML).
Once you've used the .html method to assign the HTML of an element to a variable, you can operate on the HTML like so:
var html, withoutTitle;
html = $('#someDiv').html();
withoutTitle = $(html).remove('#title').html();
$('#someOtherDiv').html(withoutTitle);

I haven't tested this code, so you may need to tweak it a bit to suit your purposes.


Q: Sequentially arranged and add placeholders in text file I have a text file which contains data. There are 3 columns, each column starts at a specific location and ends a specific location in the file. The first column which is (300, 301, 302, 304...) is always number based. the second column is a string, and the last column is currency.
The current .txt file is missing numbers which is (303, 305).
I was able to find the missing numbers and add it to an array then write it to the file.
My goal is to write all the columns data sequentially to the text file even the missing ones. As for column 2 and 3, I want 0 to be the placeholder for the missing data and aligned with its own column.
I'm close but need help
   //read file
   string[] lines = File.ReadAllLines(FilePath);
   var Numbers = new List<int>();
   int i = 0;
   foreach (var line in lines)
   {
       //get value of first column
       var FirstColumn = line.Substring(0, 3);
       //add it to array
       Numbers.Add(Convert.ToInt32(FirstColumn));
       ++i;
   }
   //find missing numbers add to array
   var result = Enumerable.Range(Numbers.Min(), Numbers.Count);

   //write to file
   using (StreamWriter file = new StreamWriter(OutPutFile, true))
   {
       foreach (var item in result.ToArray())
       {
           file.WriteLine(item);
       }
   }

   Console.ReadKey();

Current .txt file
300     Family Guy      1,123
301     Dexters Lab     456
302     Rugrats         1,789.52
304     Scooby-Doo      321
306     Recess          2,654
307     Popeye          1,987.02

GOAL: Desired Output .txt file
300     Family Guy      1,123
301     Dexters Lab     456
302     Rugrats         1,789.52
303     0               0
304     Scooby-Doo      321
305     0               0
306     Recess          2,654
307     Popeye          1,987.02

A: You are reading the first column, but not the rest.  What I do is create a dictionary, using the first number as the index, and stuffing the other two fields into a System.ValueTuple (you need to include the ValueTyple Nuget package to get this to work).
First I set some stuff up:
 const int column1Start = 0;
 const int column1Length = 3;
 const int column2Start = 8;
 const int column2Length = 15;
 const int column3Start = 24;

 int indexMin = int.MaxValue;     //calculated during the first
 int indexMax = int.MinValue;     //pass through the file

Then I create my dictionary.  That (string, decimal) syntax describes a 2-tuple that contains a string and a decimal number (kind of like the ordered-pairs you were taught about in high school).
 Dictionary<int, (string, decimal)> data = new Dictionary<int, (string, decimal)>();

Then I make a pass through the file's lines, reading through the data, and stuffing the results in my dictionary (and calculating the max and min values for that first column):
 var lines = File.ReadAllLines(fileName);
 foreach (var line in lines) {
     //no error checking
     var indexString = line.Substring(column1Start, column1Length);
     var cartoon = line.Substring(column2Start, column2Length).TrimEnd();
     var numberString = line.Substring(column3Start);

     if (int.TryParse(indexString, out var index)) {
         //I have to parse the first number - otherwise there's nothing to index on
         if (!decimal.TryParse(numberString, out var number)){
             number = 0.0M;
         }
         data.Add(index, (cartoon, number));

         if (index < indexMin) {
             indexMin = index;
         }
         if (index > indexMax) {
             indexMax = index;
         }
     }
 }

Finally, with all my data in hand, I iterate from the min value to the max value, fetching the other two columns out of my dictionary:
 for (int i = indexMin; i <= indexMax; ++i) {
     if (!data.TryGetValue(i, out var val)){
         val = ("0", 0.0M);
     }
     Console.WriteLine($"{i,5}  {val.Item1,-column2Length - 2}  {val.Item2, 10:N}");
 }

My formatting isn't quite the same as yours (I cleaned it up a bit).  You can do what you want.  My results look like:
  300  Family Guy           1,123.00
  301  Dexters Lab            456.00
  302  Rugrats              1,789.52
  303  0                        0.00
  304  Scooby-Doo             321.00
  305  0                        0.00
  306  Recess               2,654.00
  307  Popeye               1,987.02


Q: Automatically abbreviate the length string in matplotlib Is there a way to automatically reduce the length of string in matplotlib if it conflicts with neighboring texts such as in:

What I'm looking for is if matplotlib detects a conflict with another text, it automatically reduce the texts in order for all the texts to be readable.
Note that one could of course rotate the labels or make the fontsize smaller to prevent overlap. But here I'm asking how to cut the text in case of overlap.


Q: C# Visual Studio 2013 suppress 'Class is never instantiated' I have a web api project which accepts HttpPost communications.
The controller's methods always accepting a single validated object.
For example:
public sealed class NumbersRequest
{
    [NumberOne]
    public string Number1 { get; set; }

    [NumberTwo]
    public string Number2 { get; set; }
}

Since I never declare NumbersRequest req = new NumbersRequest() and they only serve as a request object, Im getting the

class is never instantiated

How can I suppress the warning? (its more like a green underline..)
Maybe something with annontations?
Thanks.

A: This looks like a ReSharper warning and as such you can ask ReSharper to be silent about these things.
You can either configure ReSharper to stop complaining about this overall, you do this simply by hitting Alt+Enter on the squiggly in question and use the bottom menu item that usually allows you to configure the inspection severity.
You can opt to save this in your global settings, which means it will affect every project you open from now on, or you can save it to a team-shared settings file which you can then check into source control alongside your project, to make it only count for this one solution.
Now, if you want to keep the warning overall but ask it to stop complaining about one or more particular types, methods, properties or the likes, you can use the attributes that ReSharper provides.
You have several ways of bringing these attributes into your project:

*

*Add a reference to the Nuget package "JetBrains ReSharper annotations"

*Use the options dialog for ReSharper and find the page where it allows you to grab a copy of the source for those attributes onto the clipboard, then simply paste this into a file in your project.

*Define just the one or two attributes you want, even in your own namespace (which you then have to tell ReSharper about)

The recommended way is option 1, use the nuget package.
Assuming you now have the attributes available you can use either PublicAPIAttribute or the UsedImplicitlyAttribute.
Either one should suffice but they may have different connotations. Since you're flagging objects being transferred to or from clients I would go with the PublicAPIAttribute first.

Since you say in a comment that the PublicAPIAttribute didn't work but UsedImplicitlyAttribute did then I guess they do have different meanings.


Q: What is wrong passing a 2D array to a respective pointer argument? I've been doing some matrix calculation in C for university the other day where I had a 5x5 matrix to begin with so I hard-coded it into the source. It was a 2D array of doubles like:
/**
 * This is the probability-matrix for reaching from any profile
 * to another by randomly selecting a friend from the friendlist.
 */
static const double F[5][5] = {
  /*           P    , F    , L    , A    , S    */
  /* Peter */ {0    , 0.5  , 0.5  , 0    , 0    },
  /* Franz */ {1.0  , 0    , 0    , 0    , 0    },
  /* Lisa  */ {0    , 1/3.0, 0    , 1/3.0, 1/3.0},
  /* Anna  */ {0    , 0    , 0    , 0    , 1    },
  /* Sepp  */ {0    , 0.5  , 0.5  , 0    , 0    }
};

I wanted my functions to not be fixed to operate on 5-by-5 matrices so I always pass the number of rows and/or cols to the function. This forces me not to use the double [][X] syntax because it can not be completely "variable" and instead use a double* as function parameter.
inline size_t matrix_get(int rows, int i, int j);

inline void matrix_print(double* m, int rows, int cols);

inline void matrix_copy(double* d, const double* s, int rows, int cols);

void matrix_multiply(
  int m, int n, int l,
  const double* a, const double* b, double* d);

But I always get this warning when calling a function that accepts double* when I passed double [5][5] instead.
fuenf_freunde.c:138:17: warning: incompatible pointer types passing 'double [5][5]' to parameter of
      type 'double *' [-Wincompatible-pointer-types]
  matrix_print( R, 5, 5);
                ^
fuenf_freunde.c:54:27: note: passing argument to parameter 'm' here
void matrix_print(double* m, int rows, int cols)
                          ^

Casting using (double*) F resolves the warning.
Now my questions are

*

*am I wrong casting a 2D double array to a double pointer?

*why is it working if its illegal?

*what is the right way to pass an n-dimensional arbitrary size array to a function?

EDIT: This cleared a lot up for me: Accesing a 2D array using a single pointer
So I should just use double[x*y] instead of double[x][y] I think. But is it legal to cast double[] to double*?

A: I contend that there is nothing wrong with what you do. Your code just lacks an explicit cast which would get rid of the warning, indicating that your assignment is intentional.
You can access a one dimensional array through a pointer to its elements, and recursively applied, it follows that n-dimensional matrices can be accessed through pointers to the atomic elements.
C guarantees a contiguous memory layout for them. This pattern is common. In  fact passing arrays is hard or impossible to do differently, given the little information C stores with types (as opposed to, say, C#). So the matrix decays to a pointer to its first element (in your case to the first one dimensional array), which can safely be cast to an address of its first element, a double. They all share the same numerical address.
Typical concerns with pointer type casting are aliasing issues with modern optimizing compilers (a compiler can assume that you don't access memory through pointers of unrelated types except char*), but there is an explicit exemption in the standard draft 1570 which I have, par. 6.5.7, which I think is applicable here:

An object [that would be a double in your matrix, -ps] shall have its stored value accessed only by an lvalue
  expression that has one of the following types:
— a type compatible with the effective type of the object [that would be a dereferenced double pointer, -ps]
  [...]
— an aggregate [e.g. array, -ps]
  [...] type that includes one of the aforementioned types among its
  members (including, recursively, a member of a subaggregate or
  contained union) [that would be your matrix variable, containing, eventually, doubles, -ps]
[...]


Q: Need help setup windows server 2008 SMTP server I am trying to setup windows server 2008 smtp server to relay emails to gmail smtp. Everything appears to be setup but it is not sending emails. Could you please help me figure out whats wrong.
Below is the setup:

*

*Windows server 2008 with SMTP server
feature installed. Need SMTP server
to forward all messages to gmail smtp
server to send.

*I have google apps    setup for my
domain, also I can send    emails
throught my test app using
gmail smtp.

*SMTP Server Configuration: By default has default smtp server virtual directory.

*In Properties of that virtual smtp server changed following.

*Fully qualified domain name = mydomain.com

*smart host = smtp.gmail.com

*TCP Port = 587

*Out Bound Security = Basic Authentication(my username password for google apps email account)

*In domains list under virtual smtp server. I have one default domain that's server dns. I added another one for my domain name.

With above setup i am trying to redirect all email to gmail smtp.
I tested connection to smtp.gmail.com from server on port 587 through telnet and it works.
I am trying to use above server from my web application also by just dropping emails in pickup directory. It get's picked up and also accepts request form web application but never sends an email.
I can see that it adds those emails in queue folder but it stays there forever.
When i try to send emails from web app to above server it rejects if To address is other than my domain.(Am i missing something in list of domains)

A: Thanks for all answers, finally found solution there is a property for maximum sessions which value was 0 by default. Changed it to 100 and it send all pending emails immediately.

A: This souds like a DNS issue. Check your /badmail directory. It will have .bad and .bdp files in there. You can open these in notepad (there will be some binary in there).
However, it may point to the possible problem.
You may also want to try and enable logging on the SMTP service. There may be something in there.

A: Possible reasons are that some SMTP servers block the outgoing messages if there domain name mismatch, possible to prevent spam mails from being sent. So for example, I will not be able to send my email with an address abc@mydomain.com from my domain yourdomain.com.
Hope that helps.

A: Ensure your sending domain is the same as the google apps domain
Ensure your sending address is a real address and not just an alias
IIRC you need to use STARTTLS (SSL) not basic authentication


Q: why can't I pass the return twice? I'm practicing python and I don't understand why I am getting this error. I tried searching it but I can't find put why.
I tried to put pass_two = two(x) but it didn't work. it kept saying it was undefined.
can any one correct and explain why? thanks
def one():
    x = 'blue'
    return x

def two(x):
    y = 'red'
    xy = x+y
    return xy

def three(z):

    w = 'black'
    print('all three passes ' + z+w)

def main():
    pass_one = one()
    two(pass_one)

    pass_two = two()
    three(pass_two)

if __name__ == '__main__':
    main()

A: You defined the function two to work with an argument so if you try to type two(), Python will output TypeError: two() missing 1 required positional argument: 'x'.
Now, if you try to type two(x)without having defined x before, you will get a NameError.
Maybe you wanted to write pass_two = two(pass_one)


Q: Insert multipe rows after specific row in Excel 2003 For example, my table is like this :
  AAA
  bb
  cc
  AAA
  dd...

How can I insert 3 empty rows just below AAA row? So that, my table becomes :
  AAA
  first empty row
  second empty row
  third empty row
  bb
  cc
  AAA
  first empty row
  second empty row
  third empty row
  dd..

A: If you are in Excel, right click on the row numbers on the left to show a context menu, then click on "Insert". This will add a new row.


Q: Java project can display a new scene pretty easily, but only for certain JavaFXML files, how to fix this? Here's my code I'm struggling with (I marked the line that's giving me errors):
package sample.controller;

import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import sample.database.DBConnection;
import sample.model.User;

public class LoginController {

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private Button loginButton;

    @FXML
    private TextField loginEmail;

    @FXML
    private Button createAccountSwitchButton;

    @FXML
    private PasswordField loginPassword;

    private DBConnection dbConnection;

    @FXML
    void initialize() {

        dbConnection = new DBConnection();

        loginButton.setOnAction(event-> {
            String loginEmailText = loginEmail.getText().trim();
            String loginPasswordText = loginPassword.getText().trim();

            User user = new User();
            user.setEmail(loginEmailText);
            user.setPassword(loginPasswordText);

            ResultSet userRow = dbConnection.checkForUser(user);
            int counter = 0;

            try{
                while (userRow.next()){
                    counter++;
                }
                if (counter==1){
                    loginButton.getScene().getWindow().hide();
                    FXMLLoader loader = new FXMLLoader();

//THE LINE BELOW THIS LINE-------------------------------------------------------------------

                    loader.setLocation(getClass().getResource("/sample/view/CreateAccount.fxml")); //THIS LINE

//THE LINE ABOVE THIS LINE-------------------------------------------------------------------
                    try {
                        loader.load();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Parent root = loader.getRoot();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.showAndWait();

                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        });

        //  Takes user to Create Account page
        createAccountSwitchButton.setOnAction(event -> {
            createAccountSwitchButton.getScene().getWindow().hide();
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("/sample/view/CreateAccount.fxml"));

            try {
                loader.load();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Parent root = loader.getRoot();
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.showAndWait();

        });

    }

//    private void loginUser(String email, String password) {
//        //Checks if fields are empty, if so, bring them to user dashboard.
//        if(!email.equals("") || !password.equals("")){
//
//        }else{
//
//        }
//    }
}

At this point, it does exactly what I want it to do, it loads a new scene of "CreateAccount.fxml" file whenever I click the login button. But I want it to load a different FXML file, so I change the name to "Dashboard.fxml" which is my dashboard file name, but all of a sudden it no longer works and it's giving me errors that don't make any sense since my path is right and my name is right as well. This is what I changed that line to to throw the error below:
loader.setLocation(getClass().getResource("/sample/view/Dashboard.fxml"));

Lastly, to make sure, I created a completely new and blank FXML file and it won't load either.
Here are the full errors:
javafx.fxml.LoadException:
/C:/Users/andre/IdeaProjects/Covix/out/production/Covix/sample/view/Dashboard.fxml:12

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:922)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
    at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at sample.controller.LoginController.lambda$initialize$0(LoginController.java:68)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:215)
    at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
    at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
    at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:633)
    at javafx.stage.Stage.showAndWait(Stage.java:474)
    at sample.controller.CreateAccountController.lambda$initialize$0(CreateAccountController.java:59)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: sample.view.Dashboard
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:920)
    ... 106 more
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Root cannot be null
    at javafx.scene.Scene.<init>(Scene.java:336)
    at javafx.scene.Scene.<init>(Scene.java:194)
    at sample.controller.LoginController.lambda$initialize$0(LoginController.java:75)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method)
    at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:215)
    at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
    at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
    at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:633)
    at javafx.stage.Stage.showAndWait(Stage.java:474)
    at sample.controller.CreateAccountController.lambda$initialize$0(CreateAccountController.java:59)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)

Here's my Dashboard.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.shape.Rectangle?>
<?import javafx.scene.text.Font?>

<AnchorPane prefHeight="800.0" prefWidth="1400.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.view.Dashboard">
   <children>
      <AnchorPane layoutX="-6.0" layoutY="-12.0" prefHeight="816.0" prefWidth="325.0" style="-fx-background-color: #001E8A;">
         <children>
            <ImageView fitHeight="46.0" fitWidth="46.0" layoutX="64.0" layoutY="60.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../assets/whiteLogo.png" />
               </image>
            </ImageView>
            <Label layoutX="132.0" layoutY="55.0" text="Covix" textFill="WHITE">
               <font>
                  <Font size="43.0" />
               </font>
            </Label>
            <Rectangle arcHeight="5.0" arcWidth="5.0" fill="WHITE" height="5.0" layoutX="51.0" layoutY="155.0" stroke="BLACK" strokeType="INSIDE" width="222.0" />
         </children>
      </AnchorPane>
      <TableView layoutX="379.0" layoutY="342.0" prefHeight="402.0" prefWidth="397.0">
        <columns>
          <TableColumn prefWidth="75.0" text="C1" />
          <TableColumn prefWidth="75.0" text="C2" />
        </columns>
      </TableView>
      <Label layoutX="371.0" layoutY="30.0" text="Dashboard">
         <font>
            <Font name="System Bold" size="44.0" />
         </font>
      </Label>
   </children>
</AnchorPane>

Here's my CreateAccount.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="1050.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.CreateAccountController">
   <children>
      <AnchorPane layoutX="417.0" layoutY="-8.0" prefHeight="610.0" prefWidth="634.0" style="-fx-background-color: #001F8E;">
         <children>
            <ImageView fitHeight="378.0" fitWidth="534.0" layoutX="46.0" layoutY="118.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../assets/loginart.png" />
               </image>
            </ImageView>
            <Label layoutX="247.0" layoutY="514.0" text="Stay Safe With Covix" textFill="WHITE">
               <font>
                  <Font name="System Bold" size="16.0" />
               </font>
            </Label>
            <Label layoutX="160.0" layoutY="542.0" text="Update your scores and see other user's scores to keep yourself" textFill="WHITE" />
            <Label layoutX="160.0" layoutY="564.0" text="        and others around you as healthy and safe as possible." textFill="WHITE" />
         </children></AnchorPane>
      <AnchorPane layoutY="-2.0" prefHeight="606.0" prefWidth="417.0" style="-fx-background-color: white;">
         <children>
            <ImageView fitHeight="44.0" fitWidth="44.0" layoutX="38.0" layoutY="39.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../assets/covixapplogo.png" />
               </image>
            </ImageView>
            <Label layoutX="94.0" layoutY="40.0" text="Covix" textFill="#111111">
               <font>
                  <Font size="32.0" />
               </font>
            </Label>
            <Label layoutX="40.0" layoutY="111.0" text="Create Account">
               <font>
                  <Font name="System Bold" size="27.0" />
               </font>
            </Label>
            <Label layoutX="42.0" layoutY="155.0" text="Get safer with your score. Create an account today!" textFill="#6c6c6c" />
            <Button fx:id="createAccountButton" layoutX="49.0" layoutY="480.0" mnemonicParsing="false" prefHeight="30.0" prefWidth="313.0" style="-fx-background-color: #001F8E; -fx-border-radius: 10; -fx-border-color: none; text: white;" text="Create Account" textFill="WHITE" />
            <TextField fx:id="createAccountEmail" layoutX="44.0" layoutY="294.0" prefHeight="35.0" prefWidth="324.0" promptText="Email" />
            <Label layoutX="43.0" layoutY="265.0" prefHeight="18.0" prefWidth="235.0" text="Your email:" textFill="#191919">
               <font>
                  <Font size="15.0" />
               </font>
            </Label>
            <Label layoutX="47.0" layoutY="337.0" prefHeight="18.0" prefWidth="235.0" text="Password:" textFill="#191919">
               <font>
                  <Font size="15.0" />
               </font>
            </Label>
            <CheckBox layoutX="55.0" layoutY="421.0" mnemonicParsing="false" text="By creating an account you agree to the terms and conditions.">
               <font>
                  <Font size="10.0" />
               </font>
            </CheckBox>
            <Label layoutX="134.0" layoutY="531.0" text="Already have an account?" textFill="#6c6c6c" />
            <Button fx:id="loginButtonSwitch" layoutX="176.0" layoutY="549.0" mnemonicParsing="false" style="-fx-background-color: none;" text="Log In" textFill="#041cf2">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Button>
            <PasswordField fx:id="createAccountPassword" layoutX="44.0" layoutY="369.0" prefHeight="35.0" prefWidth="324.0" promptText="Password" />
            <TextField fx:id="createAccountFullName" layoutX="42.0" layoutY="218.0" prefHeight="35.0" prefWidth="324.0" promptText="e.g. John Doe" />
            <Label layoutX="42.0" layoutY="189.0" prefHeight="18.0" prefWidth="235.0" text="Your Full Name" textFill="#191919">
               <font>
                  <Font size="15.0" />
               </font>
            </Label>
         </children>
      </AnchorPane>
   </children>
</AnchorPane>

So for some reason, my CreateAccount.fxml file loads, but not a completely new FXML file that's blank or my Dashboard.fxml file. I'm not sure what the problem could be. Thanks in advance!

A: The problem is this line of the stack trace:
Caused by: java.lang.ClassNotFoundException: sample.view.Dashboard

This means that the FXML loader could not find a class named Dashboard in package sample.view.
The FXML loader looked for this class because that is what was written in file Dashboard.fxml, namely:
<AnchorPane prefHeight="800.0" prefWidth="1400.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.view.Dashboard">

Notice the part at the end of the line:
fx:controller="sample.view.Dashboard"

If you don't need a controller class then simply remove that part.


Q: Error building react native app on Android Hi I´m trying to run my react native app on android but when i build it shows me this error:
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 952 file(s) to forward-jetify. Using 8 workers...
info JS server already running.
info Installing the app...
> Task :react-native-safe-area-context:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.9/userguide/command_line_interface.html#sec:command_line_warnings
48 actionable tasks: 2 executed, 46 up-to-date

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-safe-area-context:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-safe-area-context:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

    at makeError (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:174:9)
    at /Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:106:5)
    at async Command.handleAction (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli/build/index.js:192:9)
info Run CLI with --verbose flag for more details.

It´s a bit puzzling since when i build the app on the ios simulator it runs perfectly.
Do you guys have any idea how i can solve the issue?
Thanks.

A: npm install react-native-safe-area-context

Try this and build.
If not,
Please check your computer's environment variables and set JAVA_HOME if it has not already been setup.


Q: CSS column bug fix or alternative Due to Chrome (and other Blink browsers) having a bug where only the first 500 columns are painted i need either a fix/hack, or an alternative solution.
See bug here (there is 509 pages - not 500): https://codepen.io/anon/pen/pLxozK
/* codepen link must be accompanied by code */
column-width: 400px;

I parse EPUB html to a single file. The EPUB's styling must be preserved, so i can't change the html structure.
CSS columns does a good job of rendering such a flat document horizontally. But the 500 limit in Blink means blank pages in Android Webviews.
Is there any workaround for this bug?
Users can adjust font size etc meaning amount of columns can change. So an alternative solution must be able to adjust.

A: What a cool little bug, I've never seen that before!
By the looks of things you'll need to add display:none to some of your divs. You'll need to use Javascript to see what's in view and see what's not. You'll get the added bonus of not using any system resources unnecessarily as you won't be painting any of the pages that aren't in view.


Q: PHP preg_replace exclude < and > I need to change this code:
$output = preg_replace("#<a ([^>]*)>([^<]*)<\/a>#", "$2", $output)

to make from <a some.url>description</a> to HTML code description, but after i changed < and > to < and > it doesn't make what I wanted.
Thank you for your help.
EDIT:
I wouldn't use html_entity_decode(), because I want this for enabling slightly simplified HTML tags, but the most of HTML i would have disabled.
Input for my function is a variable, obtained from a form:
Firstly the code replaces all < and > with < and >.
Than it changes back some text-modifying static HTML tags, for example  and .
But in the end, i want to change every link inputed as link (and than by code changed to <a some.url>link</a>) to be changed by preg_replace() into standard HTML code link

A: http://php.net/manual/en/function.html-entity-decode.php
$str = "this 'quote' is <b>bold</b>"
html_entity_decode($output)
// output This 'quote' is bold

http://php.net/manual/en/function.htmlentities.php
$str = "This 'quote' is bold";
htmlentities($output);
// output this 'quote' is <b>bold</b>


Q: Open a PDF file from C#.NET using Impersonate I have a folder on the server containing pdf files(Windows Server 2008 R2 Enterprise). I have to open the folder with the authorized user account and display the pdf file in the browser. The user has full control permissions on the folder and is a member of the Administrator group.
Bellow code works from my local as it opens the pdf file from the folder located in the server in Adobe Reader. But on the server the process does not start(Adobe Reader does not open) and no exception occurs. Most of the forums say that turning off UAC will help, but I don't want to do it, because of security reasons.
How can I deal that issue? Please help.
try
{
    WindowsIdentity wi = new WindowsIdentity(@"user_name@DOMAIN");
    WindowsImpersonationContext ctx = null;

    try
    {
        ctx = wi.Impersonate();

        // Thread is now impersonating you can call the backend operations here...
        Process p = new Process();

        p.StartInfo = new ProcessStartInfo()
        {
            CreateNoWindow = true,
            Verb = "open",
            FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf",
        };

        p.Start();
    }
    catch (Exception ex)
    {
        msj = ex.Message;
    }
    finally
    {
        ctx.Undo();
    }

    return msj;
}
catch (Exception ex)
{
    return msj + "Error: " + ex.Message;
}

A: Try to execute your .exe with Run as Adminstrator on the server.If it works properly then add the below code:
p.StartInfo.Verb = "runas";

A: @Chintan Udeshi Thank you for you quick answer. I can run the AcroRd32.exe by Run as Administrator but when I tried with runas I got the error which says; "No application is associated with the specified file for this operation".
I also tried to place absolute Acrobat Reader Path, but it still didn't work. Any idea?
p.StartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe")
{
   CreateNoWindow = true,
   Verb = "runas",
   FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf", // "c:\\pdf\\",
};


Q: setAttribute a href in Selenium Java I got href of an element. After that, I subString,...to make a new href and want to set it back to element. But Selenium doesn't have setAttribute method
nextListByNumber = driver.findElement(By.xpath("//*[@id='paginater']//*[text()='"+2+"']"));
String href = nextListByNumber.getAttribute("href");
int manualcode1 = href.lastIndexOf("MANUAL");
int manualcode2 = href.lastIndexOf("/sort");
String manualcode = href.substring(manualcode1, manualcode2);

String hrefNew = "http://localhost/jp/courseassign/course_assign_search_result/"+manualcode+"/sort:User.login_id/direction:asc/page:"+i+"?limit=20";

A: You can use JavaScript for this
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", nextListByNumber, "href", hrefNew);


Q: DELETE function is deleting the logo, but I don't want it to delete the logo I have a GUI in Matlab, where I have a DELETE BUTTON, after I click on it, it as well deletes the logo in it.
The code for the DELETE function:
clc

figure('Name', 'Vektorkardiogram');
%Return handle to figure named 'Vectorcardiogram'.
h = findobj('Name', 'Vektorkardiogram');
close(h);

figure('Name', 'Roviny');
%Return handle to figure named 'Vectorcardiogram'.
r = findobj('Name', 'Roviny');
close(r);

figure('Name', 'P vlna');
%Return handle to figure named 'Vectorcardiogram'.
p = findobj('Name', 'P vlna');
close(p);

figure('Name', 'QRS komplex');
%Return handle to figure named 'Vectorcardiogram'.
q = findobj('Name', 'QRS komplex');
close(q);

figure('Name', 'T vlna');
%Return handle to figure named 'Vectorcardiogram'.
t = findobj('Name', 'T vlna');
close(t);

arrayfun(@cla,findall(0,'type','axes'));
delete(findall(findall(gcf,'Type','axe'),'Type','text'));

The code for uploading the logo (I have made a GUI in Matlab using the guide command, so this code below is inserted inside the GUI code):
logo4 = imread('logo4.png','BackgroundColor',[1 1 1]);
imshow(logo4)

Pusghing the DELETE BUTTON, I just want to close certain figure windwos, not to delete the logo. Could you please help me out?

A: You are clearing all axes using cla which includes the logo that you don't want to delete.
arrayfun(@cla,findall(0,'type','axes'));

Instead of clearing everything, it's better to delete and clear specific objects.
cla(handles.axes10)
cla(handles.axes11)

Alternately, if you keep the handle to the image object, you can ignore the axes that contains it when clearing axes
himg = imshow(data);

allaxes = findall(0, 'type', 'axes');
allaxes = allaxes(~ismember(allaxes, ancestor(himg, 'axes')));

cla(allaxes)

Also, you shouldn't ever do findall(0, ... in your GUI because if I open a figure before opening my GUI you will alter the state of my other figure. Instead, use findall(gcbf, ... which will only alter children of your own GUI. Either that, or use a 'Tag' specific to your GUI and then use findall to filter for that specific tag.
figure('Tag', 'mygui')

findall(0, 'Tag', 'mygui')

Update
You should use findall combined with the 'Name' parameter to figure out which of your figures actually exists
figs = findall(0, 'Name', 'Vektorkardiogram', ...
               '-or', 'Name', 'Roviny', ...
               '-or', 'Name', 'P vlna', ...
               '-or', 'Name', 'QRS komplex', ...
               '-or', 'Name', 'T vlna');
delete(figs);

And for clearing the axes, you can ensure that they exist
ax = findall(0, 'tag', 'axes10', '-or', 'tag', 'axes11', '-or', 'tag', 'axes12');
cla(ax)


Q: How to retrieve array in php sent from iOS Following is my iOS code that sends NSmutable Array to PHP webservice:
 // Getting Server Address
            AppDelegate *appDelegate =
            [[UIApplication sharedApplication] delegate];

            NSString *serverAddress = [appDelegate getServerAddress];

            serverAddress = [serverAddress stringByAppendingString:@"ABC.php"];

            NSLog(@"Server Address: %@",serverAddress);

            NSData *post = [NSJSONSerialization dataWithJSONObject:UsersArray options:NSJSONWritingPrettyPrinted error:nil];
            NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:serverAddress]];

            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:post];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setTimeoutInterval:30];
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){
                //Do whatever with return data

                NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
                NSLog(@"Result : %@",result);
            }];

I want to retrive that array in PHP. How can I do that?
Here is the php which I tried but returns null:
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);

echo json_encode($decoded);

A: I use a slightly different Content-Type (which shouldn't matter):
[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

And I use a slightly different PHP, too:
<?php

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

$json_data = json_decode($http_raw_post_data, true);

echo json_encode($json_data);

?>

If you're getting a blank response, I'd wager you have some PHP error. I'd you check out your server's error log, or temporarily changing the display_errors setting in your php.ini as follows:
display_errors = On


Q: WCF un-domain system I have developed WCF windows service using net tcp binding. Its working fine when wcf client and wcf service both on the same system.
Getting error when both system are in work group not - Client and Service are on different machines
please suggest what configuration i need to change .
SocketId:61017335 to remote address :8005 had a connection reset error.
Error :System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:58.9879193'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
I am using Certificate authentication - I know without a domain I lack the necessary Kerberos infrastuture to authenticate UPNs and SPNs but shouldn't that be resolved because I am using certificates.
Client’s Config File
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint kind="discoveryEndpoint" address="net.tcp://localhost:8005/Probe" binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding">
      </endpoint>
      <endpoint binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding" contract="Test2ServLib.IService1" behaviorConfiguration="LargeEndpointBehavior">
        <identity>
          <dns value="WCFServer" />
        </identity>
      <!--The behaviorConfiguration is required to enable WCF deserialization of large data sets -->
      </endpoint>
    </client>
 <behaviors>
      <endpointBehaviors>
        <behavior name="disableEndpointDiscovery">
          <endpointDiscovery enabled="false" />
          <!--The behavior is required to enable WCF deserialization of large data sets -->
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <clientCredentials>
            <clientCertificate findValue="WCFClient"
                               storeLocation="LocalMachine"
                               storeName="TrustedPeople"
                               x509FindType="FindBySubjectName" />
                        <serviceCertificate >
                            <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/>
                        </serviceCertificate>
          </clientCredentials>
        </behavior>
        <behavior name="LargeEndpointBehavior">
          <!--The behavior is required to enable WCF deserialization of large data sets -->
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
            <clientCredentials>
              <clientCertificate findValue="WCFClient"
                                 storeLocation="LocalMachine"
                                 storeName="TrustedPeople"
                                 x509FindType="FindBySubjectName" />
                        <serviceCertificate >
                            <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/>
                        </serviceCertificate>
            </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="RequestReplyNetTcpBinding" receiveTimeout="05:00:00" openTimeout="00:00:59" closeTimeout="00:00:59" maxBufferPoolSize="524288" maxBufferSize="25000000" maxConnections="50" maxReceivedMessageSize="25000000" sendTimeout="00:05:00" listenBacklog="1500">
          <reliableSession ordered="false" inactivityTimeout="00:01:00" enabled="true" />
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security>
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

Service Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="announcementBehavior">
      <!--The following behavior attribute is required to enable WCF serialization of large data sets -->
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
      <serviceDiscovery>
        <announcementEndpoints>
          <endpoint kind="announcementEndpoint"
        address="net.tcp://localhost:8005/Announcement"
        binding="netTcpBinding"
        bindingConfiguration="RequestReplyNetTcpBinding"/>
        </announcementEndpoints>
      </serviceDiscovery>
      <serviceThrottling
              maxConcurrentCalls="1500"
              maxConcurrentSessions="1500"
              maxConcurrentInstances="1500"/>
      <serviceCredentials>
        <serviceCertificate findValue="WCFServer"
                            storeLocation="LocalMachine"
                            storeName="TrustedPeople"
                            x509FindType="FindBySubjectName" />
        <clientCertificate>
          <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="LocalMachine" revocationMode="NoCheck"/>
        </clientCertificate>
      </serviceCredentials>
    </behavior>
 </serviceBehaviors>
 </behaviors>
 <service name="Test2ServLib.IService1"
   behaviorConfiguration="announcementBehavior">
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://localhost:8006/Service1"/>
      </baseAddresses>
    </host>
    <endpoint binding="netTcpBinding"
              bindingConfiguration="RequestReplyNetTcpBinding"
              contract="Test2ServLib.IService1"
              behaviorConfiguration="LargeEndpointBehavior" />
        <bindings>
            <netTcpBinding>
                <binding name = "RequestReplyNetTcpBinding">
                    <security>
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>
            </netTcpBinding>
        </bindings>
  </system.serviceModel>
</configuration>


Q: Android build failed and error message is "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'" In my Android App I used pdfbox to generate PDF file. I was able to compile but when I build and try to deploy to a simulator. I got the following error message: "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'". In my build.gradle file I include a libs path and all the jar were copy to libs path
compile fileTree(include: ['*.jar'], dir: 'libs')
// implementation 'libs/*.jar'
implementation files('libs/jfreechart-1.0.19.jar')

All the jars were included in the app/libs path
The following jars were included in the app/libs path
jfreechart-1.0.0.19 jar
pdfbox-2.0.13.jar
pdfbox-app-2.0.13.jar
pdfbox-debugger-2.0.13.jar
pdfbox-tools-2.0.13.jar


Q: MongoDb: Match value on foreign collection I have the collection USER:
{
    "_id" : ObjectId("5d64d2bf48dd17387d77d27a"),
    "name" : "John",
    "notifications" : {
        "email" : false,
        "sms" : true
    }
},
{
    "_id" : ObjectId("5da9586911e192081ee1c6be"),
    "name" : "Mary",
    "notifications" : {
        "email" : false,
        "sms" : false
    }
}

And this other collection ALERT:
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a551e"),
    "active" : true,
    "user_id" : ObjectId("5d64d2bf48dd17387d77d27a")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a551f"),
    "active" : false,
    "user_id" : ObjectId("5d64d2bf48dd17387d77d27a")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a552e"),
    "active" : true,
    "user_id" : ObjectId("5da9586911e192081ee1c6be")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a552f"),
    "active" : true,
    "user_id" : ObjectId("5da9586911e192081ee1c6be")
}

I want a MongoDB query that lists the documents on collection ALERT that have property "active" as TRUE and whose matching USER has element "sms" on property "notifications" as TRUE too.

A: You can use Uncorelated sub queries in $lookup

*

*$match to get the "notifications.sms": true

*$lookupto join two collections. We are assigning uId = _id from USER collection. Inside the pipeline, we use $match to find the active :true, and _id=uId
here is the script
db.USER.aggregate([
  {
    "$match": {
      "notifications.sms": true
    }
  },
  {
    "$lookup": {
      "from": "ALERT",
      "let": {
        uId: "$_id"
      },
      "pipeline": [
        {
          $match: {
            $and: [
              {
                active: true
              },
              {
                $expr: {
                  $eq: [
                    "$user_id",
                    "$$uId"
                  ]
                }
              }
            ]
          }
        }
      ],
      "as": "joinAlert"
    }
  }
])

Working Mongo playground


Q: xml extension type and user defined I've a xml document that according to its schema definition for a certain node "level" only allows a predefined list of values (aka enumeration if not wrong). This predefined values are ok for a country, but if we change country the values might change.
For this the "level" node allows ( and here starts my doubts) attribute "userDefined" and sub nodes such as <extension> and I believe is through this <extension> node or maybe userdefined attr that I will be able to specify other value and thus get the doc validated.
The xsd file is here: http://utdanning.no/schemas/CDM/2.1/CDM.xsd and the xml sample file here
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CDM xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://utdanning.no/schemas/CDM/2.1/CDM.xsd">
    <orgUnit>
        <orgUnitID>217</orgUnitID>
        <orgUnitName>Contoso Inc [TEST PURPOSES ONLY]</orgUnitName>
        <webLink>
            <href>http://www.google.com</href>
        </webLink>
        <course>
            <courseID>341</courseID>
            <courseCode>FWTEST2222222</courseCode>
            <courseName>Another field course test imported</courseName>
            <courseDescription>Testing purposes only test teste teste</courseDescription>
            <level level="other_value"/><!--This is where i want to add a diff value other than the allowed list: vgs, folkehogskole, bachelor, master, phd, fagskole, evu, aarsstudium -->
            <credits ECTScredits="45"/>
            <admissionInfo/>
            <teachingPlace>
                <adr>
                  <country>NORWAY</country>
                </adr>
            </teachingPlace>
            <formOfTeaching>Field course</formOfTeaching>
            <instructionLanguage>Norske</instructionLanguage>
        </course>
    </orgUnit>
</CDM>

A: This schema does not allow arbitrary values in the "level" attribute. There is no way to extend the set of valid values.


Q: Differentiating Between an AJAX Call / Browser Request Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless?

A: If you use Prototype, jQuery, Mootools or YUI you should find a X-Requested-With:XMLHttpRequest header which will do the trick for you. It should be possible to insert whatever header you like with other libraries.
At the lowest level, given a XMLHttpRequest or XMLHTTP object, you can set this header with the setRequestHeader method as follows:
xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

A: After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.


Q: Log4j properties | Create new log file with timestamp for every run I'm quite new to log4j and have managed to create the logs for my code.
But what I need is, a new file to be created for each run, rather than appending the logs to the same file.
Below are the properties I'm setting (found somewhere on google).
Please suggest changes, so that new file will be created with the timestamp after each run.
// Here we have defined root logger
log4j.rootLogger=INFO,R,HTML

// Here we define the appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.HTML=org.apache.log4j.FileAppender

// Here we define log file location
log4j.appender.R.File=./Logs/LastRunLog.log
log4j.appender.HTML.File=./Logs/LastRunLog.html

// Here we define the layout and pattern
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true

A: You can use a system property to set the log4j file names with it's value and give that property an unique value for each run.
Something like this on your starter class (timeInMillis and a random to avoid name clashes):
static {
    long millis = System.currentTimeMillis();
    System.setProperty("log4jFileName", millis+"-"+Math.round(Math.random()*1000));
}

And then you refer to the system property on log4j conf properties:
log4j.appender.R.File=./Logs/${log4jFileName}.log
log4j.appender.HTML.File=./Logs/${log4jFileName}.log

Hope it helps!

A: You need to write (or find) a custom appender which will create the file with a timestamp in the name.
The 3 defaults implementation for file logging in log4j are :

*

*FileAppender : One file logging, without size limit.

*RollingFileAppender : Multiple files and rolling file when current file hits the size limit

*DailyRollingFileAppender : A file per day

The simpliest way is to extend FileAppender and overwrite the setFile and getFile methods.

A: i think this answer would be helpful for you click here
i have ran code as the page said, and i got a new log file each time i start my application.
result like that :
and all code in my Test.java is :`
private static final Logger log = Logger.getLogger(Test.class);

public static void main(String[] args) {
    log.info("Hello World");
}

`


Q: How to select checkbox button and NavigationLink to another view independently in SwiftUI List row I hope to make a list just like to-do list, the cell has a checkbox and Text. And I want when list cell selected, the view could be translate to detailView. Meanwhile I also could select the checkbox, but don't trigger the view translate to the detailView.
I removed the List{}, the code run ok, but the List property and method can't use any more. So I plan to code a customer list view. But I don't think it will be the good method. So if I still can't find a good way to make it, I may implement in this way at last.
NavigationView {
     VStack {
        List {
                 ForEach(todayDietModel.todayDietItems) { item in
                     NavigationLink(destination: DietItemDetailView()) {
                            TodayDietRow(todayDietItem: item)
                                .animation(.spring())
                        }
                    }
                }

            }
            .frame(width: 352, height: 400)
            .background(Color.white)
            .cornerRadius(16)

}

struct TodayDietRow: View {
   @State var isFinished: Bool = false

    var body: some View {
        HStack(spacing: 20.0) {
            Button(action: {self.isFinished.toggle()}) {
                if self.isFinished {
                    Image("icon_checked_s001")
                        .resizable()
                        .renderingMode(.original)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 24, height: 24)
                } else {
                    Image("icon_unchecked_s001")
                        .resizable()
                        .frame(width: 24, height: 24)
                }

            }
            .padding(.leading, 10)

            Text("DietName")
                .font(.system(size:13))
                .fontWeight(.medium)
                .foregroundColor(Color.black)

        }
        .frame(width: 327, height: 48)

    }
}

A: This works quite well with a gesture on the checkbox image. Two Buttons didn't work since every tap went to both buttons.
struct TodayTodoView2: View {
    @ObservedObject var todayDietModel = TodayDietModel()

    func image(for state: Bool) -> Image {
        return state ? Image(systemName: "checkmark.circle") : Image(systemName: "circle")
    }

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach($todayDietModel.todayDietItems) { (item: Binding<TodayDietItem>) in
                        HStack{
                            self.image(for: item.value.isFinished).onTapGesture {
                                item.value.isFinished.toggle()
                            }
                            NavigationLink(destination: DietItemDetailView2(item: item)) {
                                Text("DietNamee \(item.value.dietName)")
                                    .font(.system(size:13))
                                    .fontWeight(.medium)
                                    .foregroundColor(Color.black)
                            }
                        }
                    }
                }
                .background(Color.white)
            }
        }
    }
}


Q: cudaMemcpy returns cudaErrorInvalidArgument when reading from Device to Host, unclear why first post here. I'm currently working on a project that requires writing a large 2d array (on the order of 1,000,000x7) into my GPU, doing some computation, and returning it to the Host. Since I want to do so quickly and with such a large array, I attempted to flatten the array to help pass it into the GPU fairly straightforwardly. The array successfully writes (or at least cudaMalloc and cudaMemcpy both return cudaSuccess when I write to the device), but when I try to read it out cudaMemcpy returns an invalid argument error.
I've not been able to figure out why this is, since I think I should be writing a valid 1d array (flattened) onto the device and reading it back out, and I thought I was feeding the right arguments to do this. The only results for this error I've found online involve swapping the dst and src arguments for cudaMemcpy, but I think I've got those right here.
This is a simplified version of my code that reproduces the problem:
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

void write2dArrayToGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

void read2dArrayFromGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);

}

I compile and run this on my laptop with
 $nvcc -arch=sm_30 test.cu -o test
 $optirun cuda-memcheck ./test

and get the result:
========= CUDA-MEMCHECK
Allocating an 100x7 array ...Assigning some values ...Done!
Writing to the GPU ... Done!
Allocating second 100x7 array ...Done!
========= Program hit cudaErrorInvalidValue (error 11) due to "invalid argument" on CUDA API call to cudaMemcpy.
=========     Saved host backtrace up to driver entry point at error
Reading from the GPU into the new array ...=========     Host Frame:/usr/lib64/nvidia-bumblebee/libcuda.so.1 [0x2ef343]
cudaMemcpy Read Failed=========     Host Frame:./test [0x38c6f]
=========     Host Frame:./test [0x2f08]
=========     Host Frame:./test [0x3135]
=========     Host Frame:/usr/lib64/libc.so.6 (__libc_start_main + 0xf1) [0x20401]
=========     Host Frame:./test [0x2c6a]

=========
========= ERROR SUMMARY: 1 error

I'm moderately new to CUDA, and still learning, so any help would be appreciated, thanks!

A: Thanks to Robert Crovella for pointing me in the right direction with a comment above, and linking a similar question.
The gist is that by passing devPtr by value rather than by pointer or by reference into my GPU write and read functions, the cudaMalloc and cudaMemcpy functions were acting only on a copy in the function scope.
Two solutions - (both of these run without throwing errors for me)
First: Pass devPtr by reference into write2dArrayToGPU and read2dArrayFromGPU the solution then looks like.
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

//changed float * devPtr to float *  &devPtr
void write2dArrayToGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

//changed float * devPtr to float * &devPtr
void read2dArrayFromGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);

}

Second: Pass devPtr by pointer so the solution looks like
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

//changed float * devPtr to float ** devPtr
void write2dArrayToGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(*devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

//changed float * devPtr to float ** devPtr
void read2dArrayFromGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], *devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, &Darr, R, C); \\changed Darr to &Darr
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, &Darr, R, C); // changed Darr to &Darr

}


Q: AJAX load more posts script out putting nothing, no warnings, no notices, no data Can anyone tell me why this is outputting nothing.. at all? No errors, no notices. Nada.
I really need help with this, theres nothing wrong with the SQL details. The codes purpose is too display Mysql data with an AJAX div that loads more posts. If theres anything that could be causing this please post below. Thanks!:)
Source code:
 <?php
    /* grab stuff */
    function get_posts($start = 0, $number_of_posts = 5) {
        /* connect to the db */
        $connection = mysql_connect('localhost','root','');
        mysql_select_db('draft2',$connection) or die(mysql_error());
        $posts = array();
        /* get the posts */
        $query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());

        $result = mysql_query($query);
        while($row = mysql_fetch_assoc($result)) {
            preg_match("/
(.*)<\/p>/",$row['item_content'],$matches);
            $row['item_content'] = strip_tags($matches[1]);
            $posts[] = $row;
        }
        /* return the posts in the JSON format */
        return json_encode($posts);
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Load More

I actually have posted this problem before, i know that will get you all angry. But i tried fixing it for a while but im just not as experienced as the people on here so I return. Please dont hate me.

A: @user663049: I think your problem is this line --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());

It should be --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT " . $start . ", " . $number_of_posts;

$result = mysql_query($query) or die(mysql_error());

A: If it displays nothing maybe because of web server configuration. Could you just try to insert at the begining of the PHP block the following, so you may see at least errors and make the debugging
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
?>


Q: How can I define an ext property from Heap.io with gradle kotlin dsl Im using the heap.io and their Android SDK and they advise you to setup their library like:

*

*build.gradle:

android {
    defaultConfig {
        // Add this section to enable Heap event capture.
        ext {
          heapEnabled = true
        }
        // ...
    }
    // ...
}

But this is using the gradle groovy sintax, Im trying to use it with the Kotlin DSL of gradle like:

*

*build.gradle.kts
android {
    defaultConfig {
        ext {
            set("heapEnabled", true)
        }

But it does not work for some reason, so:
Why that may be happening?

A: This works:
(this as ExtensionAware).extensions.extraProperties.set("heapEnabled", true)

I believe Heap is looking into making it so the cast isn't necessary.

A: extra.set("heapEnabled", false)

A: I was able to make it work using withGroovyBuilder like:
android {
    defaultConfig {
        withGroovyBuilder {
            "ext" {
                setProperty("heapEnabled", LhConfig.isAnalyticEnabled(project))
            }
        }

I still dont understand where is the issue :(


Q: How to add a new line in text field of dropdown in semantic-ui react? Here is the render function
render(){
    const { members, user } = this.props;
    let memberOptions = [];
    members.forEach((member, i) => {
      memberOptions.push({
        key: i,
        text: member.user.name,
        value: member.user.id,
        image: { avatar: true, src: member.user.gravatar },
      });
    });
    return (
      <Dropdown placeholder='Select User' fluid selection options={memberOptions} />
    )
  }

This will render perfectly. But I also want to add one more text(say email) in this text field in a new line. So that dropdown items show  similar to this : https://react.semantic-ui.com/elements/list#list-example-relaxed
How can I achieve this?

A: Akhila, I would recommend that you use the content prop instead of the text prop for your Dropdown.Item that you are rendering from your memberOptions array. The text prop specifically expects a string. The content prop will accept anything, including other React components or nodes. So instead of returning text as a string, you could do something like this for content, maybe as a separate class method on your component:
const renderItemContent = (member) => {
  const {
    email,
    name,
  } = member.user;

  const emailStyle = {
    color    : '#333',
    fontSize : '.875em',
  }

  return(
    <React.Fragment>
      {name}
      {email &&

{email}

      }
    </React.Fragment>
  )
}

Then set content: this.renderItemContent(member) on your memberOptionsArray.


Q: How set set bash variable to file name in Docker I have a Dockerfile in which files in a directory are downloaded:
RUN wget https://www.classe.cornell.edu/~cesrulib/downloads/tarballs/ -r -l1 --no-parent -A tgz \
                                     --cut=99 -nH -nv --show-progress --progress=bar:force:noscroll

I know that there is exactly one file here of the form "bmad_dist_YYYY_MMDD.tgz" where "YYYY_MMDD" is a date. For example, the file might be named "bmad_dist_2020_0707.tgz". I want to set a bash variable to the file name without the ".tgz" extension. If this was outside of docker I could use:
FULLNAME=$(ls -1 bmad_dist_*.tgz)
BMADDIST="${FULLNAME%.*}"

So I tried in the dockerfile:
ENV FULLNAME $(ls -1 bmad_dist_*.tgz)
ENV BMADDIST "${FULLNAME%.*}"

But this does not work. Is it possible to do what I want?

A: Shell expansion does not happen in Dockerfile ENV. Then workaround that you can try is to pass the name during Docker build.
Grab the filename during build name and discard the file or you can try --spider for wget to just get the filename.
ARG FULLNAME
ENV FULLNAME=${FULLNAME}

Then pass the full name dynamically during build time.
For example
docker build --build-args FULLNAME=$(wget -nv https://upload.wikimedia.org/wikipedia/commons/5/54/Golden_Gate_Bridge_0002.jpg 2>&1 |cut -d\" -f2) -t my_image .

A: The ENV ... ... syntax is mainly for plaintext content, docker build arguments, or other environment variables. It does not support a subshell like your example.
It is also not possible to use RUN export ... and have that variable defined in downstream image layers.
The best route may be to write the name to a file in the filesystem and read from that file instead of an environment variable. Or, if an environment variable is crucial, you could set an environment variable from the contents of that file in an ENTRYPOINT script.


Q: Test services with real backend in angular I want to test a service, which calls a real backend url and can not find the solution for it. My service has to call data from server and I want to be sure, that the data comes to the service and the service handle it right.
So here is just a simple example of my Login Service:
@Injectable()
export class LoginService {
/**
 * The token, which will be stored on the localStorage.
 */
public token: string;
//Eventemitter, for updating the navigation, when the user logs in
@Output() loggedInEm:EventEmitter<any> = new EventEmitter();

constructor(private http: Http) {
    // set token if saved in local storage
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.token = currentUser && currentUser.token;
}

login(_mail, _pass): Observable<number> {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var data = {
        mail: _mail,
        pass: _pass
    };
    return this.http.post('/login', JSON.stringify(data), {
        headers : headers
    }).map((response: Response) => {
        let res = response.json();
        this.logged = res;
    });
}

public loggedIn() : boolean {
    return this.logged;
}

This is how I want to test it:
describe('Login Service', () => {

    let loginService: LoginService;

    beforeEach(() =>  {
        TestBed.configureTestingModule({
            declarations: [
            ],
            providers: [
                LoginService
            ],
            imports: [
                FormsModule,
                IonicModule
            ],
        });
        inject([LoginService], (service) => {
            loginService = service;
        });
    });

    it("Should login user", () => {
        loginService.login("mail@mail.ru", "123456");
        let loggedIn = loginService.loggedIn();
        expect(loggedIn).toBe(true);
    });
});

But I get following error:
TypeError: Cannot read property 'login' of undefined, so the service must be undefined. I could mock the service, but I want to work it with the real database, which I have on my backend server.
So what could be the problem and how can I solve it?
Kind regards,
Andrej

A: Try this :
it("Should login user", () => {
    loginService.login("mail@mail.ru", "123456").subscribe(value => {
      let loggedIn = loginService.loggedIn();
      expect(loggedIn).toBe(true);
      done();
    });
})