问:
C++: Redirecting STDOUT
In my application, I want to redirect the output that would normally go to the stdout stream to a function I define. I read that you can redirect stdio to a file, so why not to a function?

For example:

```<code>void MyHandler( const char* data );

//<<Magical redirection code>>

printf( "test" );
std::cout << "test" << std::endl;

//MyHandler should have been called with "test" twice, at this point
</code>```

How can I achieve this / similar behaviour?

答:
@Konrad Rudolph is right, you can totally do this, easily, at least for cout/cerr/clog.  You don't even need your own streambuf implementation, just use an ostringstream.

```<code>// Redirect cout.
streambuf* oldCoutStreamBuf = cout.rdbuf();
ostringstream strCout;
cout.rdbuf( strCout.rdbuf() );

// This goes to the string stream.
cout << "Hello, World!" << endl;

// Restore old cout.
cout.rdbuf( oldCoutStreamBuf );

// Will output our Hello World! from above.
cout << strCout.str();
</code>```

Same thing works for cerr and clog, but in my experience that will NOT work for stdout/stderr in general, so printf won't output there.  cout goes to stdout, but redirecting cout will not redirect all stdout.  At least, that was my experience.

If the amount of data is expected to be small, the freopen/setbuf thing works fine.  I ended up doing the fancier dup/dup2 thing redirecting to a pipe.

Update: I wrote a blog post showing the dup2 method I ended up using, which you can read here.  It's written for OS X, but might work in other Unix flavors.  I seriously doubt it would work in Windows.  Cocoa version of the same thing here.

ContentLicense: CC BY-SA 2.5

Title: C++: Redirecting STDOUT

Body:
In my application, I want to redirect the output that would normally go to the stdout stream to a function I define. I read that you can redirect stdio to a file, so why not to a function?

For example:

void MyHandler( const char* data );

//<<Magical redirection code>>

printf( "test" );
std::cout << "test" << std::endl;

//MyHandler should have been called with "test" twice, at this point

How can I achieve this / similar behaviour?

Body:
@Konrad Rudolph is right, you can totally do this, easily, at least for cout/cerr/clog.  You don't even need your own streambuf implementation, just use an ostringstream.

// Redirect cout.
streambuf* oldCoutStreamBuf = cout.rdbuf();
ostringstream strCout;
cout.rdbuf( strCout.rdbuf() );

// This goes to the string stream.
cout << "Hello, World!" << endl;

// Restore old cout.
cout.rdbuf( oldCoutStreamBuf );

// Will output our Hello World! from above.
cout << strCout.str();

Same thing works for cerr and clog, but in my experience that will NOT work for stdout/stderr in general, so printf won't output there.  cout goes to stdout, but redirecting cout will not redirect all stdout.  At least, that was my experience.

If the amount of data is expected to be small, the freopen/setbuf thing works fine.  I ended up doing the fancier dup/dup2 thing redirecting to a pipe.

Update: I wrote a blog post showing the dup2 method I ended up using, which you can read here.  It's written for OS X, but might work in other Unix flavors.  I seriously doubt it would work in Windows.  Cocoa version of the same thing here.


来源: stackexchange

问:
What exactly is JavaScript factory functions?
What exactly is factoryfunctions in JavaScript ? What problems does it solve ? What is the real time example ?

答:
The factory function is a normal function that build an object and return it. For example we can create a person interface/class in this way:

```<code>function createPerson(name,age)
{
   let per  = new Object();
   per.name = name;
   per.age  = age;
   per.sayName() = function(){
                      return this.name;
                      };
  return per;
}
</code>```

With this factory function pattern you can create a new instance of  person in this way:

```<code>let myNewPerson = createPerson("Nick",20);
</code>```

The main problem of this pattern is that the functions property aren't on the prototype trereby a new object (an anonymous function is an object, an instance of Function) is created for each function property. Furthermore this pattern doesn't address the issue of object identification namely isn't possible to say what type of object an object is.

ContentLicense: CC BY-SA 4.0

Body:
The factory function is a normal function that build an object and return it. For example we can create a person interface/class in this way:

function createPerson(name,age)
{
   let per  = new Object();
   per.name = name;
   per.age  = age;
   per.sayName() = function(){
                      return this.name;
                      };
  return per;
}

With this factory function pattern you can create a new instance of  person in this way:

let myNewPerson = createPerson("Nick",20);

The main problem of this pattern is that the functions property aren't on the prototype trereby a new object (an anonymous function is an object, an instance of Function) is created for each function property. Furthermore this pattern doesn't address the issue of object identification namely isn't possible to say what type of object an object is.


问:
duplicate results on query for pair-wise relationships between rows for a SQL Server table
I work creating a database of merchants traders in the Atlantic at the end of the fifteen century. I wrote this query to find the relationships of individuals in the same contracts. It works fine, but It is creating duplicate results in the sense that will give for example; 'a,b,01-01-1500' and 'b,a,01-01-1500'. For me, it is a problem since I am not considering directionality at this point. I tried to simply filter the results but it created a more significant problem, as it just left one result regardless if the association had happened on a different date or a different contract (which granted was probably my fault, filtering is something I am still learning)

What would be a way to avoid this issue?

```<code>SELECT d1.gen_id as 'source',
d2.gen_id as 'target',
        c.date as 'timestamp'
from (
Select * from deed_party1
    ) as d1
    INNER JOIN
    (
    select * from deed_party1
    ) as d2
    on d1.deed_id = d2.deed_id
inner join contracts as c
on d1.deed_id = c.id
where d1.gen_id != d2.gen_id AND c.date between '1500-01-01' AND '1509-12-31';
</code>```

Thanks for reading and your help,

答:
You simply want < rather than !=.  But the subqueries are not necessary, so:

```<code>select d1.gen_id as source, d2.gen_id as target,
       c.date as timestamp
from deed_party1 d1 join
     deed_party1 d2
     on d1.deed_id = d2.deed_id and
        d1.gen_id < d2.gen_id join
     contracts c
     on d1.deed_id = c.id
where c.date between '1500-01-01' AND '1509-12-31';
</code>```

Also:

Do not unnecessarily use subqueries.  In most databases, this just clutters the query unnecessarily.  MySQL has a tendency to materialize subqueries, so subqueries can have a (negative) performance impact as well.

Do not use single quotes to delimit column names.  Single quotes should only be used for string and date constants.

If you must escape column names, use backticks.

Do not choose names that are already used by SQL, such as timestamp.  This is safe in MySQL, but just a bad practice.

Body:
I work creating a database of merchants traders in the Atlantic at the end of the fifteen century. I wrote this query to find the relationships of individuals in the same contracts. It works fine, but It is creating duplicate results in the sense that will give for example; 'a,b,01-01-1500' and 'b,a,01-01-1500'. For me, it is a problem since I am not considering directionality at this point. I tried to simply filter the results but it created a more significant problem, as it just left one result regardless if the association had happened on a different date or a different contract (which granted was probably my fault, filtering is something I am still learning)

What would be a way to avoid this issue?

SELECT d1.gen_id as 'source',
d2.gen_id as 'target',
        c.date as 'timestamp'
from (
Select * from deed_party1
    ) as d1
    INNER JOIN
    (
    select * from deed_party1
    ) as d2
    on d1.deed_id = d2.deed_id
inner join contracts as c
on d1.deed_id = c.id
where d1.gen_id != d2.gen_id AND c.date between '1500-01-01' AND '1509-12-31';

Thanks for reading and your help,

Body:
You simply want < rather than !=.  But the subqueries are not necessary, so:

select d1.gen_id as source, d2.gen_id as target,
       c.date as timestamp
from deed_party1 d1 join
     deed_party1 d2
     on d1.deed_id = d2.deed_id and
        d1.gen_id < d2.gen_id join
     contracts c
     on d1.deed_id = c.id
where c.date between '1500-01-01' AND '1509-12-31';

Also:

Do not unnecessarily use subqueries.  In most databases, this just clutters the query unnecessarily.  MySQL has a tendency to materialize subqueries, so subqueries can have a (negative) performance impact as well.

Do not use single quotes to delimit column names.  Single quotes should only be used for string and date constants.

If you must escape column names, use backticks.

Do not choose names that are already used by SQL, such as timestamp.  This is safe in MySQL, but just a bad practice.


问:
In what order does a minheap sort?
I've been reading various definitions on minHeap and maxHeap. I stumbled upon statements which say:

minHeap is used to sort in descending order.

maxHeap is used to sort in ascending order.

Statements taken from the "Note" in https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/ .
But when I implement minHeap using PriorityQueue<Integer> in Java with default comparator, and poll() it, I get the minimum element. Why is that?
Thanks to anybody who's trying to help :).

答:
The explanation in the blog is correct

While having a close look at the heapSort() function, it has smartly made use of min heap. The smallest element of the array gets replaced with the last element and size of heap is reduced by 1 to again heapify() it.

arr[0] -> represents the smallest element.

In every iteration, for i from n-1 to 0, the arr[0] is swapped with the arr[i]  and heap is again heapified with size of 1 smaller than previous iteration.

Title: In what order does a minheap sort?


问:
Is it possible to add icon inside Material UI Tooltip?
Here is my code. I have tried to use the material icon(PhoneInTalk) inside Tooltip's title attribute. But my process seems not working.
Here is my output:
enter image description here

//@material-ui/core/styles
const CustomTooltip = withStyles({
  tooltip: {
    color: "tomato",
    backgroundColor: "black",
    fontWeight: "bold",
    fontSize: "12px",
  },
})(Tooltip);

