问:
"Abstract Error" shows up when calling methods from child classes
I want to instantiate classes based on a parameter. Both classes are derived from TSample so I define my code as:

```<code>var T: TSample;
</code>```

then I do

```<code>T := TMySample.Create;
</code>```

or

```<code>T := TYourSample.Create;
</code>```

and calling T.Hello gives an "Abstract Error".

```<code>type TSample = class
     public
       procedure Hello; virtual; abstract;
     end;

     TMySample = class(TSample)
     public
       procedure Hello;
     end;

     TYourSample = class(TSample)
     public
       procedure Hello;
     end;

...

procedure TForm1.Button1Click(Sender: TObject);
var T: TSample;
    a: Integer;
begin
  if a = 1 then T := TMySample.Create
  else          T := TYourSample.Create;

  T.Hello;      //Abstract Error here
  T.Free;
end;

procedure TMySample.Hello;
begin
  showmessage('My');
end;

procedure TYourSample.Hello;
begin
  showmessage('Your');
end;
</code>```

答:
You forgot to declare the overridden methods as, well, overridden:

```<code> TMySample = class(TSample)
 public
   procedure Hello; override; // <--
 end;

 TYourSample = class(TSample)
 public
   procedure Hello; override; // <--
 end;
</code>```

Actually, the compiler warned you about this, but you didn't listen :)

```<code>[dcc32 Warning] Unit1.pas(25): W1010 Method 'Hello' hides virtual method of base type 'TSample'
[dcc32 Warning] Unit1.pas(30): W1010 Method 'Hello' hides virtual method of base type 'TSample'
</code>```

Also, you probably already know this, but there are two issues with your sample code:

Since local variables of non-managed types are not initialized, the value of a is undefined.

You don't protect the TSample object, so you might leak resources. (In fact, in this case, you will due to the exception!)

Fixed:

```<code>  a := 123;
  if a = 1 then
    T := TMySample.Create
  else
    T := TYourSample.Create;

  try
    T.Hello;      //Abstract Error here
  finally
    T.Free;
  end;
</code>```

Body:
I want to instantiate classes based on a parameter. Both classes are derived from TSample so I define my code as:

var T: TSample;

then I do

T := TMySample.Create;

or

T := TYourSample.Create;

and calling T.Hello gives an "Abstract Error".

type TSample = class
     public
       procedure Hello; virtual; abstract;
     end;

     TMySample = class(TSample)
     public
       procedure Hello;
     end;

     TYourSample = class(TSample)
     public
       procedure Hello;
     end;

...

procedure TForm1.Button1Click(Sender: TObject);
var T: TSample;
    a: Integer;
begin
  if a = 1 then T := TMySample.Create
  else          T := TYourSample.Create;

  T.Hello;      //Abstract Error here
  T.Free;
end;

procedure TMySample.Hello;
begin
  showmessage('My');
end;

procedure TYourSample.Hello;
begin
  showmessage('Your');
end;

Body:
You forgot to declare the overridden methods as, well, overridden:

 TMySample = class(TSample)
 public
   procedure Hello; override; // <--
 end;

 TYourSample = class(TSample)
 public
   procedure Hello; override; // <--
 end;

Actually, the compiler warned you about this, but you didn't listen :)

[dcc32 Warning] Unit1.pas(25): W1010 Method 'Hello' hides virtual method of base type 'TSample'
[dcc32 Warning] Unit1.pas(30): W1010 Method 'Hello' hides virtual method of base type 'TSample'

Also, you probably already know this, but there are two issues with your sample code:

Since local variables of non-managed types are not initialized, the value of a is undefined.

You don't protect the TSample object, so you might leak resources. (In fact, in this case, you will due to the exception!)

Fixed:

  a := 123;
  if a = 1 then
    T := TMySample.Create
  else
    T := TYourSample.Create;

  try
    T.Hello;      //Abstract Error here
  finally
    T.Free;
  end;


来源: stackexchange

问:
JDBC Class can not be found during runtime
I am creating an application that is utilizing JDBC and am currently having problems running the code without getting java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver. I have done extensive research into trying to solve this issue and nothing i have tried seems to work.

For one, I would like to note that my code works fine when it is run from my IDE (intellij). The database connection works and all the queries execute as necessary. The problem comes when I try to compile and run using javac and java in the terminal. Becuase this is a school project, I will need to enable my professors to be able to run it locally.

Secondly, I am compiling the application using the same jar files that are also included within intellij:

```<code>javac -classpath lib/\* DatabaseDriver.java
</code>```

The lib folder contains my JDBC jar file. You can find the two jar files in this folder here (json.org) and here (connector j). Everything compiles correctly but it seems that once the following execution occurs in the code (see below for the full code) the is a runtime excetion that says the class can not be found:

```<code>Class.forName("com.mysql.cj.jdbc.Driver"); // also tried com.mysql.jdbc.Driver
</code>```

The following code is what I am trying to compile (not the full DatabaseDriver, just enough to reproduce the issue):

```<code>import org.json.JSONObject;
import java.sql.*;

public class DatabaseDriver {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

    public static String runStatement(String sql) throws Exception {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

        return "";
    }//end main

    public static void main(String[] args) throws Exception {
        DatabaseDriver.runStatement("SELECT * FROM employees LIMIT 10");
    }
}
</code>```

This is the full stack that I get when I run the code:

```<code>Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at DatabaseDriver.runStatement(DatabaseDriver.java:15)
        at DatabaseDriver.main(DatabaseDriver.java:40)
</code>```

Problem Summary: I am unable to run this script such that the jar file gets picked up even though it is the same jar file that my IDE is able to properly use. There must be something that I am forgetting or missing to do because all of the solutions I am finding only have to deal with people forgetting to include the correct jar files.

答:
Run your class as given below:

In Unix based systems

```<code>java -cp ".:lib/*" DatabaseDriver
</code>```

In MS Windows

```<code>java -cp ".;lib/*" DatabaseDriver
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating an application that is utilizing JDBC and am currently having problems running the code without getting java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver. I have done extensive research into trying to solve this issue and nothing i have tried seems to work.

For one, I would like to note that my code works fine when it is run from my IDE (intellij). The database connection works and all the queries execute as necessary. The problem comes when I try to compile and run using javac and java in the terminal. Becuase this is a school project, I will need to enable my professors to be able to run it locally.

Secondly, I am compiling the application using the same jar files that are also included within intellij:

javac -classpath lib/\* DatabaseDriver.java

The lib folder contains my JDBC jar file. You can find the two jar files in this folder here (json.org) and here (connector j). Everything compiles correctly but it seems that once the following execution occurs in the code (see below for the full code) the is a runtime excetion that says the class can not be found:

Class.forName("com.mysql.cj.jdbc.Driver"); // also tried com.mysql.jdbc.Driver

The following code is what I am trying to compile (not the full DatabaseDriver, just enough to reproduce the issue):

import org.json.JSONObject;
import java.sql.*;

public class DatabaseDriver {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

    public static String runStatement(String sql) throws Exception {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

        return "";
    }//end main

    public static void main(String[] args) throws Exception {
        DatabaseDriver.runStatement("SELECT * FROM employees LIMIT 10");
    }
}

This is the full stack that I get when I run the code:

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at DatabaseDriver.runStatement(DatabaseDriver.java:15)
        at DatabaseDriver.main(DatabaseDriver.java:40)

Problem Summary: I am unable to run this script such that the jar file gets picked up even though it is the same jar file that my IDE is able to properly use. There must be something that I am forgetting or missing to do because all of the solutions I am finding only have to deal with people forgetting to include the correct jar files.

Body:
Run your class as given below:

In Unix based systems

java -cp ".:lib/*" DatabaseDriver

In MS Windows

java -cp ".;lib/*" DatabaseDriver


问:
onDatachange is called and crash the app when i remove value from firebase
**i am making an app which have function of sending request request to users and i storing senders user id as key and "true"  as value whan user send the request. But when he cancel the request, value removed from the database but on dataChange is called and compare the value with null as in the code **</p>

```<code>friend_requests = FirebaseDatabase.getInstance().getReference().child("Users").child(phone)
                    .child("Friend_Requests").child(user.getPhoneNumber());
            friend_requests.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getValue().equals("null"))
                    {

                    }
                    else
                    {
                        follow.setText("Requested");
                    }
                        Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
