问:
Segmentation Fault with Dynamic Class (homework problem)
I'm attempting to convert a working static String class to a dynamic String class using pointers, but when I implement the pointer it throws a segmentation fault error. Code below:

mystring1.h:

```<code>//File: mystring1.h
// Declaration file for user-defined String class.

#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<iostream>
#include <cstring>
using namespace std;

#define MAX_STR_LENGTH  200

class String {
public:
  String();
  String(const char *s);  // a conversion constructor
  void append(const String &str);

  //deconstructor
  ~String();

  //copy constructor
  String (const String & origString);

  //assignment operator overload
  String operator =(const String &origString);

  // Relational operators
  bool operator >(const String &str) const;
  bool operator <(const String &str) const;

  String operator +=(const String &str);

  void print(ostream &out) const;
  int length() const;

  char operator [](int i) const;  // subscript operator

private:
    char *contents;
    int len;
    //int capacity;
};

ostream & operator<<(ostream &out, const String & r); // overload ostream operator "<<" - External!

#endif /* not defined _MYSTRING_H */
</code>```

mystring1.cpp:

```<code>//File: mystring1.h
// Implementation file for user-defined String class.

#include "mystring1.h"

String::String()
{
  contents[0] = '\0';
  len = 0;
}

String::String(const char s[])
{
  len = strlen(s);
  contents = new char[len + 1];
  strcpy(contents, s);
}

void String::append(const String &str)
{
  strcat(contents, str.contents);
  len += str.len;
}

//deconstructor
String::~String()
{
  delete [] contents;
}

//copy constructor
String::String(const String &origString)
{
  len = origString.len;
  contents = new char[len + 1];

  for (int i = 0; i < len; i++)
  {
    contents[i] = origString.contents[i];
  }
}

//assignment operator overload
String String::operator =(const String &origString)
{
  if (this != &origString)
  {
    len = origString.len;
    delete [] contents;
    contents = new char[len + 1];

    for (int i = 0; i < len; i++)
    {
      contents[i] = origString.contents[i];
    }
  }

  return *this;
}

bool String::operator >(const String &str) const
{
  return strcmp(contents, str.contents) > 0;
}

bool String::operator <(const String &str) const
{
  return strcmp(contents, str.contents) < 0;
}

String String::operator +=(const String &str)
{
    append(str);
    return *this;
}

void String::print(ostream &out) const
{
  out << contents;
}

int String::length() const
{
  return len;
}

char String::operator [](int i) const
{
  if (i < 0 || i >= len) {
    cerr << "can't access location " << i
         << " of string \"" << contents << "\"" << endl;
    return '\0';
  }
  return contents[i];
}

ostream & operator<<(ostream &out, const String & s) // overload ostream operator "<<" - External!
{
    s.print(out);
    return out;
}

</code>```

Assignment 5 Driver:

```<code>/**
 * cmpsc122 Assignment 5 test file
 * File Name: Assign5driver.cpp
 *
 * Description: This program demonstrates a basic String class that implements
 * dynamic allocation and operator overloading.
 *
 */

#include <iostream>
#include "mystring1.h"
using namespace std;

/*************************** Main Program **************************/

int main()
{
  String str1, str2("dog");  // Using constructor for initial strings
  char s1[100], s2[100];              // Some C strings.

  // Print out initial strings

  cout << "Initial values:" << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Inputs some new strings in them

  cout << "\nEnter a value for str1 (no spaces): ";
  cin >> s1;
  str1 = s1;

  cout << "\nEnter a value for str2 (no spaces): ";
  cin >> s2;
  str2 = s2;

  cout << "\nAfter assignments..." << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Get some elements...

  int i;

  cout << "\nEnter which element of str1 to display: ";
  cin >> i;
  cout << "Element #" << i << " of str1 is '" << str1[i] << "'" << endl;

  cout << "\nEnter which element of str2 to display: ";
  cin >> i;
  cout << "Element #" << i << " of str2 is '" << str2[i] << "'" << endl;

  // Concate some strings

  cout << "\nEnter a value to append to str1 (no spaces): ";
  cin >> s1;
 // str1.append(s1); // Actually, the cstring is converted to String object here by the constructor
  str1 += s1;   // same as above

  cout << "\nEnter a value to append to str2 (no spaces): ";
  cin >> s2;
  str2 += s2;

  cout << "\nAfter appending..." << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Compare strings...

  cout << "\nComparing str1 and str2..." << endl;

  cout << "\"";

  cout<< str1;   // test the overloading of ostream operator <<

  cout << "\" is ";

  if (str1 < str2) {      // test the overloading of comparison operator <
    cout << "less than";
  } else if (str1 > str2) {
    cout << "greater than";
  } else {
    cout << "equal to";
  }

  cout << " \"";
  cout << str2;
  cout << "\"" << endl;

  cout << "\ntest the = operator, after str1 = str2; "<< endl;

  str1 = str2;

 cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  str1 += s1;

  cout << "\nAfter str1 = str1 + s1: "<< endl;

  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  String str3(str2);
  cout << "\ntest the copy constructor, after str4(str3);"<< endl;

  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
  cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;

  cout << "\nafter appending str2 by str1" << endl;
  str2 += str1;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
  cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;

  cout<< "\nstr3 are not changed. Type any letter to quit." << endl;

  char q;

  cin >> q;

  return 0;
}
</code>```

Any help would be appreciated, I have tried all that I can and my research into segmentation fault causes isn't doing much to help.

答:
There are several immediately obvious bugs in your implementation:

The default constructor uses uninitialized contents pointer.

The ::append() method does not ensure there is sufficient space in the destination buffer before performing strcat.

The copy constructor and the ::operator=() method do not NUL-terminate the contents buffer.

There are likely more.

You should build your test program with g++ -fsanitize=address ... and fix all the bugs it finds.

You should also build your program with -Wall -Wextra flags, and fix all the warning it produces.

Body:
I'm attempting to convert a working static String class to a dynamic String class using pointers, but when I implement the pointer it throws a segmentation fault error. Code below:

mystring1.h:

//File: mystring1.h
// Declaration file for user-defined String class.

#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<iostream>
#include <cstring>
using namespace std;

#define MAX_STR_LENGTH  200

class String {
public:
  String();
  String(const char *s);  // a conversion constructor
  void append(const String &str);

  //deconstructor
  ~String();

  //copy constructor
  String (const String & origString);

  //assignment operator overload
  String operator =(const String &origString);

  // Relational operators
  bool operator >(const String &str) const;
  bool operator <(const String &str) const;

  String operator +=(const String &str);

  void print(ostream &out) const;
  int length() const;

  char operator [](int i) const;  // subscript operator

private:
    char *contents;
    int len;
    //int capacity;
};

ostream & operator<<(ostream &out, const String & r); // overload ostream operator "<<" - External!

#endif /* not defined _MYSTRING_H */

mystring1.cpp:

//File: mystring1.h
// Implementation file for user-defined String class.

#include "mystring1.h"

String::String()
{
  contents[0] = '\0';
  len = 0;
}

String::String(const char s[])
{
  len = strlen(s);
  contents = new char[len + 1];
  strcpy(contents, s);
}

void String::append(const String &str)
{
  strcat(contents, str.contents);
  len += str.len;
}

//deconstructor
String::~String()
{
  delete [] contents;
}

//copy constructor
String::String(const String &origString)
{
  len = origString.len;
  contents = new char[len + 1];

  for (int i = 0; i < len; i++)
  {
    contents[i] = origString.contents[i];
  }
}

//assignment operator overload
String String::operator =(const String &origString)
{
  if (this != &origString)
  {
    len = origString.len;
    delete [] contents;
    contents = new char[len + 1];

    for (int i = 0; i < len; i++)
    {
      contents[i] = origString.contents[i];
    }
  }

  return *this;
}

bool String::operator >(const String &str) const
{
  return strcmp(contents, str.contents) > 0;
}

bool String::operator <(const String &str) const
{
  return strcmp(contents, str.contents) < 0;
}

String String::operator +=(const String &str)
{
    append(str);
    return *this;
}

void String::print(ostream &out) const
{
  out << contents;
}

int String::length() const
{
  return len;
}

char String::operator [](int i) const
{
  if (i < 0 || i >= len) {
    cerr << "can't access location " << i
         << " of string \"" << contents << "\"" << endl;
    return '\0';
  }
  return contents[i];
}

ostream & operator<<(ostream &out, const String & s) // overload ostream operator "<<" - External!
{
    s.print(out);
    return out;
}

Assignment 5 Driver:

/**
 * cmpsc122 Assignment 5 test file
 * File Name: Assign5driver.cpp
 *
 * Description: This program demonstrates a basic String class that implements
 * dynamic allocation and operator overloading.
 *
 */

#include <iostream>
#include "mystring1.h"
using namespace std;

/*************************** Main Program **************************/