//JSX
<CustomTooltip
        title={`${(<PhoneInTalk />)} Let's talk`}
        placement="top-end"
        arrow
        >
<Avatar className={classes.avatar} src={avatar} alt="Ibrahim Kaiser" />
</CustomTooltip>```

答:
Try enclosing the icon and text in a fragment.

```<code><CustomTooltip
    title={<><PhoneInTalk /> Let's talk</>}
    placement="top-end"
    arrow
>
</code>```

Check this example sandbox link

Body:
Try enclosing the icon and text in a fragment.

<CustomTooltip
    title={<><PhoneInTalk /> Let's talk</>}
    placement="top-end"
    arrow
>

Check this example sandbox link


问:
Extract ipv6 prefix in python
Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?

Is there a library that would do this for me, or would I have to:

convert the address from string to an int (inet_ntop)

Mask out the prefix

Convert prefix back to binary

Convert binary to string (inet_ntop)

答:
You can also write a small own function which extracts the IPv6 prefix:</p>

```<code># Returns the IPv6 prefix
def getIPv6Prefix(ipv6Addr, prefixLen):
    prefix = ""
    curPrefixLen = 0
    ipv6Parts = ipv6Addr.split(":")
    for part in ipv6Parts:
        if not prefix == "": # if it's not empty
            prefix = prefix + ":"
        prefix = prefix + part
        curPrefixLen += 32
        if int(curPrefixLen) >= int(prefixLen):
            return prefix
    return prefix
</code>```

OwnerDisplayName: Readonly

Title: Extract ipv6 prefix in python

Body:
You can also write a small own function which extracts the IPv6 prefix:

# Returns the IPv6 prefix
def getIPv6Prefix(ipv6Addr, prefixLen):
    prefix = ""
    curPrefixLen = 0
    ipv6Parts = ipv6Addr.split(":")
    for part in ipv6Parts:
        if not prefix == "": # if it's not empty
            prefix = prefix + ":"
        prefix = prefix + part
        curPrefixLen += 32
        if int(curPrefixLen) >= int(prefixLen):
            return prefix
    return prefix


问:
Label.image shows AttributeError: 'NoneType' object has no attribute 'image'
I have been trying to use the following code for showing image on labels:

for i in range (0, 10):
   img = Image.open("Toy Story.PNG")
   img.load()
   img = img.resize((100, 100), Image.ANTIALIAS)
   img_title = ImageTk.PhotoImage(img)
   print(img_title)
   myLabel_image = Label(tab_recommend, height = 90, width = 90, image = img_title).place(x=108,y=200)
   myLabel_image.image = img_title #For creating reference
```

The last line is giving no attribute error and when I remove the last line, the image disappears.

答:
Try changing last two lines to:

```<code>myLabel_image = Label(tab_recommend, height = 90, width = 90, image = img_title)
myLabel_image.place(x=108,y=200)
myLabel_image.image = img_title
</code>```

place method does not return Label, but modifies it in-place, returning None.

Body:
I have been trying to use the following code for showing image on labels:

for i in range (0, 10):
   img = Image.open("Toy Story.PNG")
   img.load()
   img = img.resize((100, 100), Image.ANTIALIAS)
   img_title = ImageTk.PhotoImage(img)
   print(img_title)
   myLabel_image = Label(tab_recommend, height = 90, width = 90, image = img_title).place(x=108,y=200)
   myLabel_image.image = img_title #For creating reference

The last line is giving no attribute error and when I remove the last line, the image disappears.

Body:
Try changing last two lines to:

myLabel_image = Label(tab_recommend, height = 90, width = 90, image = img_title)
myLabel_image.place(x=108,y=200)
myLabel_image.image = img_title

place method does not return Label, but modifies it in-place, returning None.


问:
How do you round a double in Dart to a given degree of precision AFTER the decimal point?
Given a double, I want to round it to a given number of points of precision after the decimal point, similar to PHP's round() function.

The closest thing I can find in the Dart docs is double.toStringAsPrecision(), but this is not quite what I need because it includes the digits before the decimal point in the total points of precision.

For example, using toStringAsPrecision(3):

```<code>0.123456789 rounds to 0.123
9.123456789 rounds to 9.12
98.123456789 rounds to 98.1
987.123456789 rounds to 987
9876.123456789 rounds to 9.88e+3
</code>```

As the magnitude of the number increases, I correspondingly lose precision after the decimal place.

答:
To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed() method, but you have to convert it back to double

```<code>void main() {
  double step1 = 1/3;
  print(step1); // 0.3333333333333333

  String step2 = step1.toStringAsFixed(2);
  print(step2); // 0.33

  double step3 = double.parse(step2);
  print(step3); // 0.33
}

</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given a double, I want to round it to a given number of points of precision after the decimal point, similar to PHP's round() function.

The closest thing I can find in the Dart docs is double.toStringAsPrecision(), but this is not quite what I need because it includes the digits before the decimal point in the total points of precision.

For example, using toStringAsPrecision(3):

0.123456789 rounds to 0.123
9.123456789 rounds to 9.12
98.123456789 rounds to 98.1
987.123456789 rounds to 987
9876.123456789 rounds to 9.88e+3

As the magnitude of the number increases, I correspondingly lose precision after the decimal place.

Body:
To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed() method, but you have to convert it back to double

void main() {
  double step1 = 1/3;
  print(step1); // 0.3333333333333333

  String step2 = step1.toStringAsFixed(2);
  print(step2); // 0.33

  double step3 = double.parse(step2);
  print(step3); // 0.33
}


问:
Flutter Countdown Timer
How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...</p>

```<code>import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;

  TimerButton(this.timerTastoPremuto);

  @override
  _TimerButtonState createState() => _TimerButtonState();
}

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}
</code>```

答:
Here is my Timer widget, not related to the Question but may help someone.

```<code>import 'dart:async';

import 'package:flutter/material.dart';

class OtpTimer extends StatefulWidget {
  @override
  _OtpTimerState createState() => _OtpTimerState();
}

class _OtpTimerState extends State<OtpTimer> {
  final interval = const Duration(seconds: 1);

  final int timerMaxSeconds = 60;

  int currentSeconds = 0;

  String get timerText =>
      '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: ${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';

  startTimeout([int milliseconds]) {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      setState(() {
        print(timer.tick);
        currentSeconds = timer.tick;
        if (timer.tick >= timerMaxSeconds) timer.cancel();
      });
    });
  }

  @override
  void initState() {
    startTimeout();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Icon(Icons.timer),
        SizedBox(
          width: 5,
        ),
        Text(timerText)
      ],
    );
  }
}
</code>```

You will get something like this

Title: Flutter Countdown Timer

Body:
How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;

  TimerButton(this.timerTastoPremuto);

  @override
  _TimerButtonState createState() => _TimerButtonState();
}

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}

Body:
Here is my Timer widget, not related to the Question but may help someone.

import 'dart:async';

import 'package:flutter/material.dart';

class OtpTimer extends StatefulWidget {
  @override
  _OtpTimerState createState() => _OtpTimerState();
}

class _OtpTimerState extends State<OtpTimer> {
  final interval = const Duration(seconds: 1);

  final int timerMaxSeconds = 60;

  int currentSeconds = 0;

  String get timerText =>
      '${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: ${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';

  startTimeout([int milliseconds]) {
    var duration = interval;
    Timer.periodic(duration, (timer) {
      setState(() {
        print(timer.tick);
        currentSeconds = timer.tick;
        if (timer.tick >= timerMaxSeconds) timer.cancel();
      });
    });
  }

  @override
  void initState() {
    startTimeout();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Icon(Icons.timer),
        SizedBox(
          width: 5,
        ),
        Text(timerText)
      ],
    );
  }
}

You will get something like this


问:
How to add one more button in DateTimePicker of material UI?
I am using DateTimePicker in my React application.

I want to add one Clear button to the left of the Cancel Button.

```<code>import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";

<MuiPickersUtilsProvider utils={DateFnsUtils}>
            <DateTimePicker
              autoOk
              inputVariant="outlined"
              value={date}
              onChange={e =>handleSetDate(e.getTime())
              }
            />
          </MuiPickersUtilsProvider>
</code>```

How can I do that?

Thanks in Advance!!

答:
Just use clearable prop and set it to true.

Working demo is here

Code Snippet

      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <DateTimePicker
          autoOk
          label="Clearable"
          clearable
          disableFuture
          value={selectedDate}
          // onChange={handleDateChange}  //<---reset back to blank date
          onChange={(e) => { handleDateChange(e ? e : new Date()) }} //<---reset back to initial date
        />
      </MuiPickersUtilsProvider>
```

Just a heads up: I had to use version 1x of @date-io/date-fns as I was getting some unrelated error. See here.  Keep it in mind while playing around.

Body:
I am using DateTimePicker in my React application.

I want to add one Clear button to the left of the Cancel Button.

import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";

<MuiPickersUtilsProvider utils={DateFnsUtils}>
            <DateTimePicker
              autoOk
              inputVariant="outlined"
              value={date}
              onChange={e =>handleSetDate(e.getTime())
              }
            />
          </MuiPickersUtilsProvider>

How can I do that?

Thanks in Advance!!

Body:
Just use clearable prop and set it to true.

Working demo is here

Code Snippet

      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <DateTimePicker
          autoOk
          label="Clearable"
          clearable
          disableFuture
          value={selectedDate}
          // onChange={handleDateChange}  //<---reset back to blank date
          onChange={(e) => { handleDateChange(e ? e : new Date()) }} //<---reset back to initial date
        />
      </MuiPickersUtilsProvider>