</code>```

答:
Try this .You are checking String="null" which is a value . </p>

```<code> @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.getValue()==null)
                {
                   //Logic for cancelled friend request
                }
                else
                {
                    follow.setText("Requested");
                }
                    Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

            }
</code>```

Body:
**i am making an app which have function of sending request request to users and i storing senders user id as key and "true"  as value whan user send the request. But when he cancel the request, value removed from the database but on dataChange is called and compare the value with null as in the code **

friend_requests = FirebaseDatabase.getInstance().getReference().child("Users").child(phone)
                    .child("Friend_Requests").child(user.getPhoneNumber());
            friend_requests.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getValue().equals("null"))
                    {

                    }
                    else
                    {
                        follow.setText("Requested");
                    }
                        Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

Body:
Try this .You are checking String="null" which is a value .

 @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.getValue()==null)
                {
                   //Logic for cancelled friend request
                }
                else
                {
                    follow.setText("Requested");
                }
                    Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

            }


问:
Did VB 6/.NET interop recently get broken by a Windows update?
Recently a VB 6 application using .NET 1.1/2.0 components stopped working on my companies XP machines. The IT department was installing Windows patches at the time, so I'm wondering if anyone has heard of an update breaking VB 6/.NET interop?</p>

答: Are you running the COM+ components as proxies against other servers? If so, I've had problems before when installing e.g. SP2 for Windows 2003 server, in that the COM+ settings (Component Services, root node) have had the "remote activation" security setting permission missing after the update. Don't know if this is your problem, though.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Trying to understand and reproduce Regex Pattern
I am currently trying to understand Pattern and Matcher a little bit more and found the following code:

```<code>private static final Pattern PATTERN = Pattern.compile(
            String.format("addPart%s(?<assembly>%s)\\+(?<amount>%s)%s(?<part>%s)",
                    InOutputStrings.COMMAND_SEPARATOR,
                    InOutputStrings.NAME_PATTERN,
                    InOutputStrings.NUMBER_PATTERN,
                    InOutputStrings.INNER_SEPARATOR,
                    InOutputStrings.NAME_PATTERN));

    private String assemblyName;
    private int amount;
    private String partName;

    ...

    assemblyName = matcher.group("assembly");
    amount = tryParse(matcher.group("amount"));
    partName = matcher.group("part");
</code>```

whereby

```<code>    NAME_PATTERN("[a-zA-Z]+"),
    NUMBER_PATTERN("(?!(0[0-9]))[0-9]+"),
    COMMAND_SEPARATOR(" "),
    ARGUMENT_SEPARATOR(";"),
    INNER_SEPARATOR(":")
</code>```

What would be a valid input here?

Could someone show me how this would look like for the input-pattern

"add track <startPoint> -> <endPoint>"?

I am working on a Command-line pattern and this would be a good way of implementing the input parsing.

Also, what is the meaning of "?", "\\+" and "<assembly>"...?

答:
What would be a valid input here?

addPart foo+42:bar

...how this would look like for the input-pattern...

add track (?<startPoint>[a-zA-Z]+) -> (?<endPoint>[a-zA-Z]+)

...what is the meaning of...

?! is a Negative Lookahead

?<assembly> is a Named Capturing Group

\\+ is a literal plus sign (not a RegEx operator)

Also note that %s is a variable reference for String.format. It is not a RegEx operator either.

Body:
I am currently trying to understand Pattern and Matcher a little bit more and found the following code:

private static final Pattern PATTERN = Pattern.compile(
            String.format("addPart%s(?<assembly>%s)\\+(?<amount>%s)%s(?<part>%s)",
                    InOutputStrings.COMMAND_SEPARATOR,
                    InOutputStrings.NAME_PATTERN,
                    InOutputStrings.NUMBER_PATTERN,
                    InOutputStrings.INNER_SEPARATOR,
                    InOutputStrings.NAME_PATTERN));

    private String assemblyName;
    private int amount;
    private String partName;

    ...

    assemblyName = matcher.group("assembly");
    amount = tryParse(matcher.group("amount"));
    partName = matcher.group("part");

whereby

    NAME_PATTERN("[a-zA-Z]+"),
    NUMBER_PATTERN("(?!(0[0-9]))[0-9]+"),
    COMMAND_SEPARATOR(" "),
    ARGUMENT_SEPARATOR(";"),
    INNER_SEPARATOR(":")

What would be a valid input here?

Could someone show me how this would look like for the input-pattern

"add track <startPoint> -> <endPoint>"?

I am working on a Command-line pattern and this would be a good way of implementing the input parsing.

Also, what is the meaning of "?", "\\+" and "<assembly>"...?


问:
Images disappear from page when other image is displayed
I have some tabs and there are several buttons in the third tab which display different images when clicked. The problem is that when any of these buttons are clicked and an image is displayed, all the other images on my web page disappear. Perhaps this is because I'm not appending the images to that particular tab?
What do I need to add/change in my code to fix this issue?

// tabs
function selectTab(tabIndex) {

    document.getElementById('tab1Content').style.display = "none";
    document.getElementById('tab2Content').style.display = "none";
    document.getElementById('tab3Content').style.display = "none";
    document.getElementById('tab4Content').style.display = "none";

    document.getElementById('tab1').classList.remove("active");
    document.getElementById('tab2').classList.remove("active");
    document.getElementById('tab3').classList.remove("active");
    document.getElementById('tab4').classList.remove("active");

    document.getElementById('tab' + tabIndex + 'Content').style.display = "block";

    document.getElementById('tab' + tabIndex).classList.add("active");
}

// Colour Swatch
function showImage(el, id = 'tab3Content') {
    var images = document.getElementById('img1');
    Array.from(images).forEach(i => i.style.display = 'none');
    var img = document.createElement('img');
    img.style.marginTop = '-50px'
    img.setAttribute("width", "850");
    img.setAttribute("height", "500");
    img.setAttribute("src", "");;
    if(el.getAttribute('data-id') == '1'){
      }
    else if(el.getAttribute('data-id') == '2'){
    img.setAttribute("src", "");;
    }
    else if(el.getAttribute('data-id') == '3'){
        img.setAttribute("src", "");;
      }
      else if(el.getAttribute('data-id') == '4'){
        img.setAttribute("src", "");;
      }

  document.getElementById(id).appendChild(img);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab {
    border-radius: 0.5px;
}
  .tabButton {
    color: #FFFFFF;
    border: 1px solid;
    border-color:  rgb(45, 68, 117);
    border-radius: 0.3em;
    color:  rgb(45, 68, 117);
    margin-top: 50px;
    background-color: white;
    margin-left: 70px;
    padding-left: 100px;
    padding-right: 100px;
    padding-top: 14px;
    padding-bottom: 14px;
    margin-right: -75px;
 }</code>```

           <button class="tabButton active" id="tab1" onClick="selectTab(1);">Tab1</button>
           <button class="tabButton" id="tab2" onClick="selectTab(2);">Tab2</button>
           <button class="tabButton" id="tab3" onClick="selectTab(3);">Tab3</button>
           <button class="tabButton" id="tab4" onClick="selectTab(4);">Tab4</button>