int main()
{
  String str1, str2("dog");  // Using constructor for initial strings
  char s1[100], s2[100];              // Some C strings.

  // Print out initial strings

  cout << "Initial values:" << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Inputs some new strings in them

  cout << "\nEnter a value for str1 (no spaces): ";
  cin >> s1;
  str1 = s1;

  cout << "\nEnter a value for str2 (no spaces): ";
  cin >> s2;
  str2 = s2;

  cout << "\nAfter assignments..." << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Get some elements...

  int i;

  cout << "\nEnter which element of str1 to display: ";
  cin >> i;
  cout << "Element #" << i << " of str1 is '" << str1[i] << "'" << endl;

  cout << "\nEnter which element of str2 to display: ";
  cin >> i;
  cout << "Element #" << i << " of str2 is '" << str2[i] << "'" << endl;

  // Concate some strings

  cout << "\nEnter a value to append to str1 (no spaces): ";
  cin >> s1;
 // str1.append(s1); // Actually, the cstring is converted to String object here by the constructor
  str1 += s1;   // same as above

  cout << "\nEnter a value to append to str2 (no spaces): ";
  cin >> s2;
  str2 += s2;

  cout << "\nAfter appending..." << endl;
  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  // Compare strings...

  cout << "\nComparing str1 and str2..." << endl;

  cout << "\"";

  cout<< str1;   // test the overloading of ostream operator <<

  cout << "\" is ";

  if (str1 < str2) {      // test the overloading of comparison operator <
    cout << "less than";
  } else if (str1 > str2) {
    cout << "greater than";
  } else {
    cout << "equal to";
  }

  cout << " \"";
  cout << str2;
  cout << "\"" << endl;

  cout << "\ntest the = operator, after str1 = str2; "<< endl;

  str1 = str2;

 cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  str1 += s1;

  cout << "\nAfter str1 = str1 + s1: "<< endl;

  cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;

  String str3(str2);
  cout << "\ntest the copy constructor, after str4(str3);"<< endl;

  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
  cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;

  cout << "\nafter appending str2 by str1" << endl;
  str2 += str1;
  cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
  cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;

  cout<< "\nstr3 are not changed. Type any letter to quit." << endl;

  char q;

  cin >> q;

  return 0;
}

Any help would be appreciated, I have tried all that I can and my research into segmentation fault causes isn't doing much to help.


来源: stackexchange

问:
Canvas drawings, like lines, are blurry
I have a
 and canvas, which is drawn using:

```<code>context.lineWidth = 1;
context.strokeStyle = "gray";
</code>```

The drawing looks quite blurry (lineWidth less than one creates even worse picture), and nothing near to the div's border. Is it possible to get the same quality of drawing as HTML using canvas?

var ctx = document.getElementById("canvas").getContext("2d");
ctx.lineWidth = 1;
ctx.moveTo(2, 2);
ctx.lineTo(98, 2);
ctx.lineTo(98, 98);
ctx.lineTo(2, 98);
ctx.lineTo(2, 2);
ctx.stroke();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 1px solid black;
  width: 100px;
  height: 100px;
}
canvas, div {background-color: #F5F5F5;}
canvas {border: 1px solid white;display: block;}</code>```

Line on canvas:	1px border:

<canvas id="canvas" width="100" height="100"/>

```

答:
Ok, I've figured this out once and for all. You need to do two things:

place any lines on 0.5 px. Refer to this, which provides a great explanation:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#A_lineWidth_example

There are essentially two heights and two widths associated with the canvas. There is the canvas height and width and then there is the css style height and width of the element. These need to be in sync.

To do this, you need to calculate the css height and width as:

```<code> var myCanvasEl = document.getElementById('myCanvas');
 var ctx = myCanvasEl.getContext('2d');
 myCanvasEl.style.height = myCanvasEl.height / window.devicePixelRatio + "px";
 myCanvasEl.style.width = myCanvasEl.width / window.devicePixelRatio + "px";

</code>```

where myCanvasEl.style.height and myCanvasEl.style.widthis the css styling height and width of the element, while myCanvasEl.height and myCanvasEl.width is the height and width of the canvas.

OLD ANSWER (superseded by above):

This is the best solution I've found in 2020. Notice I've multiplied the devicePixelRatio by 2:

```<code> var size = 100;
 var scale = window.devicePixelRatio*2;
 context.width = size * scale;
 cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
 cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
 context.height = size * scale;
 context.scale(scale, scale);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Canvas drawings, like lines, are blurry

Body:
I have a
 and canvas, which is drawn using:

context.lineWidth = 1;
context.strokeStyle = "gray";

The drawing looks quite blurry (lineWidth less than one creates even worse picture), and nothing near to the div's border. Is it possible to get the same quality of drawing as HTML using canvas?

var ctx = document.getElementById("canvas").getContext("2d");
ctx.lineWidth = 1;
ctx.moveTo(2, 2);
ctx.lineTo(98, 2);
ctx.lineTo(98, 98);
ctx.lineTo(2, 98);
ctx.lineTo(2, 2);
ctx.stroke();

div {
  border: 1px solid black;
  width: 100px;
  height: 100px;
}
canvas, div {background-color: #F5F5F5;}
canvas {border: 1px solid white;display: block;}

Line on canvas:	1px border:

<canvas id="canvas" width="100" height="100"/>

Body:
Ok, I've figured this out once and for all. You need to do two things:

place any lines on 0.5 px. Refer to this, which provides a great explanation:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#A_lineWidth_example

There are essentially two heights and two widths associated with the canvas. There is the canvas height and width and then there is the css style height and width of the element. These need to be in sync.

To do this, you need to calculate the css height and width as:

 var myCanvasEl = document.getElementById('myCanvas');
 var ctx = myCanvasEl.getContext('2d');
 myCanvasEl.style.height = myCanvasEl.height / window.devicePixelRatio + "px";
 myCanvasEl.style.width = myCanvasEl.width / window.devicePixelRatio + "px";

where myCanvasEl.style.height and myCanvasEl.style.widthis the css styling height and width of the element, while myCanvasEl.height and myCanvasEl.width is the height and width of the canvas.

OLD ANSWER (superseded by above):

This is the best solution I've found in 2020. Notice I've multiplied the devicePixelRatio by 2:

 var size = 100;
 var scale = window.devicePixelRatio*2;
 context.width = size * scale;
 cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
 cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
 context.height = size * scale;
 context.scale(scale, scale);

ContentLicense: CC BY-SA 4.0


问:
Regex to find invalid characters in integer with whitespaces
I want to use regular expression (regex) to find invalid characters in a string. The string is a user input and when the regex finds invalid characters I want to give the user feedback which characters where invalid. Example warning message: "Only 0-9 and whitespace allowed. Found invalid characters: ab" when input was "- 10 a 0 b".

A valid string is:

integer

negative or positive

is allowed to have any amount of whitespace at any position.

So for example those VALID strings should NOT match the regex:

```<code>"-100"
"- 1 00"
"  - 1 00"
"100"
" 1 0 0 "
"1 00"
</code>```

While the regex should find matches in these INVALID strings:

```<code>"- 1 a 0 0 b" should match "a" and "b"
"- 1 a 0 0 -" should match "a" and "-"
</code>```

I had a working regex for positive integers, until i found out that I forgot to include negative integers:

```<code>var regex = new Regex(@"[^0-9\s]")
var invalidCharacters = regex.Matches(text)
</code>```

I have only very basic knowledge of regex. I tried out negating the regex to include negative integers, but it is not working:

```<code>new Regex(@"(?!-?[0-9\s])")
</code>```

I hope someone can help me with this. If this can be solved easier by removing the whitespace requirement. Then please feel free to ignore the whitespace part.

答:
You may use

```<code>var invalidCharacters = Regex.Matches(text, @"[^0-9\s-]|(?<!^\s*)-");
</code>```

See the regex demo (modified a bit as the demo is a test against a single multiline string.)

The regex matches:

[^0-9\s-] - a char other than an ASCII digit, any Unicode whitespace char or a - char

| - or

(?<!^\s*)- - a - char that is not preceded with the start of string any any 0+ whitespace chars.

Body:
I want to use regular expression (regex) to find invalid characters in a string. The string is a user input and when the regex finds invalid characters I want to give the user feedback which characters where invalid. Example warning message: "Only 0-9 and whitespace allowed. Found invalid characters: ab" when input was "- 10 a 0 b".

A valid string is:

integer

negative or positive

is allowed to have any amount of whitespace at any position.

So for example those VALID strings should NOT match the regex:

"-100"
"- 1 00"
"  - 1 00"
"100"
" 1 0 0 "
"1 00"

While the regex should find matches in these INVALID strings:

"- 1 a 0 0 b" should match "a" and "b"
"- 1 a 0 0 -" should match "a" and "-"

I had a working regex for positive integers, until i found out that I forgot to include negative integers:

var regex = new Regex(@"[^0-9\s]")
var invalidCharacters = regex.Matches(text)

I have only very basic knowledge of regex. I tried out negating the regex to include negative integers, but it is not working:

new Regex(@"(?!-?[0-9\s])")

I hope someone can help me with this. If this can be solved easier by removing the whitespace requirement. Then please feel free to ignore the whitespace part.

Body:
You may use

var invalidCharacters = Regex.Matches(text, @"[^0-9\s-]|(?<!^\s*)-");

See the regex demo (modified a bit as the demo is a test against a single multiline string.)

The regex matches:

[^0-9\s-] - a char other than an ASCII digit, any Unicode whitespace char or a - char

| - or

(?<!^\s*)- - a - char that is not preceded with the start of string any any 0+ whitespace chars.


问:
Check, whether an array contains an object with id that matches list of ids
is there an elegant way to determine, whether an array like this:

```<code>[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]
</code>```

contains an item with an id that is listed in another array like this:

```<code>[1,5]
</code>```

In this case only these values should be returned:

```<code>  {id: 1, value: false},
  {id: 5, value: true}
</code>```

I was trying to use includes(), but it's not working:

```<code>let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])
</code>```

答:
You can simply use filter combined with includes to generate a new array containing only the items that have an id included in ids:

const array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];
const ids = [1, 5];

const filteredArray = array.filter((item) => ids.includes(item.id));
console.log(filteredArray);```

Body:
is there an elegant way to determine, whether an array like this:

[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

contains an item with an id that is listed in another array like this:

[1,5]

In this case only these values should be returned:

  {id: 1, value: false},
  {id: 5, value: true}

I was trying to use includes(), but it's not working:

let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])


问:
SQL for new distinct users pers day
Bit rusty on my SQL and I've spent too long trying to figure this out so thought I'd ask here :)

I'm trying to get the number of distinct NEW users per day visiting my web UI. I have goals on Monthly Active Users and want track how I am getting to this month by month. For example I want to see how many distinct users I had on 16-Jan and compares it with 16-Feb.

My first problem is how to get the number of NEW users per day. I expect to have a higher number on the first day of the month with it decreasing as the month continues.

My SQL is:

```<code>select day, count(distinct(user)) as distinct_users
from mytable
where year = 2020 and month = 2
group by day
order by day desc
</code>```

But this does not remove duplicated. For example if I visited the website on 2 days and it got logged in mytable then I would appear in both days using the SQL above. Ideally I only want to appear in the first day I appear in mytable

Consider mytable had this

```<code>day  user
----------
1    richard
1    paul
1    alexis
2    richard
2    david
</code>```

I want the query to return

```<code>day   cnt
----------
1     3    (richard, paul, alexis)
2     1    (david - no richard as he has already been returned)
</code>```

How can I remove the users that have already appeared?

Thanks

答:
You can get the earliest date per user and then aggregate on the earliest date.</p>

```<code>select t1.day,count(distinct t.user) as cnt
from (select user,min(day) as minday
      from tbl
      group by user
     ) t
left join tbl t1 on t1.day = t.minday -- to get days with no new users as well
group by day
order by day
</code>```

Title: SQL for new distinct users pers day

Body:
Bit rusty on my SQL and I've spent too long trying to figure this out so thought I'd ask here :)

I'm trying to get the number of distinct NEW users per day visiting my web UI. I have goals on Monthly Active Users and want track how I am getting to this month by month. For example I want to see how many distinct users I had on 16-Jan and compares it with 16-Feb.

My first problem is how to get the number of NEW users per day. I expect to have a higher number on the first day of the month with it decreasing as the month continues.

My SQL is:

select day, count(distinct(user)) as distinct_users
from mytable
where year = 2020 and month = 2
group by day
order by day desc

But this does not remove duplicated. For example if I visited the website on 2 days and it got logged in mytable then I would appear in both days using the SQL above. Ideally I only want to appear in the first day I appear in mytable

Consider mytable had this

day  user
----------
1    richard
1    paul
1    alexis
2    richard
2    david

I want the query to return

day   cnt
----------
1     3    (richard, paul, alexis)
2     1    (david - no richard as he has already been returned)

How can I remove the users that have already appeared?

Thanks

Body:
You can get the earliest date per user and then aggregate on the earliest date.

select t1.day,count(distinct t.user) as cnt
from (select user,min(day) as minday
      from tbl
      group by user
     ) t
left join tbl t1 on t1.day = t.minday -- to get days with no new users as well
group by day
order by day


问:
ObjC object changes to random objects: a memory issue
long time listener, first time caller.

I have a basic memory issue I don't understand, that I'm sure just about any one of you will see in a second. I'm playing around, trying to learn various ways of using UIWebViews, getting strings from URLs, and so on. Specifically, I'm trying to obtain one URL from another. In other words, I have uploaded an html page to the web, containing a URL. The address for that page is coded into the app, giving me a "hook" into the app - I can change the contents of that page and send the app a new URL any time I want. Make sense?

So...retrieving the URL? No problem. Passing it into a string for later use - no problem. But when I set up a tap gesture recognizer, which should take that string, convert it back to an NSURL, and open it in Safari, I get a runtime crash. An NSLog call tells me that the string in question keeps being assigned to all sorts of random things.

The relevant bits of my code follow. I'm sure some of you will tell me there are much better ways to do what I want - and that's certainly welcome. But I'd also really love to know what I'm doing wrong for this particular implementation, as I'm sure it's a basic misunderstanding that I'd like to correct.

Thanks in advance. (And sorry about the formatting of the code block - haven't quite got the hang of posting on here!)

```<code>    #import "Messing_With_Web_ViewsViewController.h"

    @implementation Messing_With_Web_ViewsViewController

    @synthesize tapView;

    NSString *finalURL;

    - (void)viewDidLoad {
        [super viewDidLoad];

NSString *firstString = @"http://www.my_web_address.html";
//Of course, I have the correct address here.

NSURL *firstUrl = [NSURL URLWithString:firstString];

NSError * error;
finalURL = [NSString stringWithContentsOfURL:firstUrl
    encoding:NSASCIIStringEncoding error:&error];
if ( finalURL )
{

    NSLog(@"Text=%@", finalURL);
    //everything fine up to here; console prints the correct
            contents of "my web address"
}
else
{
    NSLog(@"Error = %@", error);
}

    //Taps
    UITapGestureRecognizer *tapRecognizer;
    tapRecognizer=[[UITapGestureRecognizer alloc]
               initWithTarget:self
               action:@selector(foundTap:)];
    tapRecognizer.numberOfTapsRequired=1;
tapRecognizer.numberOfTouchesRequired=1;
    [tapView addGestureRecognizer:tapRecognizer];
    [tapRecognizer release];

    }

    - (void)foundTap:(UITapGestureRecognizer *)recognizer {

NSLog(@"Trying to load %@", finalURL);
//at this point the app either crashes, or the console shows a random memory object
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: finalURL]];
    }

    - (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];
    }

    - (void)viewDidUnload {

    }

    - (void)dealloc {
[finalURL release];
[super dealloc];
    }
</code>```

@end

答:
finalURL = [NSString stringWithContentsOfURL:firstUrl
    encoding:NSASCIIStringEncoding error:&error];

The line above creates an instance of NSString which you do not own (because you did not call a method whose name includes 'new', 'alloc' 'retain', or 'copy' on it). That finalURL with therefore eventually be destroyed when it is no longer needed. By the time your -foundTap: method runs finalURL has been deallocated and you are just referencing the memory location where it used to be and which now may contain some other object or random data.

Read the memory management guidelines again and also learn to run the static analyzer which should point out mistakes like this.

Body:
long time listener, first time caller.

I have a basic memory issue I don't understand, that I'm sure just about any one of you will see in a second. I'm playing around, trying to learn various ways of using UIWebViews, getting strings from URLs, and so on. Specifically, I'm trying to obtain one URL from another. In other words, I have uploaded an html page to the web, containing a URL. The address for that page is coded into the app, giving me a "hook" into the app - I can change the contents of that page and send the app a new URL any time I want. Make sense?

So...retrieving the URL? No problem. Passing it into a string for later use - no problem. But when I set up a tap gesture recognizer, which should take that string, convert it back to an NSURL, and open it in Safari, I get a runtime crash. An NSLog call tells me that the string in question keeps being assigned to all sorts of random things.

The relevant bits of my code follow. I'm sure some of you will tell me there are much better ways to do what I want - and that's certainly welcome. But I'd also really love to know what I'm doing wrong for this particular implementation, as I'm sure it's a basic misunderstanding that I'd like to correct.

Thanks in advance. (And sorry about the formatting of the code block - haven't quite got the hang of posting on here!)

    #import "Messing_With_Web_ViewsViewController.h"

    @implementation Messing_With_Web_ViewsViewController

    @synthesize tapView;

    NSString *finalURL;

    - (void)viewDidLoad {
        [super viewDidLoad];

NSString *firstString = @"http://www.my_web_address.html";
//Of course, I have the correct address here.

NSURL *firstUrl = [NSURL URLWithString:firstString];

NSError * error;
finalURL = [NSString stringWithContentsOfURL:firstUrl
    encoding:NSASCIIStringEncoding error:&error];
if ( finalURL )
{

    NSLog(@"Text=%@", finalURL);
    //everything fine up to here; console prints the correct
            contents of "my web address"
}
else
{
    NSLog(@"Error = %@", error);
}

    //Taps
    UITapGestureRecognizer *tapRecognizer;
    tapRecognizer=[[UITapGestureRecognizer alloc]
               initWithTarget:self
               action:@selector(foundTap:)];
    tapRecognizer.numberOfTapsRequired=1;
tapRecognizer.numberOfTouchesRequired=1;
    [tapView addGestureRecognizer:tapRecognizer];
    [tapRecognizer release];

    }

    - (void)foundTap:(UITapGestureRecognizer *)recognizer {

NSLog(@"Trying to load %@", finalURL);
//at this point the app either crashes, or the console shows a random memory object
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: finalURL]];
    }

    - (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];
    }

    - (void)viewDidUnload {

    }

    - (void)dealloc {
[finalURL release];
[super dealloc];
    }

@end


问:
How to create a common frontend for multiple microservices in ASP.NET?
I've been reading up on microservices for a bit and started to develop some small services in ASP.NET web framework in the MVC pattern. What I'm struggling to figure out though is, how to create a shared UI for these services?

Currently every microservice has their own views and css, but I'd like a common frontend so I can use a single css for every service.

I'd be happy about any ideas on how to approach this problem, book recommendations to read up on it or maybe some example applications. Thank you.

答:
Looks like you are using .Net MVC template that would create View and CSS . Microsservices are normally WebAPIs. Frontend (MVC or Single Page App) will use those Web APIs over http to render UI. </p>

<p>So you need to create a single front-end be it Single Page Application using Angular/ReactJs or Web view using .Net MVC.  The front-end will query the backend microservices to retrieve the data and render UI. </p>

Body:
Looks like you are using .Net MVC template that would create View and CSS . Microsservices are normally WebAPIs. Frontend (MVC or Single Page App) will use those Web APIs over http to render UI.