Just a heads up: I had to use version 1x of @date-io/date-fns as I was getting some unrelated error. See here.  Keep it in mind while playing around.


问:
What is the difference between a normal file download and a PHP-driven download?
Is there a difference between directly downloading a file from a web server, and downloading the same file through a PHP script that uses these headers?  (Assume that all of the variables here contain correct values for the file being downloaded.)

```<code>header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
</code>```

After reading the discussion here, i want to change the question :

With a file on server for user who can download.

What & when do we need to process this task by PHP script?

Same question with direct link of file

答:
Not as far as the client is concerned, no.

The difference for the server is that you have the full power of PHP to do something with before initiating the download, which is not the case if Apache handles the download directly. It also means that the whole cruft of PHP needs to be loaded and executed before a download can start and it'll occupy one PHP process until the download is finished.

Body:
Is there a difference between directly downloading a file from a web server, and downloading the same file through a PHP script that uses these headers?  (Assume that all of the variables here contain correct values for the file being downloaded.)

header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

After reading the discussion here, i want to change the question :

With a file on server for user who can download.

What & when do we need to process this task by PHP script?

Same question with direct link of file


问:
Replicating exp function with multiple inputs from R in python
I am attempting to replicate an R script in python, and have come across an exponential function that I do not understand:

```<code>exp(-var1-var2-var3)
</code>```

If I were to use 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588. However, I do not know how this is arrived at. I understand that the equivalent of exp in python is **, and know how to replicate this function with only one number as input but I see no way to do this with multiple numbers. I have tried -var1**-var2**-var3, which gives me -1.235241.

How do I interpret this function, and what would the equivalent python code be for this?

答:
The function exp means e**(-var1-var2-var3)

You can translate from R to python by using math or numpy:

```<code>import numpy as np
import math

var1=0.8
var2=1.2
var3=0.3
print('numpy:',np.exp(-var1-var2-var3))
print('math:',math.exp( -var1-var2-var3 ))
</code>```

The output of the following code will be

```<code>numpy: 0.10025884372280375
math: 0.10025884372280375
</code>```

Body:
I am attempting to replicate an R script in python, and have come across an exponential function that I do not understand:

exp(-var1-var2-var3)

If I were to use 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588. However, I do not know how this is arrived at. I understand that the equivalent of exp in python is **, and know how to replicate this function with only one number as input but I see no way to do this with multiple numbers. I have tried -var1**-var2**-var3, which gives me -1.235241.

How do I interpret this function, and what would the equivalent python code be for this?

Body:
The function exp means e**(-var1-var2-var3)

You can translate from R to python by using math or numpy:

import numpy as np
import math

var1=0.8
var2=1.2
var3=0.3
print('numpy:',np.exp(-var1-var2-var3))
print('math:',math.exp( -var1-var2-var3 ))

The output of the following code will be

numpy: 0.10025884372280375
math: 0.10025884372280375


问:
GridSearchCV has no attribute best_estimator_
I keep getting the error about the attribute when it worked 20 minutes ago. I am not sure what can be going wrong, when I set up the code on a seperate notebook it ran and GridSearchCV moved along smoothly. Do I need to update Scikit-Learn? I posted the entire code because I believe it is essential in case little details are missing. Any help is appreciated.</p>

```<code>import pandas as pd
train_data = pd.read_csv("~/Desktop/Personal/Data/train.csv")
test_features = pd.read_csv("~/Desktop/Personal/Data/test.csv")
test_survived = pd.read_csv("~/Desktop/Personal/Data/gender_submission.csv")

from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV

def data_process(data):
    data = data.drop("Cabin", 1)
    data = data.drop("Embarked", 1)
    data = data.drop("Ticket",1)
    data = data.drop("Name", 1)
    data = data.drop("PassengerId", 1)
    data["Sex"] = LabelEncoder().fit_transform(data["Sex"])

    numerical_attr = ["Age", "Pclass", "SibSp", "Parch", "Fare"]

    for attr in numerical_attr:
        data[attr].fillna(round(data[attr].mean(), 0), inplace=True)
    return data

train_data = data_process(train_data)

test_features = data_process(test_features).to_numpy()

test_survived = test_survived.drop("PassengerId", 1).to_numpy()

full_train_features = train_data.drop("Survived", 1).to_numpy()

full_train_survived = train_data.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

train_set,test_set = train_test_split(train_data, test_size = 0.3, random_state = 1)

part_train_set_features = train_set.drop("Survived", 1).to_numpy()
part_train_set_survived = train_set.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

val_set_features = test_set.drop("Survived", 1).to_numpy()
val_set_survived = test_set.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

log_reg = LogisticRegression(solver = 'liblinear')

log_reg.fit(part_train_set_features, part_train_set_survived)

predict_log_reg_base = log_reg.predict(val_set_features)
accuracy_log_reg_base = accuracy_score(predict_log_reg_base, val_set_survived)
print(accuracy_log_reg_base)

fixed_range1 = range(1,21)
c_values = [i/10 for i in fixed_range1]

fixed_range2 = range(10,21)
max_iter_values = [i*10 for i in fixed_range2]

parameters_log_reg = {'C' : c_values, 'penalty' : ['l1', 'l2'], 'max_iter' : max_iter_values}

log_reg_best = GridSearchCV(LogisticRegression(solver = 'liblinear'), parameters_log_reg, return_train_score = True)

final_log_reg = log_reg_best.best_estimator_
</code>```

答:
You need to fit it first:

```<code># define
log_reg_best = GridSearchCV(LogisticRegression(solver = 'liblinear'), parameters_log_reg, return_train_score = True)
# fit
log_reg_best.fit(part_train_set_features, part_train_set_survived)
# get best estimator
final_log_reg = log_reg_best.best_estimator_
</code>```

Body:
I keep getting the error about the attribute when it worked 20 minutes ago. I am not sure what can be going wrong, when I set up the code on a seperate notebook it ran and GridSearchCV moved along smoothly. Do I need to update Scikit-Learn? I posted the entire code because I believe it is essential in case little details are missing. Any help is appreciated.

import pandas as pd
train_data = pd.read_csv("~/Desktop/Personal/Data/train.csv")
test_features = pd.read_csv("~/Desktop/Personal/Data/test.csv")
test_survived = pd.read_csv("~/Desktop/Personal/Data/gender_submission.csv")

from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV

def data_process(data):
    data = data.drop("Cabin", 1)
    data = data.drop("Embarked", 1)
    data = data.drop("Ticket",1)
    data = data.drop("Name", 1)
    data = data.drop("PassengerId", 1)
    data["Sex"] = LabelEncoder().fit_transform(data["Sex"])

    numerical_attr = ["Age", "Pclass", "SibSp", "Parch", "Fare"]

    for attr in numerical_attr:
        data[attr].fillna(round(data[attr].mean(), 0), inplace=True)
    return data

train_data = data_process(train_data)

test_features = data_process(test_features).to_numpy()

test_survived = test_survived.drop("PassengerId", 1).to_numpy()

full_train_features = train_data.drop("Survived", 1).to_numpy()

full_train_survived = train_data.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

train_set,test_set = train_test_split(train_data, test_size = 0.3, random_state = 1)

part_train_set_features = train_set.drop("Survived", 1).to_numpy()
part_train_set_survived = train_set.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

val_set_features = test_set.drop("Survived", 1).to_numpy()
val_set_survived = test_set.drop(["Age", "Pclass", "SibSp", "Parch", "Fare", "Sex"], 1).to_numpy().ravel()

log_reg = LogisticRegression(solver = 'liblinear')

log_reg.fit(part_train_set_features, part_train_set_survived)

predict_log_reg_base = log_reg.predict(val_set_features)
accuracy_log_reg_base = accuracy_score(predict_log_reg_base, val_set_survived)
print(accuracy_log_reg_base)

fixed_range1 = range(1,21)
c_values = [i/10 for i in fixed_range1]

fixed_range2 = range(10,21)
max_iter_values = [i*10 for i in fixed_range2]

parameters_log_reg = {'C' : c_values, 'penalty' : ['l1', 'l2'], 'max_iter' : max_iter_values}

log_reg_best = GridSearchCV(LogisticRegression(solver = 'liblinear'), parameters_log_reg, return_train_score = True)

final_log_reg = log_reg_best.best_estimator_

Body:
You need to fit it first:

# define
log_reg_best = GridSearchCV(LogisticRegression(solver = 'liblinear'), parameters_log_reg, return_train_score = True)
# fit
log_reg_best.fit(part_train_set_features, part_train_set_survived)
# get best estimator
final_log_reg = log_reg_best.best_estimator_


问:
How to add a stacked layout in a tab widget in PyQt5?
I am trying to add multiple tables to a single tab of the QTabWidget with the help of QStackedLayout.
Here is my code:

```<code>class ui(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('ui')

        self.generalLayout = QGridLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        self.table()

    def table(self):
        self.tabs_layout = QTabWidget()
        self.stack_layout = QStackedLayout()

        self.display1 = QTableWidget()
        self.display1.setColumnCount(2)
        self.display1.setHorizontalHeaderLabels(['S. No.', 'Title'])
        self.header = self.display1.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.display2 = QTableWidget()
        self.display2.setColumnCount(2)
        self.display2.setHorizontalHeaderLabels(['S. No.', 'Name'])
        self.header = self.display2.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.stack_layout.addWidget(self.display1)
        self.stack_layout.addWidget(self.display2)

        self.tabs_layout.addTab(self.stack_layout,'1')
        self.generalLayout.addWidget(self.tabs_layout,0,0)

</code>```