tab 1

Tab 2

           <button class="colour-btn colour-btn--1"data-id="1"  onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--2" data-id="2" onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--3"data-id="3"  onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--4"data-id="4"  onClick="showImage(this)"></button>

tab4

```

答:
Simply change var images = document.querySelectorAll('img'); to a more specific selector.

'img' targets every image tag () on your page.

Perhaps var images = document.querySelectorAll('.img'); is what you want (or '.img-position?) with a dot to point to a class.

Body:
I have some tabs and there are several buttons in the third tab which display different images when clicked. The problem is that when any of these buttons are clicked and an image is displayed, all the other images on my web page disappear. Perhaps this is because I'm not appending the images to that particular tab?
What do I need to add/change in my code to fix this issue?

// tabs
function selectTab(tabIndex) {

    document.getElementById('tab1Content').style.display = "none";
    document.getElementById('tab2Content').style.display = "none";
    document.getElementById('tab3Content').style.display = "none";
    document.getElementById('tab4Content').style.display = "none";

    document.getElementById('tab1').classList.remove("active");
    document.getElementById('tab2').classList.remove("active");
    document.getElementById('tab3').classList.remove("active");
    document.getElementById('tab4').classList.remove("active");

    document.getElementById('tab' + tabIndex + 'Content').style.display = "block";

    document.getElementById('tab' + tabIndex).classList.add("active");
}

// Colour Swatch
function showImage(el, id = 'tab3Content') {
    var images = document.getElementById('img1');
    Array.from(images).forEach(i => i.style.display = 'none');
    var img = document.createElement('img');
    img.style.marginTop = '-50px'
    img.setAttribute("width", "850");
    img.setAttribute("height", "500");
    img.setAttribute("src", "");;
    if(el.getAttribute('data-id') == '1'){
      }
    else if(el.getAttribute('data-id') == '2'){
    img.setAttribute("src", "");;
    }
    else if(el.getAttribute('data-id') == '3'){
        img.setAttribute("src", "");;
      }
      else if(el.getAttribute('data-id') == '4'){
        img.setAttribute("src", "");;
      }

  document.getElementById(id).appendChild(img);
}

.tab {
    border-radius: 0.5px;
}
  .tabButton {
    color: #FFFFFF;
    border: 1px solid;
    border-color:  rgb(45, 68, 117);
    border-radius: 0.3em;
    color:  rgb(45, 68, 117);
    margin-top: 50px;
    background-color: white;
    margin-left: 70px;
    padding-left: 100px;
    padding-right: 100px;
    padding-top: 14px;
    padding-bottom: 14px;
    margin-right: -75px;
 }

           <button class="tabButton active" id="tab1" onClick="selectTab(1);">Tab1</button>
           <button class="tabButton" id="tab2" onClick="selectTab(2);">Tab2</button>
           <button class="tabButton" id="tab3" onClick="selectTab(3);">Tab3</button>
           <button class="tabButton" id="tab4" onClick="selectTab(4);">Tab4</button>

tab 1

Tab 2

           <button class="colour-btn colour-btn--1"data-id="1"  onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--2" data-id="2" onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--3"data-id="3"  onClick="showImage(this)"></button>
           <button class="colour-btn colour-btn--4"data-id="4"  onClick="showImage(this)"></button>

tab4

Body:
Simply change var images = document.querySelectorAll('img'); to a more specific selector.

'img' targets every image tag (<img>) on your page.

Perhaps var images = document.querySelectorAll('.img'); is what you want (or '.img-position?) with a dot to point to a class.


问:
How to set `__class__.__name__` as class attribute?
I need to get class name from class:

class Cls:
    notation = None

    def __init__(self):
        notation = self.__class__.__name__
```

print(Cls.notation) prints None but I need 'Cls'

How to fix it or how to define class attribute which returns a name of class?

答:
You are assigning to a local variable, not the class attribute:

```<code>def __init__(self):
    Cls.notation = self.__class__.__name__
</code>```

Note that self.__class__ isn't necessarily Cls, if there is a subclass of Cls involved. You might want to use

```<code>def __init__(self):
    type(self).notation = self.__class__.__name__
</code>```

depending on your use case.

Assigning to self.notation won't work, because that creates an instance attribute that shadows the class attribute.

If you want Cls.notation == "Cls" immediately after the class is defined, you may as well just hard-code it:

```<code>class Cls:
    notation = "Cls"
</code>```

or

```<code>class Cls:
    pass

Cls.notation = Cls.__name__
</code>```

though you can also write

```<code>class Cls:
    notation = __qualname__
</code>```

to set its value based on the name used in the first line of the statement, though __qualname__ takes into account nesting as well:

```<code>class Cls1:
    class Cls2:
        notation = __qualname__  # "Cls1.Cls2", not "Cls2"
</code>```

Body:
I need to get class name from class:

class Cls:
    notation = None

    def __init__(self):
        notation = self.__class__.__name__

print(Cls.notation) prints None but I need 'Cls'

How to fix it or how to define class attribute which returns a name of class?

Body:
You are assigning to a local variable, not the class attribute:

def __init__(self):
    Cls.notation = self.__class__.__name__

Note that self.__class__ isn't necessarily Cls, if there is a subclass of Cls involved. You might want to use

def __init__(self):
    type(self).notation = self.__class__.__name__

depending on your use case.

Assigning to self.notation won't work, because that creates an instance attribute that shadows the class attribute.

If you want Cls.notation == "Cls" immediately after the class is defined, you may as well just hard-code it:

class Cls:
    notation = "Cls"

or

class Cls:
    pass

Cls.notation = Cls.__name__

though you can also write

class Cls:
    notation = __qualname__

to set its value based on the name used in the first line of the statement, though __qualname__ takes into account nesting as well:

class Cls1:
    class Cls2:
        notation = __qualname__  # "Cls1.Cls2", not "Cls2"


问:
Can I add attributes to an object property at runtime?
For example I want to remove or change below property attributes or add a new one. Is it possible?</p>

```<code>[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
  get { return billInfo; }
  set { billInfo = value; }
}
</code>```

答:
It is not possible to add/remove attributes from a class at runtime.

It is possible however to update the way XML serialization works at runtime without needing to edit attributes.  See Marc's post.

EDIT Updated

OwnerDisplayName: Alish

Body:
For example I want to remove or change below property attributes or add a new one. Is it possible?

[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
  get { return billInfo; }
  set { billInfo = value; }
}

LastEditorDisplayName: Dimitre Novatchev

OwnerDisplayName: JaredPar

LastEditorDisplayName: JaredPar


问:
Java: runtime method resolution
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

```<code>package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}
</code>```

答:
I've had some success with MVEL and properties, but I can't recall whether it can dispatch method calls.

However, you might be looking for different language entirely. Given the nature of the problem, I suggest taking a look at Groovy, which integrates very cleanly with Java.

Title: Java: runtime method resolution

Body:
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}


问:
Is it proper to use size_t for count in a bitshift operation?
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

```<code>uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}
</code>```

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

```<code>deltaSwap(b, 63, 0x0000000000000001);
</code>```