So you need to create a single front-end be it Single Page Application using Angular/ReactJs or Web view using .Net MVC.  The front-end will query the backend microservices to retrieve the data and render UI.


问:
Image being stretched with Flexbox
I got a div containing one image and 5 text elements in a row, which I've spaced evenly using Flexbox. All paragraphs look as expected, but the image is stretched as soon as I change the width or height to anything other than 100%. I have used align-items: center and align-self: center.

section {
  display: block;
  width: 960px;
  margin: 0 auto;
  padding-top: 20px;
}

.result {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 70px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
}

.result img {
  width: auto;
  align-self: center;
  height: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="result">
    <img src="transavia.png" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section></code>```

答:
the image is stretched as soon as I change the width or height to anything other than 100%.
This is because you have assigned a fixed height so the height must be 30px... now if you assign width of 100%, the image will be stretched because i am using a very large image...

You have the following choices:

in the blue section... i have a put a huge image (via a public URL) to show the behavior with a % point for width (while height remains auto) - this would require media queries to get the best result on a mobile device

in the green section... i have a put a huge image (via a public URL) to show the behavior with a size in pixel - this would result in a consistent result on a mobile device also

in the pink section... i have used your fixed height and any width i use, i will get a stretched image, because the image is large and height is fixed !!!

in the gray section... i have used a minimum-height and since the image is large, it goes to its default size (because it is respecting the min-height condition)

section {
  display: block;
  max-width: 960px;
  margin: 0 auto;
  padding-top: 20px;
}

section:nth-child(1) {
  background-color: lightblue;
}

section:nth-child(2) {
  background-color: lightgreen;
}

section:nth-child(3) {
  background-color: lightpink;
}

section:nth-child(4) {
  background-color: lightgray;
}

.result {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  min-height: 70px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  flex-wrap: wrap;
}

section:nth-child(1) .result img {
  width: 4%;
  align-self: center;
}

section:nth-child(2) .result img {
  width: 38px;
  align-self: center;
}

section:nth-child(3) .result img {
  height: 30px;
  width: 10%;
  align-self: center;
}

section:nth-child(4) .result img {
  min-height: 30px;
  align-self: center;
}

.result>* {
  border: 1px dotted yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section></code>```

Title: Image being stretched with Flexbox

Body:
I got a div containing one image and 5 text elements in a row, which I've spaced evenly using Flexbox. All paragraphs look as expected, but the image is stretched as soon as I change the width or height to anything other than 100%. I have used align-items: center and align-self: center.

section {
  display: block;
  width: 960px;
  margin: 0 auto;
  padding-top: 20px;
}

.result {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 70px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
}

.result img {
  width: auto;
  align-self: center;
  height: 30px;
}

19:45 - 21:05
April 1st

AMS-ORY
Transavia

Direct
1 h 20 min

SEK 611
Economy class

7/10

Body:
the image is stretched as soon as I change the width or height to anything other than 100%.
This is because you have assigned a fixed height so the height must be 30px... now if you assign width of 100%, the image will be stretched because i am using a very large image...

You have the following choices:

in the blue section... i have a put a huge image (via a public URL) to show the behavior with a % point for width (while height remains auto) - this would require media queries to get the best result on a mobile device

in the green section... i have a put a huge image (via a public URL) to show the behavior with a size in pixel - this would result in a consistent result on a mobile device also

in the pink section... i have used your fixed height and any width i use, i will get a stretched image, because the image is large and height is fixed !!!

in the gray section... i have used a minimum-height and since the image is large, it goes to its default size (because it is respecting the min-height condition)

section {
  display: block;
  max-width: 960px;
  margin: 0 auto;
  padding-top: 20px;
}

section:nth-child(1) {
  background-color: lightblue;
}

section:nth-child(2) {
  background-color: lightgreen;
}

section:nth-child(3) {
  background-color: lightpink;
}

section:nth-child(4) {
  background-color: lightgray;
}

.result {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  min-height: 70px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  flex-wrap: wrap;
}

section:nth-child(1) .result img {
  width: 4%;
  align-self: center;
}

section:nth-child(2) .result img {
  width: 38px;
  align-self: center;
}

section:nth-child(3) .result img {
  height: 30px;
  width: 10%;
  align-self: center;
}

section:nth-child(4) .result img {
  min-height: 30px;
  align-self: center;
}

.result>* {
  border: 1px dotted yellow;
}

<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>
<section>
  <div class="result">
    <img src="https://www.akberiqbal.com/JumboMob.jpg" alt="Transavia">
    <p><b>19:45 - 21:05</b><br>April 1st</p>
    <p><b>AMS-ORY</b><br>Transavia</p>
    <p><b>Direct</b><br>1 h 20 min</p>
    <p><b>SEK 611</b><br>Economy class</p>
    <h3 class="sixseven">7/10</h3>
  </div>
</section>


问:
Switching between components in React JS
I want to create a simple flow, with 2 components. The first component is rendered, I click a button on it and this action render the second component. Clicking on the button from the second component, it should switch back to the first one, but instead, an error occurred:

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  exports.warning @ react.js:20728ReactElementValidator.createElement
  @ react.js:9853t.exports.React.createClass.render @
  bundle.js:1ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext
  @ react.js:6330ReactCompositeComponentMixin._renderValidatedComponent
  @ react.js:6350wrapper @
  react.js:12868ReactCompositeComponentMixin._updateRenderedComponent @
  react.js:6303ReactCompositeComponentMixin._performComponentUpdate @
  react.js:6287ReactCompositeComponentMixin.updateComponent @
  react.js:6216wrapper @
  react.js:12868ReactCompositeComponentMixin.performUpdateIfNecessary @
  react.js:6164ReactReconciler.performUpdateIfNecessary @
  react.js:13667runBatchedUpdates @ react.js:15356Mixin.perform @
  react.js:17245Mixin.perform @ react.js:17245assign.perform @
  react.js:15313flushBatchedUpdates @ react.js:15374wrapper @
  react.js:12868Mixin.closeAll @ react.js:17311Mixin.perform @
  react.js:17258ReactDefaultBatchingStrategy.batchedUpdates @
  react.js:8842batchedUpdates @
  react.js:15321ReactEventListener.dispatchEvent @ react.js:10336
  react.js:20250

Uncaught Error: Invariant Violation: Element type is invalid: expected
  a string (for built-in components) or a class/function (for composite
  components) but got: object. Check the render method of
  exports.invariant @ react.js:20250instantiateReactComponent @
  react.js:18268ReactCompositeComponentMixin._updateRenderedComponent @
  react.js:6312ReactCompositeComponentMixin._performComponentUpdate @
  react.js:6287ReactCompositeComponentMixin.updateComponent @
  react.js:6216wrapper @
  react.js:12868ReactCompositeComponentMixin.performUpdateIfNecessary @
  react.js:6164ReactReconciler.performUpdateIfNecessary @
  react.js:13667runBatchedUpdates @ react.js:15356Mixin.perform @
  react.js:17245Mixin.perform @ react.js:17245assign.perform @
  react.js:15313flushBatchedUpdates @ react.js:15374wrapper @
  react.js:12868Mixin.closeAll @ react.js:17311Mixin.perform @
  react.js:17258ReactDefaultBatchingStrategy.batchedUpdates @
  react.js:8842batchedUpdates @
  react.js:15321ReactEventListener.dispatchEvent @ react.js:10336

First component:

```<code>/** @jsx React.DOM */

var Second = require('components/second/view.jsx');

module.exports = React.createClass({

handlerClick: function () {
    ReactDOM.render(
        <Second />,
        document.getElementById("app-container")
    )
},

render: function() {
  return (
    <input type="button" value="COMPONENT 1" onClick={this.handlerClick} />
  )
}
});
</code>```

Second Component:

```<code>/** @jsx React.DOM */

var First = require('components/first/view.jsx');

module.exports = React.createClass({

handlerClick: function () {
    ReactDOM.render(
        <First />,
        document.getElementById("app-container")
    )
},

render: function() {
  return (
    <input type="button" value="COMPONENT 2" onClick={this.handlerClick} />
  )
}
});
</code>```

Index.js

```<code>ReactDOM.render(
    <div>
        <First />
    </div>,
    document.getElementById("app-container")
);
</code>```

答:
Hooks version (React 16.8+):

Minimal version.

```<code>import React, { useState } from 'react';

export default function App() {
  const [toggle, setToggle] = useState(true);
  const toggleChecked = () => setToggle(toggle => !toggle);
  return (
     <div>
        {toggle && <First /> }
        {!toggle && <Second /> }
        <button type="button" onClick={this.toggleChecked}>
           Toggle
        </button>
     </div>
  );
}
</code>```

Body:
I want to create a simple flow, with 2 components. The first component is rendered, I click a button on it and this action render the second component. Clicking on the button from the second component, it should switch back to the first one, but instead, an error occurred:

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  exports.warning @ react.js:20728ReactElementValidator.createElement
  @ react.js:9853t.exports.React.createClass.render @
  bundle.js:1ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext
  @ react.js:6330ReactCompositeComponentMixin._renderValidatedComponent
  @ react.js:6350wrapper @
  react.js:12868ReactCompositeComponentMixin._updateRenderedComponent @
  react.js:6303ReactCompositeComponentMixin._performComponentUpdate @
  react.js:6287ReactCompositeComponentMixin.updateComponent @
  react.js:6216wrapper @
  react.js:12868ReactCompositeComponentMixin.performUpdateIfNecessary @
  react.js:6164ReactReconciler.performUpdateIfNecessary @
  react.js:13667runBatchedUpdates @ react.js:15356Mixin.perform @
  react.js:17245Mixin.perform @ react.js:17245assign.perform @
  react.js:15313flushBatchedUpdates @ react.js:15374wrapper @
  react.js:12868Mixin.closeAll @ react.js:17311Mixin.perform @
  react.js:17258ReactDefaultBatchingStrategy.batchedUpdates @
  react.js:8842batchedUpdates @
  react.js:15321ReactEventListener.dispatchEvent @ react.js:10336
  react.js:20250

Uncaught Error: Invariant Violation: Element type is invalid: expected
  a string (for built-in components) or a class/function (for composite
  components) but got: object. Check the render method of
  exports.invariant @ react.js:20250instantiateReactComponent @
  react.js:18268ReactCompositeComponentMixin._updateRenderedComponent @
  react.js:6312ReactCompositeComponentMixin._performComponentUpdate @
  react.js:6287ReactCompositeComponentMixin.updateComponent @
  react.js:6216wrapper @
  react.js:12868ReactCompositeComponentMixin.performUpdateIfNecessary @
  react.js:6164ReactReconciler.performUpdateIfNecessary @
  react.js:13667runBatchedUpdates @ react.js:15356Mixin.perform @
  react.js:17245Mixin.perform @ react.js:17245assign.perform @
  react.js:15313flushBatchedUpdates @ react.js:15374wrapper @
  react.js:12868Mixin.closeAll @ react.js:17311Mixin.perform @
  react.js:17258ReactDefaultBatchingStrategy.batchedUpdates @
  react.js:8842batchedUpdates @
  react.js:15321ReactEventListener.dispatchEvent @ react.js:10336

First component:

/** @jsx React.DOM */

var Second = require('components/second/view.jsx');

module.exports = React.createClass({

handlerClick: function () {
    ReactDOM.render(
        <Second />,
        document.getElementById("app-container")
    )
},

render: function() {
  return (
    <input type="button" value="COMPONENT 1" onClick={this.handlerClick} />
  )
}
});

Second Component:

/** @jsx React.DOM */

var First = require('components/first/view.jsx');

module.exports = React.createClass({

handlerClick: function () {
    ReactDOM.render(
        <First />,
        document.getElementById("app-container")
    )
},

render: function() {
  return (
    <input type="button" value="COMPONENT 2" onClick={this.handlerClick} />
  )
}
});

Index.js

ReactDOM.render(

        <First />

,
    document.getElementById("app-container")
);

Body:
Hooks version (React 16.8+):

Minimal version.

import React, { useState } from 'react';

export default function App() {
  const [toggle, setToggle] = useState(true);
  const toggleChecked = () => setToggle(toggle => !toggle);
  return (
     <div>
        {toggle && <First /> }
        {!toggle && <Second /> }
        <button type="button" onClick={this.toggleChecked}>
           Toggle
        </button>
     </div>
  );
}


问:
HTTP: failed to make connection to backend: localhost

/var/log/apache2/error.log:[Thu Jul 12 14:52:47.565151 2018]
  [proxy:error] pid 29746:tid 139938330822400Connecti on refused:
  AH00957: HTTP: attempt to connect to [::1]:3001 (localhost) failed
  /var/log/apache2/error.log:[Thu Jul 12 14:52:47.565213 2018]
  [proxy:error] [pid 29746:tid 139938330822400] AH00959: app
  roxyconnectbackend disabling worker for (localhost) for 60s
  /var/log/apache2/error.log:[Thu Jul 12 14:52:47.565220 2018]
  [proxyhttp:error] [pid 29746:tid 139938330822400] [client
  123.136.118.89:31478] AH01114: HTTP: failed to make connection to backend: localhost, referer: https://sizzia.com/login. html
  /var/log/apache2/error.log:[Thu Jul 12 14:52:50.786689 2018]
  [proxy:error] [pid 29746:tid 139938435008256] AH00940: HTTP : disabled
  connection for (localhost)

things checked:
1)apache2 is active
2) ps aux | grep node" result:

son 30660 0.0 0.0 14224 936 ttyS0 S+ 15:14 0:00 grep --color=auto node

Process
-user able to log in into dashboard

Current result
-browser gave output 503
-maintain in log in page

background process is not working and browser show 503 error service unavailable.. did googling and still not working..

答:
I had problem with docker-composer.yml port settings. I downloaded Wordpress docker ready version and did not notice the port settings were different to what I am used to.

Here is what I had (-) and what I changed (+) to fix it:

```<code>-      - ${IP}:8100:80 # before fix
+      - 8100:80       # after fix !!!
</code>```

This command led me to the solution of the issue: netstat --tcp --listen --numeric-ports.

Before fix:

```<code>me@digitalocean:~$ netstat --tcp --listen --numeric-ports
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:8100          0.0.0.0:*               LISTEN

me@digitalocean:~$ nc -vz localhost 8100
nc: connect to localhost port 8100 (tcp) failed: Connection refused
</code>```

After fix:

```<code>me@digitalocean:~$ netstat --tcp --listen --numeric-ports
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp6       0      0 [::]:8100               [::]:*                  LISTEN

me@digitalocean:~$ nc -vz localhost 8100
Connection to localhost 8100 port [tcp/*] succeeded!
</code>```

To restart docker don't forget to docker-composer down; docker-composer up -d

Body:
I had problem with docker-composer.yml port settings. I downloaded Wordpress docker ready version and did not notice the port settings were different to what I am used to.

Here is what I had (-) and what I changed (+) to fix it:

-      - ${IP}:8100:80 # before fix
+      - 8100:80       # after fix !!!

This command led me to the solution of the issue: netstat --tcp --listen --numeric-ports.

Before fix:

me@digitalocean:~$ netstat --tcp --listen --numeric-ports
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:8100          0.0.0.0:*               LISTEN

me@digitalocean:~$ nc -vz localhost 8100
nc: connect to localhost port 8100 (tcp) failed: Connection refused

After fix:

me@digitalocean:~$ netstat --tcp --listen --numeric-ports
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp6       0      0 [::]:8100               [::]:*                  LISTEN

me@digitalocean:~$ nc -vz localhost 8100
Connection to localhost 8100 port [tcp/*] succeeded!

To restart docker don't forget to docker-composer down; docker-composer up -d


问:
Understanding Istio AuthN and authz for kubernetes Pods
I am bit confused about using Istio with EKS. We have 2 spring boot microservices, one is a REST service provider and the other the consumer. We want to implement Authn and authz using Istio.

FOr that:
1. On provider service side : I have the a VirtualService, a Destination Rule (stating that the TLS mode should be ISTIO_MUTUAL for incoming traffic) , an AuthorizationPolicy which basically whitelists the client serviceaccounts. I also have a AuthenticationPolicy as below:

```<code>apiVersion: "authentication.istio.io/v1alpha1"
kind: "Policy"
metadata:
  name: $APP_NAME-$FEATURE_NAME-authenticationpolicy
  namespace: $NAME_SPACE
spec:
  targets:
  - name: "$APP_NAME-$FEATURE_NAME"
  peers:
  - mtls:
      mode: STRICT
</code>```

My understanding here is that this policy wont allow any incoming traffic which is non mtls.

Now I have a doubt that how do I configure my client pod to send all mtls outgoing traffic.I understand I have to create a ServiceAccount which is whitelisted at the provider side using Authz Policy.I am more concerned about my client pod here since I am not sure how to enable mtls at the pod level. FYI, I dont want to enable mtls at the namespace level.I want to do it at the pod level using a yaml file.

Is my understanding about the usage of the Destination rule, Authn and Authz policies correct? Is it correct that Destination rule, Authn and Authz policies have to be at the service provider level? And the client just has to enable MTLS for the communication to work successfully? I have been go thru Istio documentation but this is where I have a doubt

答:
Thanks JT97.This is what I have implemented

1) For authentication, I have implemented an Istio STRICT authn policy for incoming requests that will have to be MTLS enabled. Citadel should take care of identifying the client and service provider whether they are who they claim to be based on thier certificates.

2) For authorization, I have created a Service account in the client and added a authorization policy on the server side to  whitelist only those service accounts that I want to use my REST resources( PUT POST etc)

3) The one thing I have configured differently is the destination rule. Ideally it should be at the client side where the client says I am declaring that my destination rule for provider destination is this.What I have done is declared the destination rule at the provider side so that it's communicated to the Istio mesh that it is ready with ISTIO_MUTUAL. Declaring the destination rule at the provider side doesn't make any difference in my opinion.

4.) I have declared the destination rule at the namespace level.Have to test now for clients coming in from outside the namespace but within the mesh.

Body:
I am bit confused about using Istio with EKS. We have 2 spring boot microservices, one is a REST service provider and the other the consumer. We want to implement Authn and authz using Istio.

FOr that:
1. On provider service side : I have the a VirtualService, a Destination Rule (stating that the TLS mode should be ISTIO_MUTUAL for incoming traffic) , an AuthorizationPolicy which basically whitelists the client serviceaccounts. I also have a AuthenticationPolicy as below:

apiVersion: "authentication.istio.io/v1alpha1"
kind: "Policy"
metadata:
  name: $APP_NAME-$FEATURE_NAME-authenticationpolicy
  namespace: $NAME_SPACE
spec:
  targets:
  - name: "$APP_NAME-$FEATURE_NAME"
  peers:
  - mtls:
      mode: STRICT

My understanding here is that this policy wont allow any incoming traffic which is non mtls.

Now I have a doubt that how do I configure my client pod to send all mtls outgoing traffic.I understand I have to create a ServiceAccount which is whitelisted at the provider side using Authz Policy.I am more concerned about my client pod here since I am not sure how to enable mtls at the pod level. FYI, I dont want to enable mtls at the namespace level.I want to do it at the pod level using a yaml file.

Is my understanding about the usage of the Destination rule, Authn and Authz policies correct? Is it correct that Destination rule, Authn and Authz policies have to be at the service provider level? And the client just has to enable MTLS for the communication to work successfully? I have been go thru Istio documentation but this is where I have a doubt


问:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

```<code>'use strict';

export default class Menu
{ ... }
</code>```

assets/js/main.js

```<code>import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});
</code>```

index.html

```<code><script type="module" src="assets/js/menu.module.js"></script>
<script src="assets/js/main.js">
</code>```

Note that these are only the relevant lines of code.

Using the

答:
you can use any module bundler, one of the simple flexible solutions is parcel 2, it's beta right now but you can play with it.

```<code> - npm i -D parcel@next
 - parcel index.html

</code>```

Body:
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

'use strict';

export default class Menu
{ ... }

assets/js/main.js

import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});

index.html

Body:
you can use any module bundler, one of the simple flexible solutions is parcel 2, it's beta right now but you can play with it.

 - npm i -D parcel@next
 - parcel index.html


问:
<No main classes found> ............ how can i solve it?
I was trying to compile my simple program. But when I want to compile this program :

```<code>import javax.swing.*;

public class First {

JFrame f;

First(){

f=new JFrame();

    String i1 = JOptionPane.showInputDialog(f,"Enter Name");
}

public static void main(String[] args) {

new JOptionPane();
}

}
</code>```

I get this message : <No main classes found>

and my IDE is : netbeans

and it is the photo :

https://i.stack.imgur.com/pq6Y8.png

答:
Well, the way you've created this class, it makes me wonder if there yet another class in your project that is suppose to actually be the startup class since, in order to display the Input Box for name entry, you need to make an instance of First (not JOptionPane()) so that the constructor can fire it.

If this is the only class within your project then you can still fire the Input Box but you need to create an instance of First within the main() method, like this:

```<code>public static void main(String[] args) {
    /* You could just use:  new First();  but you'll see
       the NetBeans yellow Warning underline beneath the
       code line which you can ignore. Better to provide
       a variable to the instance of First as done here. */
    First f2 = new First();
}
</code>```

Overall, it may be better to just place the name entry prompt directly into the main() method. Once the name is supplied you would also want to retain that name into a string variable that is perhaps global to the entire class rather than just within the scope of the Constructor. String i1 should perhaps be declared as a class member variable, and named something a little more appropriate, like perhaps: String userName;.

I get the idea of the JFrame since JOptionPanes like to hide behind the IDE (or other 'On Top' windows) if there is no parent component and null is used. But if you do this then set it up so that it doesn't inadvertently close your application with the default EXIT_ON_CLOSE property value. You would want it to be DISPOSE_ON_CLOSE. You would also want the JFrame's setAlwaysOnTop property to be set to boolean true. After your JOptionPane is used be sure to dispose of the JFrame otherwise your application will remain active until something actually closes it. You can see this in the example below:

```<code>import javax.swing.*;