Executing the above mentioned code I am getting the following error:

```<code>Traceback (most recent call last):
  File "ui.py", line 52, in <module>
    main()
  File "ui.py", line 44, in main
    window = ui()
  File "ui.py", line 15, in __init__
    self.table()
  File "ui.py", line 38, in table
    self.tabs_layout.addTab(self.stack_layout,'1')
TypeError: arguments did not match any overloaded call:
  addTab(self, QWidget, str): argument 1 has unexpected type 'QStackedLayout'
  addTab(self, QWidget, QIcon, str): argument 1 has unexpected type 'QStackedLayout'
</code>```

Is there any way to resolve this issue?

答:
QTabWidget.addTab excepts a widget as its first argument but you are supplying a layout. To get around this you could initialize a QWidget, set its layout to self.stack_layout and add this widget to self.tabs_layout instead of self.stack_layout. i.e. in table(self), replace self.tabs_layout.addTab(self.stack_layout,'1') with something like

```<code>tab = QWidget()
tab.setLayout(self.stack_layout)
self.tabs_layout.addTab(tab,'1')
</code>```

Body:
I am trying to add multiple tables to a single tab of the QTabWidget with the help of QStackedLayout.
Here is my code:

class ui(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('ui')

        self.generalLayout = QGridLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        self.table()

    def table(self):
        self.tabs_layout = QTabWidget()
        self.stack_layout = QStackedLayout()

        self.display1 = QTableWidget()
        self.display1.setColumnCount(2)
        self.display1.setHorizontalHeaderLabels(['S. No.', 'Title'])
        self.header = self.display1.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.display2 = QTableWidget()
        self.display2.setColumnCount(2)
        self.display2.setHorizontalHeaderLabels(['S. No.', 'Name'])
        self.header = self.display2.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.stack_layout.addWidget(self.display1)
        self.stack_layout.addWidget(self.display2)

        self.tabs_layout.addTab(self.stack_layout,'1')
        self.generalLayout.addWidget(self.tabs_layout,0,0)

Executing the above mentioned code I am getting the following error:

Traceback (most recent call last):
  File "ui.py", line 52, in <module>
    main()
  File "ui.py", line 44, in main
    window = ui()
  File "ui.py", line 15, in __init__
    self.table()
  File "ui.py", line 38, in table
    self.tabs_layout.addTab(self.stack_layout,'1')
TypeError: arguments did not match any overloaded call:
  addTab(self, QWidget, str): argument 1 has unexpected type 'QStackedLayout'
  addTab(self, QWidget, QIcon, str): argument 1 has unexpected type 'QStackedLayout'

Is there any way to resolve this issue?

Body:
QTabWidget.addTab excepts a widget as its first argument but you are supplying a layout. To get around this you could initialize a QWidget, set its layout to self.stack_layout and add this widget to self.tabs_layout instead of self.stack_layout. i.e. in table(self), replace self.tabs_layout.addTab(self.stack_layout,'1') with something like

tab = QWidget()
tab.setLayout(self.stack_layout)
self.tabs_layout.addTab(tab,'1')


问:
How to update ListView in Flutter
I am a beginner in flutter, and I want to update my listview when i load all files in mandarin directory. I am sure i have got all files and added them to tests, but i have no ideas what's wrong with my code, why listview doesn't display anything. Any ideas?

```<code> class _TeachersState extends State<TeachersList> {
      final _biggerFont = const TextStyle(fontSize: 18.0);
      List tests = List();

      Widget _buildSuggestions(BuildContext context) {
        initTests();
        return ListView.builder(
            itemCount: tests.length,
            padding: const EdgeInsets.all(16.0),
            itemBuilder: (context, i) {
              if (i.isOdd) return Divider();

              return _buildRow(tests[i]);
            });
      }

      void gotoTest(String title) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => TestList(title)));
      }

      Widget _buildRow(String pair) {
        return ListTile(
          onTap: () => gotoTest(pair),
          title: Text(
            pair,
            style: _biggerFont,
          ),
        );
      }

      void initTests() async {
        List t = List();
        String baseDir = await ExtStorage.getExternalStorageDirectory();
        String waDir = "$baseDir/mandarin";
        Directory dir = new Directory(waDir);
        dir.list().forEach((element) {
          t.add(element.path);
        });
        setState(() {
          tests.addAll(t);
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("请选择老师")),
          body: _buildSuggestions(context),
        );
      }
    }
</code>```

答:
Have you tried using the FutureBuilder widget ?

Check the code below:

Pass a snapshot to your buildSuggestion method

```<code>
      Widget _buildSuggestions(BuildContext context, AsyncSnapShot snapshot) {
        initTests();
        return ListView.builder(
            itemCount: snapshot.data.length,
            padding: const EdgeInsets.all(16.0),
            itemBuilder: (context, i) {
              if (i.isOdd) return Divider();

              return _buildRow(snapshot.data[i]);
            });
      }

</code>```

Change the function return type

```<code> Future initTests() async {
        List t = List();
        String baseDir = await ExtStorage.getExternalStorageDirectory();
        String waDir = "$baseDir/mandarin";
        Directory dir = new Directory(waDir);
        dir.list().forEach((element) {
          t.add(element.path);
        });
        setState(() {
          tests.addAll(t);
        });
        return tests;
      }

</code>```

Use a future builder widget in your body:

```<code>
     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("请选择老师")),
          body: FutureBuilder(
            future: initTests(),
            builder: (context, snapshot){
              if (snapshot.hasData){
                return _buildSuggestions(context, snapshot);
              } else {
                return CircularProgressIndicator();
              }
            },
          );
        );
      }
</code>```

It will show a Circle Progress Indicator until all the files have been read and then display them when done.

Title: How to update ListView in Flutter

Body:
I am a beginner in flutter, and I want to update my listview when i load all files in mandarin directory. I am sure i have got all files and added them to tests, but i have no ideas what's wrong with my code, why listview doesn't display anything. Any ideas?

 class _TeachersState extends State<TeachersList> {
      final _biggerFont = const TextStyle(fontSize: 18.0);
      List tests = List();

      Widget _buildSuggestions(BuildContext context) {
        initTests();
        return ListView.builder(
            itemCount: tests.length,
            padding: const EdgeInsets.all(16.0),
            itemBuilder: (context, i) {
              if (i.isOdd) return Divider();

              return _buildRow(tests[i]);
            });
      }

      void gotoTest(String title) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => TestList(title)));
      }

      Widget _buildRow(String pair) {
        return ListTile(
          onTap: () => gotoTest(pair),
          title: Text(
            pair,
            style: _biggerFont,
          ),
        );
      }

      void initTests() async {
        List t = List();
        String baseDir = await ExtStorage.getExternalStorageDirectory();
        String waDir = "$baseDir/mandarin";
        Directory dir = new Directory(waDir);
        dir.list().forEach((element) {
          t.add(element.path);
        });
        setState(() {
          tests.addAll(t);
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("请选择老师")),
          body: _buildSuggestions(context),
        );
      }
    }

Body:
Have you tried using the FutureBuilder widget ?

Check the code below:

Pass a snapshot to your buildSuggestion method

      Widget _buildSuggestions(BuildContext context, AsyncSnapShot snapshot) {
        initTests();
        return ListView.builder(
            itemCount: snapshot.data.length,
            padding: const EdgeInsets.all(16.0),
            itemBuilder: (context, i) {
              if (i.isOdd) return Divider();

              return _buildRow(snapshot.data[i]);
            });
      }

Change the function return type

 Future initTests() async {
        List t = List();
        String baseDir = await ExtStorage.getExternalStorageDirectory();
        String waDir = "$baseDir/mandarin";
        Directory dir = new Directory(waDir);
        dir.list().forEach((element) {
          t.add(element.path);
        });
        setState(() {
          tests.addAll(t);
        });
        return tests;
      }

Use a future builder widget in your body:

     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("请选择老师")),
          body: FutureBuilder(
            future: initTests(),
            builder: (context, snapshot){
              if (snapshot.hasData){
                return _buildSuggestions(context, snapshot);
              } else {
                return CircularProgressIndicator();
              }
            },
          );
        );
      }

It will show a Circle Progress Indicator until all the files have been read and then display them when done.


问:
Stacking numpy array A corresponding to array B
I have a numpy array (ndarray, each of shape (1, 10, 4)) of input features X, and a label array y corresponding to classes.

Now I want to create a new array of arrays by stacking together, all input features in X that correspond to class 0 in y, features that correspond to class 1 in y, etc... so that a new array of arrays is formed, with nested the arrays equal to the number classes.

As a minimal example, say I have:

```<code>X = np.random.randn(200, 1, 10, 4)
a = np.zeros(100, dtype=int)
b = np.ones(100, dtype=int)
y = np.hstack((a,b))
</code>```

So,

```<code>print(X.shape)
print(y.shape)
(200, 1, 10, 4)
(200,)
</code>```

New array then should then be like:

```<code>Final = [array(#all_features_of class_0), array(#all_features_of_class_1)...]
</code>```

My intention is to plot these features per class to understand their distribution.

If it may help, every single observation has 4 features, so the 4 in (1, 10, 4).

答:
did I understood you correct, is this what you want?</p>

```<code>class0, class1=[],[]
for i in range(len(y)):
if y[i]==0:
    class0.append(X[i])
else:
    class1.append(X[i])
Final = (np.array(class0) , np.array(class1))
</code>```

Body:
I have a numpy array (ndarray, each of shape (1, 10, 4)) of input features X, and a label array y corresponding to classes.