or if you wish to reverse the order of the bits:

```<code>deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);
</code>```

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

```<code>uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}
</code>```

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

答:
If you really want to be pedantic, shouldn't delta be of type size_t?

No, if you really want to be pedantic, delta should just be an unsigned integer type capable of holding at least the range of values from 0 to sizeof(uint64_t) * CHAR_BIT. In your case that's [0, 63]. There's no real need to have it be size_t.

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

In terms of correctness of code, it's ok. In terms of optimization it doesn't make much sense. size_t is used to hold a size, because it's a type guaranteed to be capable to hold the biggest possible size of an object. It's certainly not guaranteed to be any faster than a normal unsigned or any other unsigned integer type (see bottom of the answer for this).

Another important thing to notice is that this:

```<code> b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta
</code>```

Is undefined behavior according to the C standard, since you are using the value of a variable while also applying a side effect to it in the same statement (see paragraph 6.5 point 2, page 76 here).

The correct way to do what you want is:

```<code>mask &= b ^ (b >> delta);
return b ^ (mask ^ (mask << delta));
</code>```

In any case always take extra care when working with bitshift operators since they have precedence over other bit operators. Using extra parentheses or splitting expressions into multiple lines doesn't hurt performance and improves readability. A decent compiler will optimize the above without any problem.

Now, back to the real reason you're asking this question: optimization.

The correct way to optimize your code is to let the compiler choose the optimal size of the variable that you need. For this purpose, you only need one byte, and you can use uint_fast8_t from stdint.h, which is the fastest (implementation defined) unsigned integer type with width of at least 8 bits. The compiler will choose the fastest width for its purpose.

With the above being said, the correct way to optimize your code is:

```<code>uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, uint64_t mask )
{
    mask &= b ^ (b >> delta);
    return b ^ (mask ^ (mask << delta));
}
</code>```

Depending on what you're doing it might as well make sense to declare the function as inline __attribute__ ((always_inline)) if GCC does not already inline the code for you, though the compiler is usually better at figuring out when to inline code and when not. Your function is most probably already going to be inlined.

One more important thing: using the right optimization flags often matters more than hand-tuning code. For example, for the above code, you might want to compile with -Ofast -march=native, and maybe even other flags depending on where you use the function (e.g. -ftree-vectorize if used in a loop).

Other than the above: benchmarking, switching to hand-tuned assembly with an asm() statement and looking at the surrounding code are the only ways to optimize the above further, assuming that the formula is already simplified to its core.

Body:
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

deltaSwap(b, 63, 0x0000000000000001);

or if you wish to reverse the order of the bits:

deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

Body:
If you really want to be pedantic, shouldn't delta be of type size_t?

No, if you really want to be pedantic, delta should just be an unsigned integer type capable of holding at least the range of values from 0 to sizeof(uint64_t) * CHAR_BIT. In your case that's [0, 63]. There's no real need to have it be size_t.

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

In terms of correctness of code, it's ok. In terms of optimization it doesn't make much sense. size_t is used to hold a size, because it's a type guaranteed to be capable to hold the biggest possible size of an object. It's certainly not guaranteed to be any faster than a normal unsigned or any other unsigned integer type (see bottom of the answer for this).

Another important thing to notice is that this:

 b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta

Is undefined behavior according to the C standard, since you are using the value of a variable while also applying a side effect to it in the same statement (see paragraph 6.5 point 2, page 76 here).

The correct way to do what you want is:

mask &= b ^ (b >> delta);
return b ^ (mask ^ (mask << delta));

In any case always take extra care when working with bitshift operators since they have precedence over other bit operators. Using extra parentheses or splitting expressions into multiple lines doesn't hurt performance and improves readability. A decent compiler will optimize the above without any problem.

Now, back to the real reason you're asking this question: optimization.

The correct way to optimize your code is to let the compiler choose the optimal size of the variable that you need. For this purpose, you only need one byte, and you can use uint_fast8_t from stdint.h, which is the fastest (implementation defined) unsigned integer type with width of at least 8 bits. The compiler will choose the fastest width for its purpose.

With the above being said, the correct way to optimize your code is:

uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, uint64_t mask )
{
    mask &= b ^ (b >> delta);
    return b ^ (mask ^ (mask << delta));
}

Depending on what you're doing it might as well make sense to declare the function as inline __attribute__ ((always_inline)) if GCC does not already inline the code for you, though the compiler is usually better at figuring out when to inline code and when not. Your function is most probably already going to be inlined.

One more important thing: using the right optimization flags often matters more than hand-tuning code. For example, for the above code, you might want to compile with -Ofast -march=native, and maybe even other flags depending on where you use the function (e.g. -ftree-vectorize if used in a loop).

Other than the above: benchmarking, switching to hand-tuned assembly with an asm() statement and looking at the surrounding code are the only ways to optimize the above further, assuming that the formula is already simplified to its core.


问:
In ChartJS is it possible to change the line style between different points?
Using ChartJs (v2.2.2) can you change the line style between the last 2 points on a graph. e.g. have a solid line all the way and then dashed at the end? see picture below

答:
You can create a scatter chart and draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that can be used for performing custom code. The advantage of this approach is that you can customize the style of every single connection line (width, color, dash pattern etc.).

const labels = [1, 2, 3, 4, 5, 6];
const values = [12, 19, 3, 5, 2, 3];
const data = labels.map((label, index) => ({ x: label, y: values[index]}));