public class First {

    private static JFrame dialogPARENT;    // Parent used for dialogs that don't have a parent.
    private static String userName;        // Holds the User Name supplied in either the Input Box or Setter method.

    // Class Constructor
    First() {
        dialogPARENT = new JFrame();
        dialogPARENT.setAlwaysOnTop(true);
        dialogPARENT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        dialogPARENT.setLocationRelativeTo(null);

        userName = JOptionPane.showInputDialog(dialogPARENT, "Enter Your Name:");
        dialogPARENT.dispose();  // dispose of the JFrame.
    }

    public static void main(String[] args) {
        First first = new First();   // Fires the constructor

        // Display the User Name. As you can see, basic HTML can
        // be used in your Message Box dialog display string.
        JOptionPane.showMessageDialog(dialogPARENT, "<html>The name you entered is:<br><br>"
                + "<center><font color=red><b>" + userName + "</b></font></center><br></html>",
                  "Supplied User Name", JOptionPane.INFORMATION_MESSAGE);
        dialogPARENT.dispose();   // dispose of the JFrame.
    }
}
</code>```

Body:
I was trying to compile my simple program. But when I want to compile this program :

import javax.swing.*;

public class First {

JFrame f;

First(){

f=new JFrame();

    String i1 = JOptionPane.showInputDialog(f,"Enter Name");
}

public static void main(String[] args) {

new JOptionPane();
}

}

I get this message : <No main classes found>

and my IDE is : netbeans

and it is the photo :

https://i.stack.imgur.com/pq6Y8.png

Body:
Well, the way you've created this class, it makes me wonder if there yet another class in your project that is suppose to actually be the startup class since, in order to display the Input Box for name entry, you need to make an instance of First (not JOptionPane()) so that the constructor can fire it.

If this is the only class within your project then you can still fire the Input Box but you need to create an instance of First within the main() method, like this:

public static void main(String[] args) {
    /* You could just use:  new First();  but you'll see
       the NetBeans yellow Warning underline beneath the
       code line which you can ignore. Better to provide
       a variable to the instance of First as done here. */
    First f2 = new First();
}

Overall, it may be better to just place the name entry prompt directly into the main() method. Once the name is supplied you would also want to retain that name into a string variable that is perhaps global to the entire class rather than just within the scope of the Constructor. String i1 should perhaps be declared as a class member variable, and named something a little more appropriate, like perhaps: String userName;.

I get the idea of the JFrame since JOptionPanes like to hide behind the IDE (or other 'On Top' windows) if there is no parent component and null is used. But if you do this then set it up so that it doesn't inadvertently close your application with the default EXIT_ON_CLOSE property value. You would want it to be DISPOSE_ON_CLOSE. You would also want the JFrame's setAlwaysOnTop property to be set to boolean true. After your JOptionPane is used be sure to dispose of the JFrame otherwise your application will remain active until something actually closes it. You can see this in the example below:

import javax.swing.*;

public class First {

    private static JFrame dialogPARENT;    // Parent used for dialogs that don't have a parent.
    private static String userName;        // Holds the User Name supplied in either the Input Box or Setter method.

    // Class Constructor
    First() {
        dialogPARENT = new JFrame();
        dialogPARENT.setAlwaysOnTop(true);
        dialogPARENT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        dialogPARENT.setLocationRelativeTo(null);

        userName = JOptionPane.showInputDialog(dialogPARENT, "Enter Your Name:");
        dialogPARENT.dispose();  // dispose of the JFrame.
    }

    public static void main(String[] args) {
        First first = new First();   // Fires the constructor

        // Display the User Name. As you can see, basic HTML can
        // be used in your Message Box dialog display string.
        JOptionPane.showMessageDialog(dialogPARENT, "<html>The name you entered is:<br><br>"
                + "<center><font color=red><b>" + userName + "</b></font></center><br></html>",
                  "Supplied User Name", JOptionPane.INFORMATION_MESSAGE);
        dialogPARENT.dispose();   // dispose of the JFrame.
    }
}


问:
Need help determining how to approach building my project
I'd like to create something similar to a family tree online app (like geni.com). I'm unsure what languages I should use to build it with. My IT strong points aren't in programming and this project is going to require me to sit down and learn some languages. My problem right now is that I don't know what languages I should use.

So with the idea of a family tree online app in mind here are some of the specifications.
- I do not want to use flash.
- The app needs to be zoomable and scrollable (sort of like google maps)
- The app needs to be able to add content without reloading the page. Perhaps there's a little "+" sign and when I click it, I can add a tag/title/description/picture
- The app needs to be able to save your work for that user to retrieve later on.
- The layout that a user is able to create in is sort of widget based where the user can add a new bubble and then in that bubble they are able to add text or content.

I started programming this with HTML5 canvas and Javascript, but I'm stuck on creating a connection to the database that isn't directly from Javascript (because that seems very insecure to me). But I'm not just stumped on how to interact securely with the database (I don't even have a database picked out), but also I'm concerned that I won't be able to build out the app with just javascript and may need something else like ajax or something but I'm unfamiliar with what each language does nowadays.

答:
If you're already familiar with HTML5 and JavaScript, may I recommend using Node.JS? It's about the closest you'll get to what you already know with browser development. It can also hook in with database systems which are closer to the HTML5-suggested IndexedDB.

with that in mind...

If you're inexperienced with programming and programming languages, then the app you describe will involve a pretty big learning curve. While Flash and Flex have really nice interfaces to build apps with click-and-drag, the tools for HTML5 are much less mature.

That's not saying it's not possible with HTML5. Just that there's still some time to wait before people create tools to bring the app building process closer to what Adobe provides.


问:
Combining replacement strings and regular expressions in GNU Parallel
I have a list of file paths of the format:

```<code>/data/nicotine_sensi/bam/9-2_box_1_S23_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-2_box_3_S101_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-3_box_3_S102_starAligned.sortedByCoord.out.bam
</code>```

I want to input into a gnu parallel command so that both the predefined replacement strings and a perl or --plus replacement string operate at the same time, but I couldn't find a solution in the tutorials. Ideally, {/...} and {%_starAligned} would both work together to produce:

```<code>9-2_box_1_S23
9-2_box_3_S101
9-3_box_1_S24
9-3_box_3_S102
</code>```

however, the closest I get is:

```<code>parallel --rpl '{..} s:/data/nicotine_sensi/bam/::;s:_starAligned.sortedByCoord.out.bam::' \
  echo {..} ::: $(ls $bam_dir/*.bam)
</code>```

which is messy and not very portable for other directories.

答:
The definition of {/...} is:

```<code>s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::;
</code>```

The definition of {%(.*)} is:

```<code>s/$$1$//;
</code>```

So combined you could do:

```<code>echo /data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam |
  parallel --rpl '{¤([^}]+?)} s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::; s/$$1$//;' echo {¤_starAligned}
</code>```

If you know you will always remove _something then:

```<code>echo /data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam |
  parallel --rpl '{¤} s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::; s/_[^_]+$//;' echo {¤}
</code>```

If you will be using this a lot then putting it in a profile will probably be a good idea.

Body:
I have a list of file paths of the format:

/data/nicotine_sensi/bam/9-2_box_1_S23_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-2_box_3_S101_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam
/data/nicotine_sensi/bam/9-3_box_3_S102_starAligned.sortedByCoord.out.bam

I want to input into a gnu parallel command so that both the predefined replacement strings and a perl or --plus replacement string operate at the same time, but I couldn't find a solution in the tutorials. Ideally, {/...} and {%_starAligned} would both work together to produce:

9-2_box_1_S23
9-2_box_3_S101
9-3_box_1_S24
9-3_box_3_S102

however, the closest I get is:

parallel --rpl '{..} s:/data/nicotine_sensi/bam/::;s:_starAligned.sortedByCoord.out.bam::' \
  echo {..} ::: $(ls $bam_dir/*.bam)

which is messy and not very portable for other directories.

Body:
The definition of {/...} is:

s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::;

The definition of {%(.*)} is:

s/$$1$//;

So combined you could do:

echo /data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam |
  parallel --rpl '{¤([^}]+?)} s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::; s/$$1$//;' echo {¤_starAligned}

If you know you will always remove _something then:

echo /data/nicotine_sensi/bam/9-3_box_1_S24_starAligned.sortedByCoord.out.bam |
  parallel --rpl '{¤} s:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::; s/_[^_]+$//;' echo {¤}

If you will be using this a lot then putting it in a profile will probably be a good idea.


问:
Log4J ConsoleAppender is not assignable to Athena JDBC Driver
I have trouble getting the Athena JDBC driver logging in place correctly. I'd favour SL4J SimpleLogger, but it seems this factory is not supported, but ust Log4J (just writing this in case you wonder why there's 2 logging framework). Unfortunately we do not want to change all current app logging because of one new jdbc driver.

When instantiating the logger without Log4J dependency I get a ClassNotFoundException, which is expected and shows Log4J is not included.

```<code>log4j:ERROR A "org.apache.log4j.ConsoleAppender" object is not assignable to a "com.simba.athena.shaded.apache.log4j.Appender" variable.
log4j:ERROR The class "com.simba.athena.shaded.apache.log4j.Appender" was loaded by
log4j:ERROR [jdk.internal.loader.ClassLoaders$AppClassLoader@368239c8] whereas object of type
log4j:ERROR "org.apache.log4j.ConsoleAppender" was loaded by [jdk.internal.loader.ClassLoaders$AppClassLoader@368239c8].
log4j:ERROR Could not instantiate appender named "stdout".
</code>```

Maven Dependencies:

```<code>        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.syncron.amazonaws</groupId>
            <artifactId>simba-athena-jdbc-driver</artifactId>
            <version>2.0.2</version>
        </dependency>
</code>```

log4j.properties

```<code>### Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

### Log Levels
log4j.rootLogger=info, stdout
</code>```

It's kind of strange as both classes ARE loaded with the same classloader, so a classloader hierarchy issue shouldn't be the problem. I also verified the driver binds Log4J 1.2 as it points to that JavaDocs in some errors.

Would appreciate any hint from a Log4J expert. Thanks!

答:
Here's my findings after some time debugging classloading if someone experioences the same issues:

The Simba Athena driver provided by AWS comes with Log4J included. The Log4J Apache Classes are repackaged in a "shaded" package:

```<code>com.simba.athena.shaded.apache.log4j.Xyz
</code>```

These classes will still load the apache configuration as expected like log4.properties file in the resources.
The "standard" Apache Log4J classes will have troubles interoperating with those (e.g. the apache Appenders cannot be used in the log4j.properties which is loaded by the Athena driver because of this).

In the case you just want to get around the error messages created by the Athena driver (potentially not even using Log4J in the application like in the case I mentioned) you can address the Classes in the shaded packages within a standard 1.2 Log4J config and remove any Log4J dependencies from the build path.

Example:

Instead of

```<code>log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
</code>```

Use

```<code>log4j.appender.Appender1=com.simba.athena.shaded.apache.log4j.ConsoleAppender
</code>```

I know it's not a perfect solution for all scenarios, but at least you can control errors spilled by the Athena driver this way.

Body:
I have trouble getting the Athena JDBC driver logging in place correctly. I'd favour SL4J SimpleLogger, but it seems this factory is not supported, but ust Log4J (just writing this in case you wonder why there's 2 logging framework). Unfortunately we do not want to change all current app logging because of one new jdbc driver.

When instantiating the logger without Log4J dependency I get a ClassNotFoundException, which is expected and shows Log4J is not included.

log4j:ERROR A "org.apache.log4j.ConsoleAppender" object is not assignable to a "com.simba.athena.shaded.apache.log4j.Appender" variable.
log4j:ERROR The class "com.simba.athena.shaded.apache.log4j.Appender" was loaded by
log4j:ERROR [jdk.internal.loader.ClassLoaders$AppClassLoader@368239c8] whereas object of type
log4j:ERROR "org.apache.log4j.ConsoleAppender" was loaded by [jdk.internal.loader.ClassLoaders$AppClassLoader@368239c8].
log4j:ERROR Could not instantiate appender named "stdout".

Maven Dependencies:

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.syncron.amazonaws</groupId>
            <artifactId>simba-athena-jdbc-driver</artifactId>
            <version>2.0.2</version>
        </dependency>

log4j.properties

### Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

### Log Levels
log4j.rootLogger=info, stdout

It's kind of strange as both classes ARE loaded with the same classloader, so a classloader hierarchy issue shouldn't be the problem. I also verified the driver binds Log4J 1.2 as it points to that JavaDocs in some errors.

Would appreciate any hint from a Log4J expert. Thanks!

Body:
Here's my findings after some time debugging classloading if someone experioences the same issues:

The Simba Athena driver provided by AWS comes with Log4J included. The Log4J Apache Classes are repackaged in a "shaded" package:

com.simba.athena.shaded.apache.log4j.Xyz

These classes will still load the apache configuration as expected like log4.properties file in the resources.
The "standard" Apache Log4J classes will have troubles interoperating with those (e.g. the apache Appenders cannot be used in the log4j.properties which is loaded by the Athena driver because of this).

In the case you just want to get around the error messages created by the Athena driver (potentially not even using Log4J in the application like in the case I mentioned) you can address the Classes in the shaded packages within a standard 1.2 Log4J config and remove any Log4J dependencies from the build path.

Example:

Instead of

log4j.appender.Appender1=org.apache.log4j.ConsoleAppender

Use

log4j.appender.Appender1=com.simba.athena.shaded.apache.log4j.ConsoleAppender

I know it's not a perfect solution for all scenarios, but at least you can control errors spilled by the Athena driver this way.


问:
Cron job not running python
I tried to get cron to run a python file but it doesn't seem to run. The command in cron is:

```<code>24 21 * * * python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py
</code>```

And the following appeared in the log:

```<code>Feb 16 21:24:01 MSI CRON[3839]: (slatifi) CMD (python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py)
</code>```

However, it doesn't actually run the code. When I run the command in backets above it works with no issues. Please advise.

Update (after Romeo's responce):

I have now move the command to a script (automate_script):

```<code>#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/usr/bin/python3 automate.py
</code>```

And I now have the following in Crontab:

```<code>50 14 * * * /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script
</code>```

And when running /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script in the command line it works, however, it does run with cron as it appears in the log but nothing happens.

答:
Interesting... your cron is set properly and it is working. The problem is probably with your script.
Maybe you forgot to add the exec permission to it?
Try running chmod +x path/to/your/script and then run your cron again.

Title: Cron job not running python

Body:
I tried to get cron to run a python file but it doesn't seem to run. The command in cron is:

24 21 * * * python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py

And the following appeared in the log:

Feb 16 21:24:01 MSI CRON[3839]: (slatifi) CMD (python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py)

However, it doesn't actually run the code. When I run the command in backets above it works with no issues. Please advise.

Update (after Romeo's responce):

I have now move the command to a script (automate_script):

#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/usr/bin/python3 automate.py

And I now have the following in Crontab:

50 14 * * * /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script

And when running /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script in the command line it works, however, it does run with cron as it appears in the log but nothing happens.


问:
Parameter in Controller is giving null value exception in asp.net mvc
I am making a text-box with drop down for auto-completing suggestion using jquery and ajax but the error I have found through debugging is that when the debug point comes to the given code it successfully moves to return statement and when comes second time on the same statement it gives an exception that "Keyword is null" (Keyword is the alphabet entered by the user in the textbox)

```<code>var result = (from a in objGameList where
a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });
</code>```

Here is the code:

Index.cs

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#GameName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { keyword: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.GameName, value: item.GameName };
                        }))
                    },
                    error: function () {
                        alert('something went wrong !');
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <div class="form-group">
            <div>
                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>
    </div>
}
```
```
<p><strong>Controller.cs</strong></p>
```[HttpPost]
    public JsonResult Index(string keyword)
    {
        //This can be replaced with database call.

        List<Games> objGameList = new List<Games>(){
            new Games {Id=1,GameName="Cricket" },
            new Games {Id=2,GameName="Football" },
            new Games {Id=3,GameName="Chesh" },
            new Games {Id=4,GameName="VallyBall" },
        };

        var result = (from a in objGameList
                        where a.GameName.ToLower().StartsWith(keyword.ToLower())
                        select new { a.GameName });

        return Json(result);
    }
```

Thanks in advance.

答:
So I made an example from scratch to see if it wouldn't work and... it worked so please follow the example and try to figure out what is different in your aproach. I'll point out every change I made compared to the code fragments You have provided.

I'll start with the new empty project.

```<code>dotnet new mvc -o test
</code>```

I copy and paste entire POST action of Yours into the HomeController.cs, fixing imports and generating a missing Games model, putting that file into .\Models\Games.cs:

```<code>namespace test.Models
{
    public class Games // changed the default visibility to public
    {
        public int Id { get; set; }
        public string GameName { get; set; }
    }
}
</code>```

I replaced content of ./Views/Home/Index.cshtml with Your view (adding at the top of the file the line: @Model Games to let the view know about the model so the @Html.EditorFor() be able to generate the form control - without it i got an error: CS1963  An expression tree may not contain a dynamic operation):

So:

```<code>@model Games
<script type="text/javascript">
...
</code>```

I have putted jQuery imports in .\Shared\_Layout.cshtml:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
...
</code>```

and removed reference to any other js file:

```<code>...
    </footer>
</body>
</html>
</code>```

Lastly I have edited the default action of HomeController:

```<code>public IActionResult Index()
{
  return View(new Games()); // added new Games object to be injected as a model for the view.
}
</code>```

At that stage I do not encounter anything what You have described. Although I got an error: Uncaught TypeError: this.options.messages.results is not a function but this is something completly different and can be solved by replacing

```<code>    messages: {
        noResults: "", results: ""
    }
});
</code>```

with this:

```<code>    messages: {
        noResults: "", results : function(count) {
        return "";
      }
    }
});
</code>```

The solution results in no errors and working mechanism.

Please play around with it, it simply ahould work. All I can come up with is the different library version.

Body:
I am making a text-box with drop down for auto-completing suggestion using jquery and ajax but the error I have found through debugging is that when the debug point comes to the given code it successfully moves to return statement and when comes second time on the same statement it gives an exception that "Keyword is null" (Keyword is the alphabet entered by the user in the textbox)

var result = (from a in objGameList where
a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });

Here is the code:

Index.cs

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })

}
```

Controller.cs

[HttpPost]
    public JsonResult Index(string keyword)
    {
        //This can be replaced with database call.

        List<Games> objGameList = new List<Games>(){
            new Games {Id=1,GameName="Cricket" },
            new Games {Id=2,GameName="Football" },
            new Games {Id=3,GameName="Chesh" },
            new Games {Id=4,GameName="VallyBall" },
        };

        var result = (from a in objGameList
                        where a.GameName.ToLower().StartsWith(keyword.ToLower())
                        select new { a.GameName });

        return Json(result);
    }

Thanks in advance.

Body:
So I made an example from scratch to see if it wouldn't work and... it worked so please follow the example and try to figure out what is different in your aproach. I'll point out every change I made compared to the code fragments You have provided.

I'll start with the new empty project.

dotnet new mvc -o test

I copy and paste entire POST action of Yours into the HomeController.cs, fixing imports and generating a missing Games model, putting that file into .\Models\Games.cs:

namespace test.Models
{
    public class Games // changed the default visibility to public
    {
        public int Id { get; set; }
        public string GameName { get; set; }
    }
}

I replaced content of ./Views/Home/Index.cshtml with Your view (adding at the top of the file the line: @Model Games to let the view know about the model so the @Html.EditorFor() be able to generate the form control - without it i got an error: CS1963  An expression tree may not contain a dynamic operation):

So:

@model Games
<script type="text/javascript">
...

I have putted jQuery imports in .\Shared\_Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
...

and removed reference to any other js file:

...
    </footer>
</body>
</html>

Lastly I have edited the default action of HomeController:

public IActionResult Index()
{
  return View(new Games()); // added new Games object to be injected as a model for the view.
}

At that stage I do not encounter anything what You have described. Although I got an error: Uncaught TypeError: this.options.messages.results is not a function but this is something completly different and can be solved by replacing

    messages: {
        noResults: "", results: ""
    }
});

with this:

    messages: {
        noResults: "", results : function(count) {
        return "";
      }
    }
});

The solution results in no errors and working mechanism.

Please play around with it, it simply ahould work. All I can come up with is the different library version.


问:
Converting number to a padded string
I am trying to convert numeric types to fixed length string representations with leading '0's (used in a GUI that can only deal with strings - and lexicographic sorting of numbers is really awkward).

Instead of creating the string on the spot where it is required, I figure it should be possible to make a nice template for others to use that also works with different arithmetic types.

```<code>template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>
std::string arithmeticToMaxLengthString(const T& value)
{
  std::string number, result;
  number = std::to_string( value );
  result = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, number );
  return result;
}

std::string lpad( char filler, std::string::size_type length, const std::string& input)
{
  std::string result;
  if( input.length() < length )
  {
     result.append( lenght - input.lenght(), filler ).append( input );
     return result;
  }
  return input;
}
</code>```

So far so good.
It compiles and I can use it.
BUT:

When I tried using it, I got a surprise.
Calling this function with an int32_t which is

```<code>typedef int int32_t;
</code>```

that has a value of 100 the result is the string "100", length 3.

I am pretty certain that no other template with such a bad name exists in the codebase (I have search through all of it, and all linked libraries), but I can not seem to understand what is wrong with the code I have produced.
To verify the code to be correct I have just copy-pasted it to the place it is called, which now basically looks like this:

```<code>myDataClass{
  int32_t     quantity;
  std::string numberAsString;
}

void setNumberString( myDataClass data )
{
   std::string result    = arithmeticToMaxLengthString( data.quantity );
   std::string reference = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, std::to_string(data.quantity) );
   std::cout << "quantity<" << data.quantity << "> numericLimits<" << std::numeric_limits<decltype(value)>::digits10 + 1 << ">" << std::endl;
   std::cout << "result  template: length<" << result.lenght()    << "> content<" << result    << ">" << std::endl;
   std::cout << "result reference: length<" << reference.lenght() << "> content<" << reference << ">" << std::endl;
}
</code>```

Now to my understanding the template "arithmeticToMaxLengthString" is called with int32_t as the type of the argument, which is a normal int, where "numeric_limits::digits10 + 1" gives me 10.
But when this funtion is now called with a quantity of say 100 the results differ.

```<code>quantity<100> numericLimits<10>
result  template: length<3> content<100>
result reference: length<10> content<0000000100>
</code>```

Am I missing something about templates, enable_if or numeric_limits?
In what way does the template differ (aside from the obvious enable_if) ?

答:
This is not really the answer to your question, but the suggestion of how to implement the same functionality using STL.

```<code>#include <iomanip>
#include <sstream>

template <typename T, unsigned N = 5>
std::string to_string_with_leading_0(T element) {
    std::stringstream ss;
    ss << std::setw(N) << std::setfill('0') << element;
    return ss.str();
}
</code>```

Title: Converting number to a padded string

Body:
I am trying to convert numeric types to fixed length string representations with leading '0's (used in a GUI that can only deal with strings - and lexicographic sorting of numbers is really awkward).

Instead of creating the string on the spot where it is required, I figure it should be possible to make a nice template for others to use that also works with different arithmetic types.

template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>
std::string arithmeticToMaxLengthString(const T& value)
{
  std::string number, result;
  number = std::to_string( value );
  result = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, number );
  return result;
}

std::string lpad( char filler, std::string::size_type length, const std::string& input)
{
  std::string result;
  if( input.length() < length )
  {
     result.append( lenght - input.lenght(), filler ).append( input );
     return result;
  }
  return input;
}

So far so good.
It compiles and I can use it.
BUT:

When I tried using it, I got a surprise.
Calling this function with an int32_t which is

typedef int int32_t;

that has a value of 100 the result is the string "100", length 3.

I am pretty certain that no other template with such a bad name exists in the codebase (I have search through all of it, and all linked libraries), but I can not seem to understand what is wrong with the code I have produced.
To verify the code to be correct I have just copy-pasted it to the place it is called, which now basically looks like this:

myDataClass{
  int32_t     quantity;
  std::string numberAsString;
}

void setNumberString( myDataClass data )
{
   std::string result    = arithmeticToMaxLengthString( data.quantity );
   std::string reference = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, std::to_string(data.quantity) );
   std::cout << "quantity<" << data.quantity << "> numericLimits<" << std::numeric_limits<decltype(value)>::digits10 + 1 << ">" << std::endl;
   std::cout << "result  template: length<" << result.lenght()    << "> content<" << result    << ">" << std::endl;
   std::cout << "result reference: length<" << reference.lenght() << "> content<" << reference << ">" << std::endl;
}

Now to my understanding the template "arithmeticToMaxLengthString" is called with int32_t as the type of the argument, which is a normal int, where "numeric_limits::digits10 + 1" gives me 10.
But when this funtion is now called with a quantity of say 100 the results differ.

quantity<100> numericLimits<10>
result  template: length<3> content<100>
result reference: length<10> content<0000000100>

Am I missing something about templates, enable_if or numeric_limits?
In what way does the template differ (aside from the obvious enable_if) ?

Body:
This is not really the answer to your question, but the suggestion of how to implement the same functionality using STL.

#include <iomanip>
#include <sstream>

template <typename T, unsigned N = 5>
std::string to_string_with_leading_0(T element) {
    std::stringstream ss;
    ss << std::setw(N) << std::setfill('0') << element;
    return ss.str();
}