Now I want to create a new array of arrays by stacking together, all input features in X that correspond to class 0 in y, features that correspond to class 1 in y, etc... so that a new array of arrays is formed, with nested the arrays equal to the number classes.

As a minimal example, say I have:

X = np.random.randn(200, 1, 10, 4)
a = np.zeros(100, dtype=int)
b = np.ones(100, dtype=int)
y = np.hstack((a,b))

So,

print(X.shape)
print(y.shape)
(200, 1, 10, 4)
(200,)

New array then should then be like:

Final = [array(#all_features_of class_0), array(#all_features_of_class_1)...]

My intention is to plot these features per class to understand their distribution.

If it may help, every single observation has 4 features, so the 4 in (1, 10, 4).

Body:
did I understood you correct, is this what you want?

class0, class1=[],[]
for i in range(len(y)):
if y[i]==0:
    class0.append(X[i])
else:
    class1.append(X[i])
Final = (np.array(class0) , np.array(class1))


问:
Cannot run program "mvn" error=2, No such file or directory
I'm doing a build on my Ubuntu 14.04 LTS but I'm getting the following:

```<code>Started by user anonymous
Building in workspace /var/lib/jenkins/workspace/videovixx
 > /usr/bin/git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > /usr/bin/git config remote.origin.url https://bitbucket.org/mdennis10/videovixx.git #     timeout=10
Fetching upstream changes from https://bitbucket.org/mdennis10/videovixx.git
 > /usr/bin/git --version # timeout=10
using .gitcredentials to set credentials
 > /usr/bin/git config --local credential.helper store --    file=/tmp/git6236060328558794078.credentials # timeout=10
 > /usr/bin/git fetch --tags --progress https://bitbucket.org/mdennis10/videovixx.git   +refs/heads/*:refs/remotes/origin/*
 > /usr/bin/git config --local --remove-section credential # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision f5c53e95d33c1e15abd7519346c18ec6bc0c81d7      (refs/remotes/origin/master)
 > /usr/bin/git config core.sparsecheckout # timeout=10
 > /usr/bin/git checkout -f f5c53e95d33c1e15abd7519346c18ec6bc0c81d7
 > /usr/bin/git rev-list f5c53e95d33c1e15abd7519346c18ec6bc0c81d7 # timeout=10
[videovixx] $ mvn install package
FATAL: command execution failed
java.io.IOException: Cannot run program "mvn" (in directory    "/var/lib/jenkins/workspace/videovixx"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
    at hudson.Proc$LocalProc.<init>(Proc.java:244)
    at hudson.Proc$LocalProc.<init>(Proc.java:216)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:802)
    at hudson.Launcher$ProcStarter.start(Launcher.java:380)
    at hudson.Launcher$ProcStarter.join(Launcher.java:387)
    at hudson.tasks.Maven.perform(Maven.java:328)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:770)
    at hudson.model.Build$BuildExecution.build(Build.java:199)
    at hudson.model.Build$BuildExecution.doRun(Build.java:160)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:533)
    at hudson.model.Run.execute(Run.java:1745)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
    at java.lang.ProcessImpl.start(ProcessImpl.java:130)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
    ... 15 more
Build step 'Invoke top-level Maven targets' marked build as failure
Archiving artifacts
Recording test results
Finished: FAILURE
</code>```

I'm assuming that this caused by some linux security feature that stops the /var/lib/jenkins/workspace/videovixx from being created without the correct permissions
which I might not have. Is this the problem and how do I solve it?

答:
I had the same problem and i installed maven in Jenkins Server and issue was fixed.</p>

```<code>sudo yum install maven
</code>```

Body:
I'm doing a build on my Ubuntu 14.04 LTS but I'm getting the following:

Started by user anonymous
Building in workspace /var/lib/jenkins/workspace/videovixx
 > /usr/bin/git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > /usr/bin/git config remote.origin.url https://bitbucket.org/mdennis10/videovixx.git #     timeout=10
Fetching upstream changes from https://bitbucket.org/mdennis10/videovixx.git
 > /usr/bin/git --version # timeout=10
using .gitcredentials to set credentials
 > /usr/bin/git config --local credential.helper store --    file=/tmp/git6236060328558794078.credentials # timeout=10
 > /usr/bin/git fetch --tags --progress https://bitbucket.org/mdennis10/videovixx.git   +refs/heads/*:refs/remotes/origin/*
 > /usr/bin/git config --local --remove-section credential # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision f5c53e95d33c1e15abd7519346c18ec6bc0c81d7      (refs/remotes/origin/master)
 > /usr/bin/git config core.sparsecheckout # timeout=10
 > /usr/bin/git checkout -f f5c53e95d33c1e15abd7519346c18ec6bc0c81d7
 > /usr/bin/git rev-list f5c53e95d33c1e15abd7519346c18ec6bc0c81d7 # timeout=10
[videovixx] $ mvn install package
FATAL: command execution failed
java.io.IOException: Cannot run program "mvn" (in directory    "/var/lib/jenkins/workspace/videovixx"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
    at hudson.Proc$LocalProc.<init>(Proc.java:244)
    at hudson.Proc$LocalProc.<init>(Proc.java:216)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:802)
    at hudson.Launcher$ProcStarter.start(Launcher.java:380)
    at hudson.Launcher$ProcStarter.join(Launcher.java:387)
    at hudson.tasks.Maven.perform(Maven.java:328)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:770)
    at hudson.model.Build$BuildExecution.build(Build.java:199)
    at hudson.model.Build$BuildExecution.doRun(Build.java:160)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:533)
    at hudson.model.Run.execute(Run.java:1745)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:89)
    at hudson.model.Executor.run(Executor.java:240)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
    at java.lang.ProcessImpl.start(ProcessImpl.java:130)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
    ... 15 more
Build step 'Invoke top-level Maven targets' marked build as failure
Archiving artifacts
Recording test results
Finished: FAILURE

I'm assuming that this caused by some linux security feature that stops the /var/lib/jenkins/workspace/videovixx from being created without the correct permissions
which I might not have. Is this the problem and how do I solve it?

Body:
I had the same problem and i installed maven in Jenkins Server and issue was fixed.

sudo yum install maven


问:
SQL query to convert Date to another format
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

```<code>                  200901
                  200902
</code>```

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

答:
For MySQL, you would use the STR_TO_DATE function, see http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date

```<code>SELECT STR_TO_DATE(paid_month,'%Y%m');
</code>```

Sounds like the column contains some normal dates and some YYYYMM dates.  If the goal is to update the entire column, you can attempt to isolate the YYYYMM dates and update only those.  Something like:

```<code>UPDATE YourTable
SET paid_month = DATE_FORMAT(STR_TO_DATE(paid_month, '%Y%m'), '%m/%d/%Y')
WHERE LENGTH(paid_month) = 6
</code>```

Body:
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

                  200901
                  200902

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

Body:
For MySQL, you would use the STR_TO_DATE function, see http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date

SELECT STR_TO_DATE(paid_month,'%Y%m');

Sounds like the column contains some normal dates and some YYYYMM dates.  If the goal is to update the entire column, you can attempt to isolate the YYYYMM dates and update only those.  Something like:

UPDATE YourTable
SET paid_month = DATE_FORMAT(STR_TO_DATE(paid_month, '%Y%m'), '%m/%d/%Y')
WHERE LENGTH(paid_month) = 6


问:
mysqlclient installation error in AWS Elastic Beanstalk
I am deploying a django with mysql app on AWS Elastic Beanstalk, so mysqlclient library is needed. mysqlclient needs python3-devel and mysql-devel package to be installed, so I have the custom config file for it 01_packages.config:

```<code>packages:
  yum:
    python3-devel: []
    mysql-devel: []
</code>```

Deployment fails and the log file /var/log/cfn-init.log (mentioned in Beanstalk logs) shows the error:

```<code>2020-05-31 02:17:37,565 [INFO] -----------------------Starting build-----------------------
2020-05-31 02:17:37,572 [INFO] Running configSets: Infra-EmbeddedPreBuild
2020-05-31 02:17:37,575 [INFO] Running configSet Infra-EmbeddedPreBuild
2020-05-31 02:17:37,579 [INFO] Running config prebuild_0_doyouknow
2020-05-31 02:17:41,831 [ERROR] mysql-devel is not available to be installed
2020-05-31 02:17:41,831 [ERROR] Error encountered during build of prebuild_0_doyouknow: Yum does no
t have mysql-devel available for installation
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config
    CloudFormationCarpenter(config, self._auth_config).build(worklog)
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 229, in build
    changes['packages'][manager] = CloudFormationCarpenter._packageTools[manager]().apply(packages,
 self._auth_config)
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/rpm_tools.py", line 74, in apply
    raise ToolError("Yum does not have %s available for installation" % pkg_spec)
ToolError: Yum does not have mysql-devel available for installation
2020-05-31 02:17:41,834 [ERROR] -----------------------BUILD FAILED!------------------------
</code>```

However, I tried to install it manually on my Ec2 instance through yum install mysql-devel and it is installed successfully.

My python version is 3.7 and my requirements.txt file content is:

```<code>asgiref==3.2.7
Django==3.0.5
django-cors-headers==3.2.1
django-dotenv==1.4.2
django-social-share==1.4.0
mysqlclient==1.4.6
numpy==1.18.4
pandas==1.0.3
Pillow==7.1.1
python-dateutil==2.8.1
pytz==2019.3
six==1.14.0
sqlparse==0.3.1
xlrd==1.2.0
</code>```

答:
Solved! I have replaced mysql-devel with mariadb-devel and it worked successfully, then I was able to install mysqlcient library.