var lineChart = new Chart(document.getElementById("chart"), {
  type: "scatter",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = '#922893';
           ctx.lineWidth = 2;
           if (index + 1 == data.length) {
             ctx.setLineDash([5, 10]);
           }
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: '#922893',
      pointBackgroundColor: "transparent"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          stepSize: 1
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="90"></canvas></code>```

Body:
You can create a scatter chart and draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that can be used for performing custom code. The advantage of this approach is that you can customize the style of every single connection line (width, color, dash pattern etc.).

const labels = [1, 2, 3, 4, 5, 6];
const values = [12, 19, 3, 5, 2, 3];
const data = labels.map((label, index) => ({ x: label, y: values[index]}));

var lineChart = new Chart(document.getElementById("chart"), {
  type: "scatter",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = '#922893';
           ctx.lineWidth = 2;
           if (index + 1 == data.length) {
             ctx.setLineDash([5, 10]);
           }
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: '#922893',
      pointBackgroundColor: "transparent"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          stepSize: 1
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="90"></canvas>


问:
How do I change the color of the clicked button in my menu bar?

I need some help changing the color of the clicked menu button! Ive looked everywhere for an answser on wordpress, and now I am looking to the internet! As you can see from the picture, the colors are black and orange, and the blue does not go with that. Please Help.

答:
You can use the CSS element state (Active, and Visited) to specify the color needed.

```<code>a:visited, a:active {
color: red;
}
</code>```

You can change the 'a' with the element class. You can send me your website URL and I will prepare the right code for you.

Thanks, let me know if I can help.

Body:
You can use the CSS element state (Active, and Visited) to specify the color needed.

a:visited, a:active {
color: red;
}

You can change the 'a' with the element class. You can send me your website URL and I will prepare the right code for you.

Thanks, let me know if I can help.


问:
SQL - Updating specific rows based on group by count
I want to update a set of rows if they fall within the result of a group by + having criteria:

Example Table:

```<code>equip_id | fiber_id | new_col
-----+-------------------------------------------------------------------
A        | 1        | *update this row/col because there are (3) A's
A        | 2        | *update this row/col because there are (3) A's
A        | 3        | *update this row/col because there are (3) A's
B        | 1        | *dont update this row/col because there are (4) B's
B        | 2        | *dont update this row/col because there are (4) B's
B        | 3        | *dont update this row/col because there are (4) B's
B        | 4        | *dont update this row/col because there are (4) B's
</code>```

I want to update new_col only where GROUP BY equip_id HAVING count(equip_id) = 3

Since GROUP BY is not supported in UPDATE, how do I achieve this result?

答:
The correct answer is already given by Andronicus.

Below is just another way. Not sure it is more effective.

```<code>update table_name set new_col=NEW_VALUE
where equip_id in

(
  select equip_id from table_name a
    where 3=
     (
       select count(*) from table_name b where
       a.equip_id=b.equip_id
     )
)
</code>```

Body:
I want to update a set of rows if they fall within the result of a group by + having criteria:

Example Table:

equip_id | fiber_id | new_col
-----+-------------------------------------------------------------------
A        | 1        | *update this row/col because there are (3) A's
A        | 2        | *update this row/col because there are (3) A's
A        | 3        | *update this row/col because there are (3) A's
B        | 1        | *dont update this row/col because there are (4) B's
B        | 2        | *dont update this row/col because there are (4) B's
B        | 3        | *dont update this row/col because there are (4) B's
B        | 4        | *dont update this row/col because there are (4) B's

I want to update new_col only where GROUP BY equip_id HAVING count(equip_id) = 3

Since GROUP BY is not supported in UPDATE, how do I achieve this result?

Body:
The correct answer is already given by Andronicus.

Below is just another way. Not sure it is more effective.

update table_name set new_col=NEW_VALUE
where equip_id in

(
  select equip_id from table_name a
    where 3=
     (
       select count(*) from table_name b where
       a.equip_id=b.equip_id
     )
)


问:
ETL batch processing
I'm looking for some open source technology that will allow me to create scheduled batch processing (e.g. Query every 1 hour some SQL DB like Oracle, and insert to Kafka. It is possible that some transformation will be done to the data between). The thing is that I need to be able to transport large amount of data ("big data" - Oracle queries could return 10GB or more).

I read about Apache Airflow for example, but it does not seem to fit for large amount of data.

What other technologies can I use for that purpose?

答:
Is Quartz Scheduler good enough for your use case?

While it is a general purpose job scheduling library, but I think it could be used for long-running ETL tasks too.

Quote from official website:

Quartz is a richly featured, open source job scheduling library that
  can be integrated within virtually any Java application - from the
  smallest stand-alone application to the largest e-commerce system.
  Quartz can be used to create simple or complex schedules for executing
  tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks
  are defined as standard Java components that may execute virtually
  anything you may program them to do. The Quartz Scheduler includes
  many enterprise-class features, such as support for JTA transactions
  and clustering.

Quartz is freely usable, licensed under the Apache 2.0 license.

Title: ETL batch processing


问:
Accessing a control created at runtime
I am new to c# and wpf.

If I create a control in XAML, I can access its properties anywhere in my code.
However, if I create a control at runtime, it shows up as null when I try to access it outside the method it was created.

```<code>public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        spTest.Children.Add(newBtn);

    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
         //I want to access the button called btnTest and display the name of the button
    }
}
</code>```

答:
There are several complications to what you're doing here which aren't immediately obvious.
One of which is you can't just define some handler and it'll work.
You also have to subscribe it to the event.
It's a delegate you're sort of plugging into an event.

Like an electrical appliance, you need to plug it in before anything is going to happen.

Here's some markup and code to explore what's going on.

So I can see messages I'll use a listbox which I'll add items to. These will be displayed as a list of messages.

```<code>    Title="MainWindow" Height="450" Width="800"
    Button.Click="Window_Button_Click">
    <Grid Name="agrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox Name="lb"
                 Grid.Column="1"/>
    </Grid>
</code>```

I hook up a button click handler at window level.
This will handle click events that bubble up to it from anywhere inside the window.
Read up on bubbling and tunnelling routed events if this is a new concept to you.

https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/routed-events-overview

Then, I'm going to dynamically add a button.
This will default to column 0 of the grid and appear on the left.

As you will see if you try it.

I also subscribe two more events of the button.

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        agrid.Children.Add(newBtn);
        newBtn.MouseUp += NewBtn_MouseUp;
        newBtn.PreviewMouseDown += NewBtn_PreviewMouseDown;
    }

    private void NewBtn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Button btn = sender as Button;
        string theName = btn?.Name ?? "Something was Preview Mouse Downed but I don't know what";
        lb.Items.Add($"Button PREVIEW MouseUp {theName}");
    }

    private void NewBtn_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Button btn = sender as Button;
        string theName = btn?.Name ?? "Something was Mouse Upped but I don't know what";
        lb.Items.Add($"Button MouseUp {theName}");
    }

    private void Window_Button_Click(object sender, RoutedEventArgs e)
    {
        Button btn = e.OriginalSource as Button;
        string theName = btn?.Name ?? "Something was CLICKED in the window but I don't know what";
        lb.Items.Add($"Window Button Click {theName}");
    }
}
</code>```

The code above is rather quick and dirty.

Notice a bubbling event handler is interested in the originalsource of the event since it's passed up the tree and sender isn't going to be the button.

f5 to spin her up and click the button.

There is a surprise waiting for you there.

No message from mouseup.

This is because the button is designed to be clicked rather than mousedown and mouse upped.
Code in ButtonBase does stuff with some of the mouse events and because it handles them, your handler will not fire.

So that's hopefully explained a few things about events.

There are a few things I should also mention though.

Almost all wpf development uses MVVM and will bind a command to the command property of a button rather than using events at all.

Adding dynamic content is also not usually done in code like this.

There are a number of options which include datatemplates.  This is very common with an approach called viewmodel first.

You can also build UI by translating xaml as a string into controls. This is the recommended way to build UI which must be dynamic when you cannot use styling or templating. It's probably too early for you to delve into this stuff but FYI https://social.technet.microsoft.com/wiki/contents/articles/28797.wpf-dynamic-xaml.aspx

Title: Accessing a control created at runtime

Body:
I am new to c# and wpf.

If I create a control in XAML, I can access its properties anywhere in my code.
However, if I create a control at runtime, it shows up as null when I try to access it outside the method it was created.

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        spTest.Children.Add(newBtn);

    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
         //I want to access the button called btnTest and display the name of the button
    }
}

Body:
There are several complications to what you're doing here which aren't immediately obvious.
One of which is you can't just define some handler and it'll work.
You also have to subscribe it to the event.
It's a delegate you're sort of plugging into an event.

Like an electrical appliance, you need to plug it in before anything is going to happen.

Here's some markup and code to explore what's going on.

So I can see messages I'll use a listbox which I'll add items to. These will be displayed as a list of messages.

    Title="MainWindow" Height="450" Width="800"
    Button.Click="Window_Button_Click">
    <Grid Name="agrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox Name="lb"
                 Grid.Column="1"/>
    </Grid>

I hook up a button click handler at window level.
This will handle click events that bubble up to it from anywhere inside the window.
Read up on bubbling and tunnelling routed events if this is a new concept to you.

https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/routed-events-overview

Then, I'm going to dynamically add a button.
This will default to column 0 of the grid and appear on the left.

As you will see if you try it.