My new 01_packages.config:

```<code>packages:
  yum:
    python3-devel: []
    mariadb-devel: []
</code>```

I don't know the root cause of it, but I did so as I noticed that the manual installation of mysql-devel through yum install mysql-devel is actually installing mariadb-devel !

Here is my ec2 instance release details. Maybe it is because of the new Amazon Linux Release 2.

```<code>$ cat /etc/*-release*
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"
Amazon Linux release 2 (Karoo)
cpe:2.3:o:amazon:amazon_linux:2
</code>```

Body:
I am deploying a django with mysql app on AWS Elastic Beanstalk, so mysqlclient library is needed. mysqlclient needs python3-devel and mysql-devel package to be installed, so I have the custom config file for it 01_packages.config:

packages:
  yum:
    python3-devel: []
    mysql-devel: []

Deployment fails and the log file /var/log/cfn-init.log (mentioned in Beanstalk logs) shows the error:

2020-05-31 02:17:37,565 [INFO] -----------------------Starting build-----------------------
2020-05-31 02:17:37,572 [INFO] Running configSets: Infra-EmbeddedPreBuild
2020-05-31 02:17:37,575 [INFO] Running configSet Infra-EmbeddedPreBuild
2020-05-31 02:17:37,579 [INFO] Running config prebuild_0_doyouknow
2020-05-31 02:17:41,831 [ERROR] mysql-devel is not available to be installed
2020-05-31 02:17:41,831 [ERROR] Error encountered during build of prebuild_0_doyouknow: Yum does no
t have mysql-devel available for installation
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config
    CloudFormationCarpenter(config, self._auth_config).build(worklog)
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 229, in build
    changes['packages'][manager] = CloudFormationCarpenter._packageTools[manager]().apply(packages,
 self._auth_config)
  File "/usr/lib/python2.7/site-packages/cfnbootstrap/rpm_tools.py", line 74, in apply
    raise ToolError("Yum does not have %s available for installation" % pkg_spec)
ToolError: Yum does not have mysql-devel available for installation
2020-05-31 02:17:41,834 [ERROR] -----------------------BUILD FAILED!------------------------

However, I tried to install it manually on my Ec2 instance through yum install mysql-devel and it is installed successfully.

My python version is 3.7 and my requirements.txt file content is:

asgiref==3.2.7
Django==3.0.5
django-cors-headers==3.2.1
django-dotenv==1.4.2
django-social-share==1.4.0
mysqlclient==1.4.6
numpy==1.18.4
pandas==1.0.3
Pillow==7.1.1
python-dateutil==2.8.1
pytz==2019.3
six==1.14.0
sqlparse==0.3.1
xlrd==1.2.0

Body:
Solved! I have replaced mysql-devel with mariadb-devel and it worked successfully, then I was able to install mysqlcient library.

My new 01_packages.config:

packages:
  yum:
    python3-devel: []
    mariadb-devel: []

I don't know the root cause of it, but I did so as I noticed that the manual installation of mysql-devel through yum install mysql-devel is actually installing mariadb-devel !

Here is my ec2 instance release details. Maybe it is because of the new Amazon Linux Release 2.

$ cat /etc/*-release*
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"
Amazon Linux release 2 (Karoo)
cpe:2.3:o:amazon:amazon_linux:2


问:
Android emulator not able to access the internet
I know that similar questions have been asked before, but my problem is new only after installing Android Studio 2.3, the latest version in March 2017.  I have several years experience developing Android applications, and I have never encountered this problem before.  After upgrading to version 2.3 of Android Studio, my emulator is no longer able to access the internet.  I even uninstalled/reinstalled Android Studio 2.3 from scratch and created a new emulator, and I am still getting the same error.  This is not an app problem.  I can't even access the internet from Chrome, and I wasn't having this problem last week.  The message that I get says that the server DNS address could not be found -- DNS_PROBE_FINISHED_BAD_CONFIG.  The only thing that has changed on my computer in the last week is the new version of Android plus possibly updates to Windows 10.  And yes, my computer has access to the internet.  Below is an image of my emulator when I try to use Chrome to search for "Google".

答:
I know this is old. But it helped me a bit. I encountered the same problem in Xamarin.Forms application. My emulator was unable a connect to a public api.

I fixed the problem by starting the emulator with factory defaults in Android Device manager.


问:
android recyclerview - TextView is not expanding properly with setmaxlines method
I am new to android development. For my learning purpose, I am developing an android application to list the fibonacci numbers in a recycler view. The list gets appended with new numbers as the user scrolls down the recycler view.

The image shows the app displaying the index and respective fibonacci number for the index in the recycler view

This is the layout xml of single item in recycler view.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>
</code>```

Excerpt from the adaptor class,

```<code>public class ViewHolder extends RecyclerView.ViewHolder {
        final TextView index;
        final TextView value;

        ViewHolder(View itemView) {
            super(itemView);
            index = itemView.findViewById(R.id.info_index);
            value = itemView.findViewById(R.id.info_value);
        }
    }

    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final TextView value = holder.value;
        final TextView index = holder.index;
        value.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                if (value.getMaxLines() == 1000) {
                    value.setMaxLines(1);
                    notifyItemChanged(position);
                } else {
                    value.setMaxLines(1000);
                    notifyItemChanged(position);
                }
            }
        });
        Log.d(TAG, "position-value:" + String.valueOf(position));

        holder.index.setBackgroundColor(Color.WHITE);
        holder.index.setText(String.valueOf(position + 1));
        holder.value.setBackgroundColor(Color.WHITE);
        holder.value.setText(mData.get(position));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            holder.index.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
            holder.value.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }

    }
</code>```

When I click on the value textview, the textview does not expand on the first click, instead I have to press two times to make it expand. The first time only the flickering happens. I have tried disabling the animator for recyclerview, tried re using the same view in the recycler view, but nothings helps.

My requirement is to expand fibonacci-value textview on click. By default it should be 1 line and when clicked it should show the whole content with multiple lines (as many as required).

currently this happens with two clicks. first time flickering and second time expands.

I believe this is a bug in android code. But just want to confirm here for any solutions that I might have missed.

答:
I was able to repeat your issue on my device, the issue you have is that your LinearLayout is consuming your click before it reaches your textview.

Include:

```<code>android:clickable="false"
android:focusableInTouchMode="false"
android:focusable="false"
</code>```

Within your LinearLayout like so:

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusableInTouchMode="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>
</code>```

Also include:

```<code>android:nestedScrollingEnabled="false"
</code>```

Within your RecyclerView

Body:
I am new to android development. For my learning purpose, I am developing an android application to list the fibonacci numbers in a recycler view. The list gets appended with new numbers as the user scrolls down the recycler view.

The image shows the app displaying the index and respective fibonacci number for the index in the recycler view

This is the layout xml of single item in recycler view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>

Excerpt from the adaptor class,

public class ViewHolder extends RecyclerView.ViewHolder {
        final TextView index;
        final TextView value;

        ViewHolder(View itemView) {
            super(itemView);
            index = itemView.findViewById(R.id.info_index);
            value = itemView.findViewById(R.id.info_value);
        }
    }

    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final TextView value = holder.value;
        final TextView index = holder.index;
        value.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                if (value.getMaxLines() == 1000) {
                    value.setMaxLines(1);
                    notifyItemChanged(position);
                } else {
                    value.setMaxLines(1000);
                    notifyItemChanged(position);
                }
            }
        });
        Log.d(TAG, "position-value:" + String.valueOf(position));

        holder.index.setBackgroundColor(Color.WHITE);
        holder.index.setText(String.valueOf(position + 1));
        holder.value.setBackgroundColor(Color.WHITE);
        holder.value.setText(mData.get(position));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            holder.index.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
            holder.value.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }

    }

When I click on the value textview, the textview does not expand on the first click, instead I have to press two times to make it expand. The first time only the flickering happens. I have tried disabling the animator for recyclerview, tried re using the same view in the recycler view, but nothings helps.

My requirement is to expand fibonacci-value textview on click. By default it should be 1 line and when clicked it should show the whole content with multiple lines (as many as required).

currently this happens with two clicks. first time flickering and second time expands.

I believe this is a bug in android code. But just want to confirm here for any solutions that I might have missed.

Body:
I was able to repeat your issue on my device, the issue you have is that your LinearLayout is consuming your click before it reaches your textview.

Include:

android:clickable="false"
android:focusableInTouchMode="false"
android:focusable="false"

Within your LinearLayout like so:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusableInTouchMode="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>

Also include:

android:nestedScrollingEnabled="false"

Within your RecyclerView


问:
How to pass 2 javascript events in one click?
I want to pass 2 javascript events in one click, I put 2 of them into href and onclick. But when I click, it always executes the onclick action. Click again or a third time, the href action gets executed. I do not know how it was like this.

How do I to solve it?

If I combine 2 javascript events in one part(href or onclick). is it could run well? how to?

thanks.

```<code><a href="javascript:function1('value1')" onclick="javascript:function2('value2')">
</code>```

答:
Try this:

```<code><a href="#" onclick="function1('value1'); function2('value2'); return false;">
</code>```

Note that you do not need to put "javascript:" in the onclick event. And it is generally better to use onclick rather than href to execute javascript.

You could even change href="#" to link to a page saying you need javascript enabled. return false; will cancel the link if javascript is working.

Body:
Try this:

<a href="#" onclick="function1('value1'); function2('value2'); return false;">

Note that you do not need to put "javascript:" in the onclick event. And it is generally better to use onclick rather than href to execute javascript.

You could even change href="#" to link to a page saying you need javascript enabled. return false; will cancel the link if javascript is working.


问:
TypeError: Cannot read property 'map' of undefined : object having list of objects
I'm trying to map data using below json format.
An object having list of objects.

'''{"pki_user_id":1234,"vc_username":null,"vc_password":null,"vc_name":"Muhammad","vc_email":"Muhammad.Bilal@gmail.com","b_isreset":false,"b_timeout":0,"_RoleDto":[{"pki_role_id":30019,"vc_rolename":"SuperUser","vc_roledesc":"Super User","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":20015,"vc_rolename":"COMADM","vc_roledesc":"Competency Admin","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":2,"vc_rolename":"IT","vc_roledesc":"IT","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":3,"vc_rolename":"TAA","vc_roledesc":"Time Attendance Administrator","vc_type":null,"i_group":0,"_MenuDto":null}]}'''

This is how I'm retrieving data:

```<code>        {props.LoginDto.vc_email}

        {props.LoginDto._RoleDto.map((record,i) => (

          <div key = {i}> {record.pki_role_id}</div>
        ))}

      </div>
</code>```

Every time I'm getting this error.
I'using react redux to receive props data.

答:
Add a null check like this:</p>

```<code>{props.LoginDto && props.LoginDto.vc_email}

        {props.LoginDto && props.LoginDto._RoleDto && !!props.LoginDto._RoleDto.length && props.LoginDto._RoleDto.map((record,i) => (

          <div key = {i}> {record.pki_role_id}</div>
        ))}

      </div>
</code>```

Body:
I'm trying to map data using below json format.
An object having list of objects.

'''{"pki_user_id":1234,"vc_username":null,"vc_password":null,"vc_name":"Muhammad","vc_email":"Muhammad.Bilal@gmail.com","b_isreset":false,"b_timeout":0,"_RoleDto":[{"pki_role_id":30019,"vc_rolename":"SuperUser","vc_roledesc":"Super User","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":20015,"vc_rolename":"COMADM","vc_roledesc":"Competency Admin","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":2,"vc_rolename":"IT","vc_roledesc":"IT","vc_type":null,"i_group":0,"_MenuDto":null},{"pki_role_id":3,"vc_rolename":"TAA","vc_roledesc":"Time Attendance Administrator","vc_type":null,"i_group":0,"_MenuDto":null}]}'''

This is how I'm retrieving data:

        {props.LoginDto.vc_email}

        {props.LoginDto._RoleDto.map((record,i) => (

 {record.pki_role_id}

        ))}

Every time I'm getting this error.
I'using react redux to receive props data.

Body:
Add a null check like this:

{props.LoginDto && props.LoginDto.vc_email}

        {props.LoginDto && props.LoginDto._RoleDto && !!props.LoginDto._RoleDto.length && props.LoginDto._RoleDto.map((record,i) => (

          <div key = {i}> {record.pki_role_id}</div>
        ))}

      </div>


问:
Javascript arguments gestion
I have a command created in JS for discord such as =
*announcement channelID "message to send"
which is defined as follows:

```<code>const channelID = args [0];
const messageaenvoyer = message.content.substring (`* ad $ {channelID}` .length + 1);
</code>```

It's quite easy knowing that the channelID has a fixed length.

Now, I would like to add a title:

```<code>*announcement channelID title message to send
</code>```

How to define each argument knowing that title and message to send have variable sizes and are subject to several words

Thank you

答:
Function or Api that is used to create and send the message, should follow a protocol, receiver function just need to know what protocol is used to transfer data.These are some simple protocols.

you can use delimiter like this

```<code>//`channelId#title#message`
var delimiter = "#"
var msg = channelId + delimiter  + title + delimiter + message
</code>```

you can use fixed length

```<code>var titleMaxLength =22;
var messageMaxLength = 200;
var data = channelId + title.padEnd(titleMaxLength ,' ')
   + message.padEnd(messageMaxLength ,' ')
</code>```

the best way is using Json

```<code>var msg = JSON.stringify({
   channelId: channelId,
   title:title,
   message:message })
</code>```

you can also add metadata to your message

```<code>var msg = channelId + title + message + '.' + message.length
</code>```

Example for first one :

```<code>var delimiter = '#'

function sender(channelId, title, message) {
  var msg = channelId + delimiter + title + delimiter + message
  return msg
}

function receiver(msg) {
  var res = msg.split(delimiter)
  console.log(res)
}

var _msg = sender('123456', 'test', 'This is a test')
console.log(_msg)
receiver(_msg)
</code>```

Title: Javascript arguments gestion

Body:
I have a command created in JS for discord such as =
*announcement channelID "message to send"
which is defined as follows:

const channelID = args [0];
const messageaenvoyer = message.content.substring (`* ad $ {channelID}` .length + 1);

It's quite easy knowing that the channelID has a fixed length.

Now, I would like to add a title:

*announcement channelID title message to send

How to define each argument knowing that title and message to send have variable sizes and are subject to several words

Thank you

Body:
Function or Api that is used to create and send the message, should follow a protocol, receiver function just need to know what protocol is used to transfer data.These are some simple protocols.

you can use delimiter like this

//`channelId#title#message`
var delimiter = "#"
var msg = channelId + delimiter  + title + delimiter + message

you can use fixed length

var titleMaxLength =22;
var messageMaxLength = 200;
var data = channelId + title.padEnd(titleMaxLength ,' ')
   + message.padEnd(messageMaxLength ,' ')

the best way is using Json

var msg = JSON.stringify({
   channelId: channelId,
   title:title,
   message:message })

you can also add metadata to your message

var msg = channelId + title + message + '.' + message.length

Example for first one :

var delimiter = '#'

function sender(channelId, title, message) {
  var msg = channelId + delimiter + title + delimiter + message
  return msg
}

function receiver(msg) {
  var res = msg.split(delimiter)
  console.log(res)
}

var _msg = sender('123456', 'test', 'This is a test')
console.log(_msg)
receiver(_msg)


问:
How can I get the console output in Angular webpage?
I have a Django project which is using Angular as frontend. I have a button which on clicking is scanning the tables in the database. I have some print statements views.py file which is printing the scanned results constantly in the IDE console. I want that output in the webpage. I want that live printing of the console output in the frontend. Can any one know how i can achieve this?</p>

答:
You can achieve this by using server sent events. python can push these console logs to the frontend. Not a expert of python so giving a link below to how to send server side events from python to frontend

https://medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56

In frontend you can listen to url exposed and as soon as server will push any message on this stream frontend can receive it and push it into component's array and can display over ui.

for frontend code, i am giving a minimal example below :-

```<code>import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
  providedIn: "root"
})
export class SseService {
  constructor(private _zone: NgZone) {}
  getServerSentEvent(url: string): Observable<any> {
    return Observable.create(observer => {
      const eventSource = this.getEventSource(url);
      eventSource.onmessage = event => {
        this._zone.run(() => {
          observer.next(event);
        });
      };
      eventSource.onerror = error => {
        this._zone.run(() => {
          observer.error(error);
        });
      };
    });
  }
  private getEventSource(url: string): EventSource {
    return new EventSource(url);
  }
}
</code>```

you can susbcribe to getServerSentEvent in above method and can continuously receive new messages, which is in your case your console logs.

Body:
You can achieve this by using server sent events. python can push these console logs to the frontend. Not a expert of python so giving a link below to how to send server side events from python to frontend

https://medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56

In frontend you can listen to url exposed and as soon as server will push any message on this stream frontend can receive it and push it into component's array and can display over ui.

for frontend code, i am giving a minimal example below :-

import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
  providedIn: "root"
})
export class SseService {
  constructor(private _zone: NgZone) {}
  getServerSentEvent(url: string): Observable<any> {
    return Observable.create(observer => {
      const eventSource = this.getEventSource(url);
      eventSource.onmessage = event => {
        this._zone.run(() => {
          observer.next(event);
        });
      };
      eventSource.onerror = error => {
        this._zone.run(() => {
          observer.error(error);
        });
      };
    });
  }
  private getEventSource(url: string): EventSource {
    return new EventSource(url);
  }
}

you can susbcribe to getServerSentEvent in above method and can continuously receive new messages, which is in your case your console logs.


问:
Pyspark: How do I extract lowest values per key?
My dataframe df:

```<code>C1    C2    C3
A     1     5
A     1     4
A     2     6
B     2     9
B     5     5

</code>```

I would like to extract the lowest value from C2 per distinct value in C1 as a new dataframe. So the output would be

```<code>C1    C2
A     1
B     2
</code>```

I think I'd have to use df.groupBy("C1"), but I'm not sure how to apply it correctly.

答:
You are correct that the correct function is df.groupBy("C1"). One can also apply the min function to that, simplifying the solution to one line of:

```<code>df.groupby(['C1']).min()
</code>```

which will return the output. Hope this helps!

Body:
My dataframe df:

C1    C2    C3
A     1     5
A     1     4
A     2     6
B     2     9
B     5     5

I would like to extract the lowest value from C2 per distinct value in C1 as a new dataframe. So the output would be

C1    C2
A     1
B     2

I think I'd have to use df.groupBy("C1"), but I'm not sure how to apply it correctly.

Body:
You are correct that the correct function is df.groupBy("C1"). One can also apply the min function to that, simplifying the solution to one line of:

df.groupby(['C1']).min()

which will return the output. Hope this helps!


问:
Should GC.SuppressFinalize be called on objects that do not have a finalizer?
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not. </p>

<p>Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined? </p>

答:
All objects have a finalizer method, even if you have not implemented one by using a c# destructor (which is not actually guaranteed to be called by the GC). It's just good practice to supress the call if you have implemented IDisposable because that means you have decided to perform the finalization explictly.

devx article

Body:
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.

Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?

LastEditorDisplayName: Mitch Wheat


问:
Entity Framework 4.0, PoCo & Navigation Properties for Lookup Tables
I have the following Models

```<code>DeltaDirectionType,
int Id
string Name

Delta,
int Id
string Name
DeltaDirectionType DeltaDirectionType
Double Value

Trade
int Id
DateTime BusinessDate
IList<Delta> deltas
</code>```

So DeltaDirectionType is a lookup table, Trade holds a collection of Deltas

In the database it is implemented as follows

```<code>DeltaDirectionTypes
Id int
Name varchar(max)

Deltas
Id int
Name varchar(max)
DeltaDirectionType_Id int
Trade_Id int
Value float

Trades
Id int
BusinessDate DateTime
Delta_Id int
</code>```

When I generate the model from code for the Edmx file, and (un check the foreign keys) as my model does not have properties for these. I am having problem with the navigation properties. Something like this in nHibernate would be a simple one to many mapping for the DeltaDirectionType and Delta and a many to many for Delta and Trades however, how do I firstly get it to recognise that DeltaDirectionType is a lookup and secondly get the Icollection to work for me.

I am struggling with this, Entity Framework does not make it easy for you. I have tried the usual, delete the navigation property that EF puts in for you on one side, but then you get some mapping fragments errors, properties not mapped etc.

Please help or point in the right direction.

Lookup tables are real life problems, not sure why it is so hard withing EF to implement.

Any help much appreciated

Thanks

答:
You must either create foreign keys or navigation properties in the model to navigate the relationship.

Navigation properties can be defined as one-way, ie from the deltas table to the look-up table. A one-way navigation like this would add the appropriate property to the delta's object but not to the looup table

Body:
I have the following Models

DeltaDirectionType,
int Id
string Name

Delta,
int Id
string Name
DeltaDirectionType DeltaDirectionType
Double Value

Trade
int Id
DateTime BusinessDate
IList<Delta> deltas

So DeltaDirectionType is a lookup table, Trade holds a collection of Deltas

In the database it is implemented as follows

DeltaDirectionTypes
Id int
Name varchar(max)

Deltas
Id int
Name varchar(max)
DeltaDirectionType_Id int
Trade_Id int
Value float

Trades
Id int
BusinessDate DateTime
Delta_Id int

When I generate the model from code for the Edmx file, and (un check the foreign keys) as my model does not have properties for these. I am having problem with the navigation properties. Something like this in nHibernate would be a simple one to many mapping for the DeltaDirectionType and Delta and a many to many for Delta and Trades however, how do I firstly get it to recognise that DeltaDirectionType is a lookup and secondly get the Icollection to work for me.

I am struggling with this, Entity Framework does not make it easy for you. I have tried the usual, delete the navigation property that EF puts in for you on one side, but then you get some mapping fragments errors, properties not mapped etc.

Please help or point in the right direction.

Lookup tables are real life problems, not sure why it is so hard withing EF to implement.

Any help much appreciated

Thanks


问:
Linux bash for do loop dynamic parameter substitution
I want to use a bash command that I assume would be something along lines of

```<code>for f in *.xml; do mv $f StaticTextPrefix + ./GetXmlSpecificNodeValue $f + StaticTextSuffix; done
</code>```

So the program GetXmlSpecificNodeValue returns a unique value from the XML found which will be guaranteed to be unique for each xml file.

Is this possible what does the structure of the command look like?

答:
thankyou @KamilCuk
had to prefix the GetXmlSpecificNodeValue with ./ but otherwise it works</p>

```<code>for f in *.xml; do mv $f "StaticTextPrefix/$(./GetXmlSpecificNodeValue "$f")StaticTextSuffix"; done
</code>```

Body:
I want to use a bash command that I assume would be something along lines of

for f in *.xml; do mv $f StaticTextPrefix + ./GetXmlSpecificNodeValue $f + StaticTextSuffix; done

So the program GetXmlSpecificNodeValue returns a unique value from the XML found which will be guaranteed to be unique for each xml file.

Is this possible what does the structure of the command look like?

Body:
thankyou @KamilCuk
had to prefix the GetXmlSpecificNodeValue with ./ but otherwise it works

for f in *.xml; do mv $f "StaticTextPrefix/$(./GetXmlSpecificNodeValue "$f")StaticTextSuffix"; done


问:
Form $ref is undefined inside of method?
I have a very simple Vuetify form with ref="form". When I press submit, I want to validate and programmatically submit the form, however for some reason this.$refs.form returns undefined.

I'm almost hoping it's something dumb like a typo because this is so seemingly simple!

<template>
  <v-form
    v-if="!submitted"
    ref="form"
    v-model="valid"
    name="contactForm"
    data-netlify="true"
    data-netlify-honeypot="bot-field"
    method="POST"
    @submit.prevent="submit">
    <input
      type="hidden"
      name="form-name"
      value="contactForm">

    ...input fields

    <v-row justify="center">
      <v-col
        sm="12"
        class="text-center">
        <v-btn
          :disabled="!valid || sendingForm"
          color="accent"
          depressed
          :ripple="false"
          x-large
          type="submit">
          {{ sendingForm ? 'Loading...' : 'Submit' }}
        </v-btn>
      </v-col>
    </v-row>

      Don't fill this out:
      <input
        type="text"
        name="bot-field">

  </v-form>
</template>

```

I have tried removing the v-if on the form, removing the type="submit/adding @click="submit on the button, removing @submit.prevent="submit from the form... nothing seems to be working! Has anybody run into something like this? Thanks!

答:
Here's what worked for me</p>

```<code><v-form
  ref="form"
  v-model="valid"
  name="contactform1"
  action="/contact"
  method="post"
  data-netlify="true"
  netlify-honeypot="bot-field"
>
  <input type="hidden" name="form-name" value="contactform1" />
  <v-row class="spacing6">
    <v-col cols="12" sm="6" class="pa-6">
      <v-text-field
        v-model="name"
        :rules="nameRules"
        :label="$t('common.form_name')"
        class="input"
        name="name"
        required
      />
    </v-col>
    <v-col cols="12" sm="6" class="pa-6">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        :label="$t('common.form_email')"
        class="input"
        name="email"
        required
      />
    </v-col>
  </v-row>
  <div class="btn-area">
    <div class="form-control-label">
      <v-checkbox
        v-model="checkbox"
        color="primary"
        :rules="[v => !!v || 'You must agree to continue!']"
        :label="$t('common.form_terms')"
        required
      />
      <a href="#">{{ $t('common.form_privacy') }}</a>
    </div>
    <v-btn
      color="primary"
      outlined
      @click="validate"
      large
      type="submit"
      value="Send message"
    >
      {{ $t('common.form_send') }}
      <v-icon class="right-icon">mdi-send</v-icon>
    </v-btn>
  </div>
</v-form>
</code>```

Body:
I have a very simple Vuetify form with ref="form". When I press submit, I want to validate and programmatically submit the form, however for some reason this.$refs.form returns undefined.

I'm almost hoping it's something dumb like a typo because this is so seemingly simple!

<template>
  <v-form
    v-if="!submitted"
    ref="form"
    v-model="valid"
    name="contactForm"
    data-netlify="true"
    data-netlify-honeypot="bot-field"
    method="POST"
    @submit.prevent="submit">
    <input
      type="hidden"
      name="form-name"
      value="contactForm">

    ...input fields

    <v-row justify="center">
      <v-col
        sm="12"
        class="text-center">
        <v-btn
          :disabled="!valid || sendingForm"
          color="accent"
          depressed
          :ripple="false"
          x-large
          type="submit">
          {{ sendingForm ? 'Loading...' : 'Submit' }}
        </v-btn>
      </v-col>
    </v-row>

      Don't fill this out:
      <input
        type="text"
        name="bot-field">

  </v-form>
</template>

I have tried removing the v-if on the form, removing the type="submit/adding @click="submit on the button, removing @submit.prevent="submit from the form... nothing seems to be working! Has anybody run into something like this? Thanks!

Body:
Here's what worked for me

<v-form
  ref="form"
  v-model="valid"
  name="contactform1"
  action="/contact"
  method="post"
  data-netlify="true"
  netlify-honeypot="bot-field"
>
  <input type="hidden" name="form-name" value="contactform1" />
  <v-row class="spacing6">
    <v-col cols="12" sm="6" class="pa-6">
      <v-text-field
        v-model="name"
        :rules="nameRules"
        :label="$t('common.form_name')"
        class="input"
        name="name"
        required
      />
    </v-col>
    <v-col cols="12" sm="6" class="pa-6">
      <v-text-field
        v-model="email"
        :rules="emailRules"
        :label="$t('common.form_email')"
        class="input"
        name="email"
        required
      />
    </v-col>
  </v-row>
  <div class="btn-area">
    <div class="form-control-label">
      <v-checkbox
        v-model="checkbox"
        color="primary"
        :rules="[v => !!v || 'You must agree to continue!']"
        :label="$t('common.form_terms')"
        required
      />
      <a href="#">{{ $t('common.form_privacy') }}</a>
    </div>
    <v-btn
      color="primary"
      outlined
      @click="validate"
      large
      type="submit"
      value="Send message"
    >
      {{ $t('common.form_send') }}
      <v-icon class="right-icon">mdi-send</v-icon>
    </v-btn>
  </div>
</v-form>