I also subscribe two more events of the button.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        agrid.Children.Add(newBtn);
        newBtn.MouseUp += NewBtn_MouseUp;
        newBtn.PreviewMouseDown += NewBtn_PreviewMouseDown;
    }

    private void NewBtn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Button btn = sender as Button;
        string theName = btn?.Name ?? "Something was Preview Mouse Downed but I don't know what";
        lb.Items.Add($"Button PREVIEW MouseUp {theName}");
    }

    private void NewBtn_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Button btn = sender as Button;
        string theName = btn?.Name ?? "Something was Mouse Upped but I don't know what";
        lb.Items.Add($"Button MouseUp {theName}");
    }

    private void Window_Button_Click(object sender, RoutedEventArgs e)
    {
        Button btn = e.OriginalSource as Button;
        string theName = btn?.Name ?? "Something was CLICKED in the window but I don't know what";
        lb.Items.Add($"Window Button Click {theName}");
    }
}

The code above is rather quick and dirty.

Notice a bubbling event handler is interested in the originalsource of the event since it's passed up the tree and sender isn't going to be the button.

f5 to spin her up and click the button.

There is a surprise waiting for you there.

No message from mouseup.

This is because the button is designed to be clicked rather than mousedown and mouse upped.
Code in ButtonBase does stuff with some of the mouse events and because it handles them, your handler will not fire.

So that's hopefully explained a few things about events.

There are a few things I should also mention though.

Almost all wpf development uses MVVM and will bind a command to the command property of a button rather than using events at all.

Adding dynamic content is also not usually done in code like this.

There are a number of options which include datatemplates.  This is very common with an approach called viewmodel first.

You can also build UI by translating xaml as a string into controls. This is the recommended way to build UI which must be dynamic when you cannot use styling or templating. It's probably too early for you to delve into this stuff but FYI https://social.technet.microsoft.com/wiki/contents/articles/28797.wpf-dynamic-xaml.aspx


问:
How do I call a function immediately upon an iPhone app resuming from a saved state?

User has my app open.

They hit the home button, resulting in my app closing and going into a "saved state".

Users uses his device for other things.

User opens up my app again, resuming from where he left off.

How, in my code, do I detect that the user has resumed from the saved state? Is there a specific iOS4 multitasking NSNotification that I can attach to?

答:
Implement applicationDidBecomeActive: in your app delegate.

See also:

applicationWillEnterForeground vs. applicationDidBecomeActive, applicationWillResignActive vs. applicationDidEnterBackground

Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?"


问:
Nested JSON data via AJAX with jquery but getting undefined value
Javascript

JSON

Web Inspect

I have got an error message.
Uncaught ReferenceError: products is not defined.

```<code>$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
    });
</code>```

JSON

```<code>
{
     "id": "2",
     "send_id": "10",
     "tracking_id": "TI-000000010",
     "user_id": "10",
     "username": "istiaqahmed",
     "email": "istiaqahmed121998@gmail.com",
     "phone": "0176430886",
     "company_name": "EVALY.COM.BD",
     "company_phone": "01747588386",
     "company_address": "Dhanmondi 28",
     "com_email": "evaly@gmail.com",
     "delivery_type": "Standard",
     "packing": "regular",
     "product_weight": "1",
     "preferred_time": "morning",
     "delivery_charge": "60",
     "customer_name": "Zenith Jhony",
     "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli",
     "to_phone": "01776065208",
     "to_zone": "Dhaka",
     "to_post_code": "1207",
     "date": "2020-01-09 23:26:10",
     "u_status": "Approve",
     "notes": "note",
     "products": [
          {
               "product_id": "1",
               "product_name": "shampoo",
               "product_quantity": "2",
               "product_price": "2333",
               "customer_send_id": "10"
          },
          {
                "product_id": "2",
               "product_name": "assf",
               "product_quantity": "1",
               "product_price": "232",
               "customer_send_id": "10"
          }
     ]
 }
</code>```

答:
You are trying to reference an attribute which does not exist.

lets say you assign that JSON object o a variable like this:

```<code>obj = {
  .... the JSON
}
</code>```

you could then pass the JSON as follows

```<code>data:{products:obj.products}
</code>```

Body:
Javascript

JSON

Web Inspect

I have got an error message.
Uncaught ReferenceError: products is not defined.

$(document).ready(function(){
    $("div").on("click", "a", function(){
        var delivery_id = $(this).attr("id");
        $.ajax({
            url:"http://localhost:8888/dashboard/fetch_edit.php",
            method:"POST",
            data:{products:products},}
        });
    });

JSON

{
     "id": "2",
     "send_id": "10",
     "tracking_id": "TI-000000010",
     "user_id": "10",
     "username": "istiaqahmed",
     "email": "istiaqahmed121998@gmail.com",
     "phone": "0176430886",
     "company_name": "EVALY.COM.BD",
     "company_phone": "01747588386",
     "company_address": "Dhanmondi 28",
     "com_email": "evaly@gmail.com",
     "delivery_type": "Standard",
     "packing": "regular",
     "product_weight": "1",
     "preferred_time": "morning",
     "delivery_charge": "60",
     "customer_name": "Zenith Jhony",
     "to_address1": "75\/1 Jafrabad Pulpar Pabna House Goli",
     "to_phone": "01776065208",
     "to_zone": "Dhaka",
     "to_post_code": "1207",
     "date": "2020-01-09 23:26:10",
     "u_status": "Approve",
     "notes": "note",
     "products": [
          {
               "product_id": "1",
               "product_name": "shampoo",
               "product_quantity": "2",
               "product_price": "2333",
               "customer_send_id": "10"
          },
          {
                "product_id": "2",
               "product_name": "assf",
               "product_quantity": "1",
               "product_price": "232",
               "customer_send_id": "10"
          }
     ]
 }

Body:
You are trying to reference an attribute which does not exist.

lets say you assign that JSON object o a variable like this:

obj = {
  .... the JSON
}

you could then pass the JSON as follows

data:{products:obj.products}


问:
How to Pass-through Physical NIC to Docker Container?
Is it possible to pass-through eth(n) to Docker Container without additional plugin installation? </p>

<p>In LXC/LXD it is easy by this command: </p>

```<code>lxc config device add CONTAINER-NAME eth2 nic nictype=physical parent=eth2 name=eth2
</code>```

答:
As of now, there is no mode or mechanism to pass a network interface directly to a container. However, there are network plugins that allow to have direct/passthrough access to the Ethernet networking device to the Docker container(s)

The bridge mode has one interface to host namespace and all containers on the host are attached to docker0 via veth-pair. Here, docker0 is a linux bridge created by docker daemon. The docker assigns private IP to the containers

In host mode, the networking namespace of host shall be shared with outside world. Here port mapping can be used to reach services. Here, the container shares the IP of docker host. Kindly refer to Networking using host network. Host mode networking can be useful in situations where a container needs to handle a large range of ports.

Here is reference to a sample application based on macvlan which can be helpful as well. You can use the macvlan network driver to assign a MAC address to each container’s virtual network interface, making it appear to be a physical network interface directly connected to the physical network. This ensures that for the network devices on your network, your container appears to be physically attached to the network.

Body:
Is it possible to pass-through eth(n) to Docker Container without additional plugin installation?

In LXC/LXD it is easy by this command:

lxc config device add CONTAINER-NAME eth2 nic nictype=physical parent=eth2 name=eth2


问:
How do I set up an automated CSV export job from Azure SQL Server?
In an on-prem SQL Server I have the option to set up scheduled Jobs with the SQL Server Agent. This feature is not present in Azure. Is there any way to do this easily in Azure or will I have to rely on automation scripts  / powershell scripting for this?

The task I want to accomplish is to export a bunch of SQL views to CSV and send them to a remote FTP server.

答:
One option is to use Azure Data Factory and create a copy activity that use Azure SQL Database as a source and SFTP as a sink.  Use copy activity to copy data from any supported data store to your SFTP server located on-premises or in the cloud. You can schedule execution on Azure Data Factory as shown here.

Another option is using Azure Logic Apps with the Azure SQL Database connector and FTP connector to access/manage SQL Database and FTP server. You can create, schedule, and run recurring tasks with Azure Logic Apps as shown here.


问:
LNK2028 LNK2029 when compiling static c++ library in managed c++/clr
As i am pretty much out of ideas and the google results by now have reached the point where they hit ~10 and less, i now turn here in hope of seeing the answer or at least a clue that leads me to the actual solution.

I am creating a project that can be distributed as executable, non-static library and static library.
I want to use the library in a WPF project (C#) which is why i created a simple CLR wrapper.

It all worked very well up until the most recent change introduced into the base-library.
Now, i get linkage errors (5 in total) on all calls to the "main" class in the library project:

```<code>1>wrapper.obj : error LNK2028: unresolved token (0A0016EB) "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall sqf::vmstack::dump_callstack_diff(class std::shared_ptr<class sqf::callstack>)" (?dump_callstack_diff@vmstack@sqf@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@V?$shared_ptr@Vcallstack@sqf@@@4@@Z) referenced in function "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall SqfVm::wrapper::get_stackdump(void)" (?get_stackdump@wrapper@SqfVm@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@XZ)
1>wrapper.obj : error LNK2028: unresolved token (0A0016F5) "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall sqf::virtualmachine::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@virtualmachine@sqf@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z) referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall SqfVm::wrapper::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@wrapper@SqfVm@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z)
1>wrapper.obj : error LNK2028: unresolved token (0A0016F6) "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@AA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z) referenced in function "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall sqf::virtualmachine::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@virtualmachine@sqf@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z) referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall SqfVm::wrapper::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@wrapper@SqfVm@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@AA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z) referenced in function "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall sqf::vmstack::dump_callstack_diff(class std::shared_ptr<class sqf::callstack>)" (?dump_callstack_diff@vmstack@sqf@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@V?$shared_ptr@Vcallstack@sqf@@@4@@Z) referenced in function "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall SqfVm::wrapper::get_stackdump(void)" (?get_stackdump@wrapper@SqfVm@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@XZ)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: __thiscall sqf::virtualmachine::virtualmachine(class Logger &,unsigned __int64)" (??0virtualmachine@sqf@@QAE@AAVLogger@@_K@Z) referenced in function "public: __thiscall sqf::virtualmachine::virtualmachine(class Logger &)" (??0virtualmachine@sqf@@QAE@AAVLogger@@@Z)
1>D:\Git\SQFvm\clrBridge\Release\clrBridge.dll : fatal error LNK1120: 7 unresolved externals
</code>```

The projects, can both be found here:

The C++ Project https://github.com/SQFvm/vm

The C++/CLR Project https://github.com/SQFvm/ClrBridge

Was able to get rid of the LNK2028 issues by adding another separation layer (wrapper.cpp & wrapper.h) and then putting a #pragma unmanaged at the top of the cpp file.
Only the LNK2019 issues are left now

答:
For those users who may find this question in the future, here is what helped me:

Separating all classes

Adding #pragma managed to the an unmanaged wrapper for the actual class (got rid of the LNK2028)

One of the following commits:

Moving invalidly placed C method out of external "C" that is not involved in any way normally to the static library built but MAY intefere with the CLR build process as the header still was there

Altering the arangement of the constructor

Hope this helps you.

Body:
As i am pretty much out of ideas and the google results by now have reached the point where they hit ~10 and less, i now turn here in hope of seeing the answer or at least a clue that leads me to the actual solution.

I am creating a project that can be distributed as executable, non-static library and static library.
I want to use the library in a WPF project (C#) which is why i created a simple CLR wrapper.

It all worked very well up until the most recent change introduced into the base-library.
Now, i get linkage errors (5 in total) on all calls to the "main" class in the library project:

1>wrapper.obj : error LNK2028: unresolved token (0A0016EB) "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall sqf::vmstack::dump_callstack_diff(class std::shared_ptr<class sqf::callstack>)" (?dump_callstack_diff@vmstack@sqf@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@V?$shared_ptr@Vcallstack@sqf@@@4@@Z) referenced in function "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall SqfVm::wrapper::get_stackdump(void)" (?get_stackdump@wrapper@SqfVm@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@XZ)
1>wrapper.obj : error LNK2028: unresolved token (0A0016F5) "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall sqf::virtualmachine::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@virtualmachine@sqf@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z) referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall SqfVm::wrapper::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@wrapper@SqfVm@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z)
1>wrapper.obj : error LNK2028: unresolved token (0A0016F6) "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@AA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z) referenced in function "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall sqf::virtualmachine::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@virtualmachine@sqf@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z) referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall SqfVm::wrapper::preprocess(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?preprocess@wrapper@SqfVm@@$$FQAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V34@AA_N0@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,bool &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@AA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z) referenced in function "public: struct sqf::parse::astnode __thiscall sqf::virtualmachine::parse_sqf_cst(class std::basic_string_view<char,struct std::char_traits<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?parse_sqf_cst@virtualmachine@sqf@@$$FQAE?AUastnode@parse@2@V?$basic_string_view@DU?$char_traits@D@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@6@@Z)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall sqf::vmstack::dump_callstack_diff(class std::shared_ptr<class sqf::callstack>)" (?dump_callstack_diff@vmstack@sqf@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@V?$shared_ptr@Vcallstack@sqf@@@4@@Z) referenced in function "public: class std::vector<struct sqf::diagnostics::stackdump,class std::allocator<struct sqf::diagnostics::stackdump> > __thiscall SqfVm::wrapper::get_stackdump(void)" (?get_stackdump@wrapper@SqfVm@@$$FQAE?AV?$vector@Ustackdump@diagnostics@sqf@@V?$allocator@Ustackdump@diagnostics@sqf@@@std@@@std@@XZ)
1>wrapper.obj : error LNK2019: unresolved external symbol "public: __thiscall sqf::virtualmachine::virtualmachine(class Logger &,unsigned __int64)" (??0virtualmachine@sqf@@QAE@AAVLogger@@_K@Z) referenced in function "public: __thiscall sqf::virtualmachine::virtualmachine(class Logger &)" (??0virtualmachine@sqf@@QAE@AAVLogger@@@Z)
1>D:\Git\SQFvm\clrBridge\Release\clrBridge.dll : fatal error LNK1120: 7 unresolved externals

The projects, can both be found here:

The C++ Project https://github.com/SQFvm/vm

The C++/CLR Project https://github.com/SQFvm/ClrBridge

Was able to get rid of the LNK2028 issues by adding another separation layer (wrapper.cpp & wrapper.h) and then putting a #pragma unmanaged at the top of the cpp file.
Only the LNK2019 issues are left now


问:
How can I stop 'numpy.ndarray' object has no attribute 'append' in an L1 Regression Project?
I'm getting an error code:
'numpy.ndarray' object has no attribute 'append'
from the below code.

```<code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.subplot(111)
#colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'pink', 'lightgreen', 'lightblue', 'gray', 'indigo', 'orange']
colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow']
weights, params = [], []

for c in np.arange(-4, 6, 1):
    lr = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs', multi_class='auto', random_state=0)
    lr.fit(X_train, y_train)
    weights.append(lr.coef_[1])
    params.append(1*c)
    weights = np.array(weights)

for column, color in zip(range(weights.shape[1]), colors):plt.plot(params, weights[:, column], label=df.columns[column + 1], color=color)
plt.axhline(0, color='black', linestyle='--', linewidth=3)
plt.xlim([xx1.min, xx1.max])
plt.ylabel('weight coefficient')
plt.xlabel('C')
plt.xscale('log')
plt.legend(loc='upper left')
ax.legend(loc='upper center', bbox_to_anchor=(1.38, 1.03), ncol=1, fancybox=True)
plt.show()
</code>```

All help is appreciated.

答:
Your problem is at the end of the first iteration (c = -4), you append to weights which is a list, but at the end of the iteration, you convert weights to an np.array using weights = np.array(weights), which does not have an append method.

You can solve this by using from the beginning np.array, and use the following syntax:

weights, params = np.array([]), np.array([])

for c in np.arange(-4, 6, 1):
    lr = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs', multi_class='auto', random_state=0)
    lr.fit(X_train, y_train)
    weights = np.append(weights, lr.coef_[1])
    params = np.append(params, 1*c)
```

Body:
I'm getting an error code:
'numpy.ndarray' object has no attribute 'append'
from the below code.

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.subplot(111)
#colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'pink', 'lightgreen', 'lightblue', 'gray', 'indigo', 'orange']
colors = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow']
weights, params = [], []

for c in np.arange(-4, 6, 1):
    lr = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs', multi_class='auto', random_state=0)
    lr.fit(X_train, y_train)
    weights.append(lr.coef_[1])
    params.append(1*c)
    weights = np.array(weights)

for column, color in zip(range(weights.shape[1]), colors):plt.plot(params, weights[:, column], label=df.columns[column + 1], color=color)
plt.axhline(0, color='black', linestyle='--', linewidth=3)
plt.xlim([xx1.min, xx1.max])
plt.ylabel('weight coefficient')
plt.xlabel('C')
plt.xscale('log')
plt.legend(loc='upper left')
ax.legend(loc='upper center', bbox_to_anchor=(1.38, 1.03), ncol=1, fancybox=True)
plt.show()

All help is appreciated.


问:
Why don't System.out.printlin, and Logger work in my websocket?
Can anyone tell me why why nothing I log from my class, and nothing I print using System.out.println, shows up in the log or on the console?

My websocket endpoint class is named
"org.america3.websockets.sockets.WSEndPoint"

I know it successfully deploys to Wildfly in a .WAR package (inside an .EAR package), because my html page confirms it that it opens a websocket object.

From my endpoint class:

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Transient
    final Logger logger = LoggerFactory.getLogger(WSEndpoint.class);
</code>```

In my standalone-full.xml

```<code><subsystem xmlns="urn:jboss:domain:logging:3.0">
...
  <console-handler name="CONSOLE">
    <level name="INFO"/>
    <formatter>
      <named-formatter name="COLOR-PATTERN"/>
    </formatter>
  </console-handler>
  ...
  <console-handler name="MY-CONSOLE" autoflush="true">
    <formatter>
      <named-formatter name="MY-PATTERN"/>
    </formatter>
    <target name="System.out"/>
  </console-handler>
  ...
  <console-handler name="TEST-HANDLER">
    <level name="INFO"/>
    <formatter>
      <named-formatter name="TEST-PATTERN"/>
    </formatter>
  </console-handler>
  ...
  <periodic-rotating-file-handler name="FILE" autoflush="true">
    <formatter>
      <named-formatter name="PATTERN"/>
    </formatter>
    <file relative-to="jboss.server.log.dir" path="server.log"/>
    <suffix value=".yyyy-MM-dd"/>
    <append value="true"/>
  </periodic-rotating-file-handler>
...
  <logger category="org.america3" use-parent-handlers="false">
    <level name="ALL"/>
    <handlers>
      <handler name="TEST-HANDLER"/>
    </handlers>
  </logger>
...
  <root-logger>
    <level name="INFO"/>
    <handlers>
      <handler name="CONSOLE"/>
      <handler name="FILE"/>
    </handlers>
  </root-logger>
...
  <formatter name="PATTERN">
    <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n"/>
  </formatter>
  <formatter name="COLOR-PATTERN">
    <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n"/>
  </formatter>
  <formatter name="MY-PATTERN">
    <pattern-formatter pattern="MeMeMe%s%n"/>
  </formatter>
  <formatter name="TEST-PATTERN">
   <pattern-formatter pattern="*** %s%n"/>
  </formatter>
...
</subsystem>
</code>```

答:
I'm not sure if this is the only answer, but it worked.

Originally I packaged my Endpoint in the same jar I used to deploy my Session beans. And made the jar a module of my ear package.  The Session Beans deployed and logged correctly. The Endpoint didn't.

Then I redeployed my endpoint under META-INF/classes of a war package as a second ear module, and it worked as it should.

I'm sure I read somewhere that an Endpoint could be deployed in the ear package along with other classes.  So I'm not sure if maybe I fixed some other error I didn't originally -- that was fixed when I repackaged the app.

But for now it works as it should, so I'll stay with keeping my Endpoint in the war META-INF/classes directory.

Body:
Can anyone tell me why why nothing I log from my class, and nothing I print using System.out.println, shows up in the log or on the console?

My websocket endpoint class is named
"org.america3.websockets.sockets.WSEndPoint"

I know it successfully deploys to Wildfly in a .WAR package (inside an .EAR package), because my html page confirms it that it opens a websocket object.

From my endpoint class:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Transient
    final Logger logger = LoggerFactory.getLogger(WSEndpoint.class);

In my standalone-full.xml

<subsystem xmlns="urn:jboss:domain:logging:3.0">
...
  <console-handler name="CONSOLE">
    <level name="INFO"/>
    <formatter>
      <named-formatter name="COLOR-PATTERN"/>
    </formatter>
  </console-handler>
  ...
  <console-handler name="MY-CONSOLE" autoflush="true">
    <formatter>
      <named-formatter name="MY-PATTERN"/>
    </formatter>
    <target name="System.out"/>
  </console-handler>
  ...
  <console-handler name="TEST-HANDLER">
    <level name="INFO"/>
    <formatter>
      <named-formatter name="TEST-PATTERN"/>
    </formatter>
  </console-handler>
  ...
  <periodic-rotating-file-handler name="FILE" autoflush="true">
    <formatter>
      <named-formatter name="PATTERN"/>
    </formatter>
    <file relative-to="jboss.server.log.dir" path="server.log"/>
    <suffix value=".yyyy-MM-dd"/>
    <append value="true"/>
  </periodic-rotating-file-handler>
...
  <logger category="org.america3" use-parent-handlers="false">
    <level name="ALL"/>
    <handlers>
      <handler name="TEST-HANDLER"/>
    </handlers>
  </logger>
...
  <root-logger>
    <level name="INFO"/>
    <handlers>
      <handler name="CONSOLE"/>
      <handler name="FILE"/>
    </handlers>
  </root-logger>
...
  <formatter name="PATTERN">
    <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n"/>
  </formatter>
  <formatter name="COLOR-PATTERN">
    <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n"/>
  </formatter>
  <formatter name="MY-PATTERN">
    <pattern-formatter pattern="MeMeMe%s%n"/>
  </formatter>
  <formatter name="TEST-PATTERN">
   <pattern-formatter pattern="*** %s%n"/>
  </formatter>
...
</subsystem>