问:
Java sending files through sockets
I want to send files as  well as some other information through sockets. I am using the following code

```<code> public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
    //after receiving file send ack
    System.out.println("waiting ");
 // int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray  = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   System.out.println(bytesRead);
   if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}
</code>```

After receiving the file, I have to receive some other strings. But when I try to read the input stream, I am getting the contents of the file. How to flush the contents of the file from the inputstream.

```<code>BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(
                webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
    while(true)
    {
        msg = inFromServer.readLine(); //here i receive the contents of the file again
     System.out.println(msg);
    }
</code>```

答:
Pass the socket's inputstream to the receivefile-method, instead of the socket itself:

```<code>InputStream is = webServerSocket.getInputStream();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));

receiveFile(webServerSocket,filesize,filename);
</code>```

The problem lies, I believe, in the fact that you have two inputstreams from the same socket made at the same point in time (before any data has actually been read). They point to the same stream but reading from one does not move the other as well, thus after reading from inputstreamBA that one is marked in position 15 (for example) while inpustream A is still in poisition 0, at the beginning of the stream.

(EDIT:)
Ofcourse, you have to use the inputstream in the receiveFile method instead of getting one from the socket. Another solution would be to get the inputstream from the socket after the call to receive file, as in

```<code>receiveFile(webServerSocket,filesize,filename);

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(webServerSocket.getInputStream()));
</code>```

Title: Java sending files through sockets

Body:
I want to send files as  well as some other information through sockets. I am using the following code

 public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
    //after receiving file send ack
    System.out.println("waiting ");
 // int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray  = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   System.out.println(bytesRead);
   if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}

After receiving the file, I have to receive some other strings. But when I try to read the input stream, I am getting the contents of the file. How to flush the contents of the file from the inputstream.

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(
                webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
    while(true)
    {
        msg = inFromServer.readLine(); //here i receive the contents of the file again
     System.out.println(msg);
    }

Body:
Pass the socket's inputstream to the receivefile-method, instead of the socket itself:

InputStream is = webServerSocket.getInputStream();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));

receiveFile(webServerSocket,filesize,filename);

The problem lies, I believe, in the fact that you have two inputstreams from the same socket made at the same point in time (before any data has actually been read). They point to the same stream but reading from one does not move the other as well, thus after reading from inputstreamBA that one is marked in position 15 (for example) while inpustream A is still in poisition 0, at the beginning of the stream.

(EDIT:)
Ofcourse, you have to use the inputstream in the receiveFile method instead of getting one from the socket. Another solution would be to get the inputstream from the socket after the call to receive file, as in

receiveFile(webServerSocket,filesize,filename);

BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(webServerSocket.getInputStream()));


来源: stackexchange

问:
kubernetes: precedence of environmental variables
Assuming a pod has an environmental variable set both in its spec, as e.g. below

```<code>spec:
  containers:
  - name: env-print-demo
    image: bash
    env:
    - name: FOO
      value: "BAR"
</code>```

as also injected to it via a ConfigMap (but with a different value) which is the one that will be taken into account?

答:
When a key exists in multiple sources, the value associated with the last source will take precedence.

Override env values defined in container spec

ContentLicense: CC BY-SA 4.0

Body:
Assuming a pod has an environmental variable set both in its spec, as e.g. below

spec:
  containers:
  - name: env-print-demo
    image: bash
    env:
    - name: FOO
      value: "BAR"

as also injected to it via a ConfigMap (but with a different value) which is the one that will be taken into account?


问:
MaterlizeCSS: Cannot append to Select option
I need to append  to  tag based on the onchange function. It was appended, but can't able to view while click the dropdown.

$(document).ready(function(){
     $('select').formSelect();
});

a=['16MA401','16ME401','16ME402','16ME403','16ME404','16ME405','16EEG02','16EEG03']
b=['16ME601','16ME602','16ME603','16ME604','16MEE07','16ME605','16ME606','16ME607']
$('#class').on('change', function(){
    $('#sub').html('');
    c=document.getElementById('class').value;
    console.log(c)
    if (c=='2a' || c=='2b') {
        for (var i = 0; i < a.length; i++) {
          $('#sub').append('<option value='+a[i]+'>'+a[i]+'</option>');}
        }
    else{
        for (var i = 0; i < a.length; i++) {
          $('#sub').append('<option value='+b[i]+'>'+b[i]+'</option>');}
        }
    }
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"> </script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.js"></script>
</head>
<body>
    <form action="" method="POST">
        <div class="row ">
            <div class="input-field col s6">
                Class
                <select required id="class" name="clas">
                <option selected disabled>Select class</option>
                <option value="2a">2a</option>
                <option value="2b">2b</option>
                <option value="3a">3a</option>
                <option value="3b">3b</option>
                </select>
            </div>
            <div class="input-field col s6">
                Subject
                <select required id="sub" name="sub">
                <option selected disabled>Select class</option>
                </select>
            </div>
            <div class="input-field col s2 offset-s5">
                <input type="submit" class="btn" name="btn" value="Submit">
            </div>
        </div>
    </form>
</body></code>```

After select some options in the first dropdown, the second dropdown innerhtml was changing based on the first option.

In console, i get this:

$(sub).html();

```<code>'<option value=\"16ME601\">16ME601</option><option value=\"16ME602\">16ME602</option><option value=\"16ME603\">16ME603</option><option value=\"16ME604\">16ME604</option><option value=\"16MEE07\">16MEE07</option><option value=\"16ME605\">16ME605</option><option value=\"16ME606\">16ME606</option><option value=\"16ME607\">16ME607</option>'
</code>```

答: Instead of .append() give .formSelect().append() and finally add $('select').formSelect();

Body:
I need to append  to  tag based on the onchange function. It was appended, but can't able to view while click the dropdown.

$(document).ready(function(){
     $('select').formSelect();
});

a=['16MA401','16ME401','16ME402','16ME403','16ME404','16ME405','16EEG02','16EEG03']
b=['16ME601','16ME602','16ME603','16ME604','16MEE07','16ME605','16ME606','16ME607']
$('#class').on('change', function(){
    $('#sub').html('');
    c=document.getElementById('class').value;
    console.log(c)
    if (c=='2a' || c=='2b') {
        for (var i = 0; i < a.length; i++) {
          $('#sub').append('<option value='+a[i]+'>'+a[i]+'</option>');}
        }
    else{
        for (var i = 0; i < a.length; i++) {
          $('#sub').append('<option value='+b[i]+'>'+b[i]+'</option>');}
        }
    }
  );

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css">

    <form action="" method="POST">

                Class
                <select required id="class" name="clas">
                <option selected disabled>Select class</option>
                <option value="2a">2a</option>
                <option value="2b">2b</option>
                <option value="3a">3a</option>
                <option value="3b">3b</option>
                </select>

                Subject
                <select required id="sub" name="sub">
                <option selected disabled>Select class</option>
                </select>

                <input type="submit" class="btn" name="btn" value="Submit">

    </form>

After select some options in the first dropdown, the second dropdown innerhtml was changing based on the first option.

In console, i get this:

$(sub).html();

'<option value=\"16ME601\">16ME601</option><option value=\"16ME602\">16ME602</option><option value=\"16ME603\">16ME603</option><option value=\"16ME604\">16ME604</option><option value=\"16MEE07\">16MEE07</option><option value=\"16ME605\">16ME605</option><option value=\"16ME606\">16ME606</option><option value=\"16ME607\">16ME607</option>'


问:
Inheritance in JavaScript
I have a class Person like this:

```<code> class Person {
    constructor(name, age, gender, interests) {
        Object.assign(this, {name, age, gender, interests});
    }
}
</code>```

And I can make sub-class like this:

```<code>class Teacher extends Person {
    constructor(name, age, gender, interests, subject, grade) {
        super(name, age, gender, interests);
        Object.assign(this, {subject, grade});
    }
}
</code>```

But what if I want to make sub-class but I don't want to inherit all the properties from the Person class. For example I don't want to inherit the interests property. Do I just exclude it like this:

```<code>class Student extends Person {
    constructor(name, age, gender, height, weight) {
        super(name, age, gender); // I haven't included the interests property here
        Object.assign(this, {height, weight});
    }
}
</code>```

I am still beginner so I am not sure if this is good practice or not. Have a nice day!

答:
Inheritance means what it means ... you inherit what the parent gives to you. So 'avoiding attributes' it not really recommended (and I'm not sure you can even do it).

Two solutions :

Architecture wise (that I recommend): in your specific case, I would just put interests in the Teacher class. If other classes would have the interests too, I would create a sub-class like PersonInterest on which Teacher would inherit from.

Code wise: you set interests to null or undefined in the class where you don't need it.

Title: Inheritance in JavaScript

Body:
I have a class Person like this:

 class Person {
    constructor(name, age, gender, interests) {
        Object.assign(this, {name, age, gender, interests});
    }
}

And I can make sub-class like this:

class Teacher extends Person {
    constructor(name, age, gender, interests, subject, grade) {
        super(name, age, gender, interests);
        Object.assign(this, {subject, grade});
    }
}

But what if I want to make sub-class but I don't want to inherit all the properties from the Person class. For example I don't want to inherit the interests property. Do I just exclude it like this:

class Student extends Person {
    constructor(name, age, gender, height, weight) {
        super(name, age, gender); // I haven't included the interests property here
        Object.assign(this, {height, weight});
    }
}

I am still beginner so I am not sure if this is good practice or not. Have a nice day!


问:
How to add <owl:Ontology rdf:about="..."/> in Jena?
I am creating an ontology using apache jena.
How do I add the following simple statement using the jena library?</p>

```<code><owl:Ontology rdf:about="http://example.owl"/>
</code>```

答:
As AKSW points out correctly, method (createOntology) needs to be called on the model itself:

```<code>model.createOntology("http://example.owl");
</code>```

Body:
I am creating an ontology using apache jena.
How do I add the following simple statement using the jena library?

<owl:Ontology rdf:about="http://example.owl"/>

Body:
As AKSW points out correctly, method (createOntology) needs to be called on the model itself:

model.createOntology("http://example.owl");


问:
How can I calculate the number of years between two dates?
I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.

This is my code to get date difference:

```<code>var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");

var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];

    var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){

    if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {

                    number_of_long_years++;
    }
}
</code>```

The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:

```<code>var years = ((days)*(thisyear-birthyear))
            /((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );
</code>```

I'm getting the year count.  Is this correct, or is there a better way to do this?

答:
```<code>getAge(month, day, year) {
    let yearNow = new Date().getFullYear();
    let monthNow = new Date().getMonth() + 1;
    let dayNow = new Date().getDate();
    if (monthNow === month && dayNow < day || monthNow < month) {
      return yearNow - year - 1;
    } else {
      return yearNow - year;
    }
  }
</code>```

Body:
I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.

This is my code to get date difference:

var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");

var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];

    var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){

    if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {

                    number_of_long_years++;
    }
}

The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:

var years = ((days)*(thisyear-birthyear))
            /((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );

I'm getting the year count.  Is this correct, or is there a better way to do this?


问:
How can I extract the values from a record as individual columns in postgresql
How can I extract the values from a record as individual comuns in postgresql

```<code>SELECT
p.*,
(SELECT ROW(id,server_id,format,product_id) FROM products_images pi WHERE pi.product_id = p.id LIMIT 1) AS image

FROM products p

WHERE p.company = 1 ORDER BY id ASC LIMIT 10
</code>```

Instead of

```<code>image
(3, 4, "jpeg", 7)
</code>```

I would like to have

```<code>id | server_id | format | product_id
3  | 4         | jpeg   | 7
</code>```

Is there any way of selecting only one image for each product and return the columns directly instead of a record?

答:
every table has an associated composite type of the same name

https://www.postgresql.org/docs/current/plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES

So, this code

```<code>drop table if exists "#typedef_image"
;
create temp table "#typedef_image"(
    id int,
    server_id int,
    format text,
    product_id int
    )
;
select (row(3, 4, 'jpeg', 7)::"#typedef_image").*
</code>```

will work

ContentLicense: CC BY-SA 2.5

Body:
How can I extract the values from a record as individual comuns in postgresql

SELECT
p.*,
(SELECT ROW(id,server_id,format,product_id) FROM products_images pi WHERE pi.product_id = p.id LIMIT 1) AS image

FROM products p

WHERE p.company = 1 ORDER BY id ASC LIMIT 10

Instead of

image
(3, 4, "jpeg", 7)

I would like to have

id | server_id | format | product_id
3  | 4         | jpeg   | 7

Is there any way of selecting only one image for each product and return the columns directly instead of a record?

Body:
every table has an associated composite type of the same name

https://www.postgresql.org/docs/current/plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES

So, this code

drop table if exists "#typedef_image"
;
create temp table "#typedef_image"(
    id int,
    server_id int,
    format text,
    product_id int
    )
;
select (row(3, 4, 'jpeg', 7)::"#typedef_image").*

will work


问:
Formatting csv file with python
I have a csv file with the following structure:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"
</code>```

I need him to stay like this:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"
</code>```

I received this .csv file from someone else, so I do not know how the conversion was done. I am trying unsuccessfully with the code below:

```<code>input_fd = open("/home/gustavo/Downloads/Redes/Despesas/csvfile.csv", 'r')
output_fd = open('dados_2018_1.csv', 'w')
for line in input_fd.readlines():
    line.replace("\"","")
    output_fd.write(line)
    input_fd.close()
output_fd.close()
</code>```

Is it possible to make this change or will I have to do the conversion from an xml file to a csv, and make this change during the conversion?

答:
First: tell the reader to use delimiter=";" and quoting=csv.QUOTE_NONE. This will properly split your second line which is a string literal containing your delimiter, which you desire to be split. We'll tweak that data to remove the quotation marks (otherwise our output will be quoted strings like '"txNomeParlamentar"', etc).

```<code>import csv
with open('file.txt') as f:
     reader = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)
     data = [list(map(lambda s: s.replace('"', ''), row)) for row in reader]
</code>```

Then: we write the file back out, with the delimiter=";", and quoting=csv.QUOTE_ALL to ensure each item is set in quotes

```<code>with open('out.txt', 'w', newline='') as o:
     writer = csv.writer(o, delimiter=";", quoting=csv.QUOTE_ALL)
     writer.writerows(data)
</code>```

Input:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"
</code>```

Output:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"
</code>```

Title: Formatting csv file with python

Body:
I have a csv file with the following structure:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"

I need him to stay like this:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"

I received this .csv file from someone else, so I do not know how the conversion was done. I am trying unsuccessfully with the code below:

input_fd = open("/home/gustavo/Downloads/Redes/Despesas/csvfile.csv", 'r')
output_fd = open('dados_2018_1.csv', 'w')
for line in input_fd.readlines():
    line.replace("\"","")
    output_fd.write(line)
    input_fd.close()
output_fd.close()

Is it possible to make this change or will I have to do the conversion from an xml file to a csv, and make this change during the conversion?

Body:
First: tell the reader to use delimiter=";" and quoting=csv.QUOTE_NONE. This will properly split your second line which is a string literal containing your delimiter, which you desire to be split. We'll tweak that data to remove the quotation marks (otherwise our output will be quoted strings like '"txNomeParlamentar"', etc).

import csv
with open('file.txt') as f:
     reader = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)
     data = [list(map(lambda s: s.replace('"', ''), row)) for row in reader]

Then: we write the file back out, with the delimiter=";", and quoting=csv.QUOTE_ALL to ensure each item is set in quotes

with open('out.txt', 'w', newline='') as o:
     writer = csv.writer(o, delimiter=";", quoting=csv.QUOTE_ALL)
     writer.writerows(data)

Input:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"

Output:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"


问:
User interface for reordering a list items
I have a list of items as a part of a web application. The question is how user can manipulate the order of items in the list (not the list sort order). The typical way is to use arrow buttons to move items up or down. The other way is the drag-and-drop.

But are there any other ways for a user interface for list reordering?

答:
You could show an overlay when hovering over an element. This overlay shows you 4 arrows (n/e/s/w) and u can click and move the element accordingly.

If you are trying to oder items across a grid like facebook's and picasaweb's photo grouping features, then that is about the only way to handle that

if you had 3 columns each with a list of items, clicking on any of the items would move the item either to the left or right, middle column could show option for left or right. you could still allow for dragging and dropping or sorting using the typical functionality for that.

OwnerDisplayName: pepez

OwnerDisplayName: NTulip


问:
Browser Debugging - How can I get the browser to reload the response from the server without re-requesting it?
In development our rails app runs slow.  When working on javascript, previewing in the browser is a pain because of some of the slow response times.  Is there a way to have the browser simply reprocess the request, and still load fresh assets, without re-requesting the page itself?

Ideal solution is in chrome or firefox.

Thanks.

答:
Generally what you can do is take advantage of the cache. As long as the server is providing correct Last-Modified, ETag, Expires and Cache-Control headers the browser should not re-request that URL unless you press F5 in the browser.

For example you could load your application in a IFRAME or old-school FRAME and add some JavaScript code that quickly navigates away from the page and then returns to the same URL. This forces the browser to reload the URL from cache and reinterpret it.

Of course you shoule make sure that the URL is reloaded from the server after you made changes (like adding a version number to the URL query string or something like that).

Unfortunately browser caching is not always possible to predict exactly.

Hope this helps.

ContentLicense: CC BY-SA 3.0


问:
Build on Xcode 10.2.1 failing at project for tvOS and iOS
I have a lib that has targets for tvOS and iOS on the same workspace.

When I build for tvOS, it gives me an error saying:

```<code>The following build commands failed:
    CompileSwift normal arm64
    CompileXIB /Users/.../<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib
    CompileSwift normal arm64
</code>```

The command Fastlane is using to run the build is:
set -o pipefail && xcodebuild -workspace "<project_name>.xcworkspace" -scheme "<scheme_name>_tvOS" -configuration "Release" -sdk "appletvos" -derivedDataPath "build/tvOS-appletvos" clean build GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES

And when I run it in verbose mode, the part that seems to be showing the error is:

```<code>CompileXIB /Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib (in target: Clappr-iOS)
    cd /Users/<project_folder>/Pods
    export XCODE_DEVELOPER_USR_PATH=/Applications/Xcode.app/Contents/Developer/usr/bin/..
    /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --module Clappr --output-partial-info-plist /Users/<project_folder>/build/tvOS-appletvos/Build/Intermediates.noindex/Pods.build/Release-appletvos/Clappr-iOS.build/SeekbarView-PartialInfo.plist --auto-activate-custom-fonts --target-device tv --minimum-deployment-target 10.0 --output-format human-readable-text --compile /Users/<project_folder>/build/tvOS-appletvos/Build/Products/Release-appletvos/Clappr-iOS/Clappr.framework/SeekbarView.nib /Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib
/* com.apple.ibtool.errors */
/Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib: error: iOS xibs do not support target device type "tv".
</code>```

It is selecting a xib that, at the dependency (Clappr), doesn't belong to tvOS target.

Also, when I try to build using the iOS target, it answers me the following:

```<code>The following build commands failed:
    CompileSwift normal armv7
    CompileSwiftSources normal armv7 com.apple.xcode.tools.swift.compiler
    CompileSwift normal arm64
    CompileSwift normal armv7
    CompileSwift normal arm64
</code>```

The fastlane lane used to run the build for tvOS is the following:

private_lane :xc_build do |params|
  xcodebuild(
    workspace: "ProjectName.xcworkspace",
    scheme: params[:scheme],
    configuration: 'Release',
    sdk: params[:sdk],
    derivedDataPath: params[:derivedDataPath],
    clean: true,
    build: true,
    xcargs: params[:xcargs]
  )
end

lane :build_tvos do
  remove_previous_builds_of(platform: "tvOS")

  #It breaks on the following command
  xc_build(
    scheme: 'ProjectScheme_tvOS',
    sdk: 'appletvos',
    derivedDataPath: 'build/tvOS-appletvos',
    xcargs: "GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES"
  )

  xc_build(
    scheme: 'ProjectScheme_tvOS',
    sdk: 'appletvsimulator',
    derivedDataPath: 'build/tvOS-appletvsimulator',
    xcargs: "GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES"
  )

  #This uses lipo to build universal frameworks
  make_universal_framework(
    universal_framework_folder: "Framework/tvOS",
    device_framework_folder: "build/tvOS-appletvos/Build/Products/Release-appletvos",
    simulator_framework_folder: "build/tvOS-appletvsimulator/Build/Products/Release-appletvsimulator"
  )
end
```

Environment info:

 * iOS target has build seating valid architectures with the value arm64 arm64e armv7 armv7s and tvOS has value: arm64

 * Fastlane version 2.123.0

 * Cocoapods version 1.6.1

 * make_universal_framework uses lipo to build

答:
To be completely honest, I don't know why it is failing, although I found a solution.

This answer led me to the right direction: https://github.com/Webtrekk/webtrekk-ios-sdk/issues/55#issuecomment-481720922

I know, my problem has nothing to do with the one written on the GitHub issue, but it gave me an idea to solve it. I went to menu

File -> Project(Workspace) Settings -> Workspace settings -> Build System => 'Legacy Build System'

And it solved the problem!

It seems to be a difference on the build system, but I haven't found documentation confirming it.

Body:
I have a lib that has targets for tvOS and iOS on the same workspace.

When I build for tvOS, it gives me an error saying:

The following build commands failed:
    CompileSwift normal arm64
    CompileXIB /Users/.../<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib
    CompileSwift normal arm64

The command Fastlane is using to run the build is:
set -o pipefail && xcodebuild -workspace "<project_name>.xcworkspace" -scheme "<scheme_name>_tvOS" -configuration "Release" -sdk "appletvos" -derivedDataPath "build/tvOS-appletvos" clean build GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES

And when I run it in verbose mode, the part that seems to be showing the error is:

CompileXIB /Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib (in target: Clappr-iOS)
    cd /Users/<project_folder>/Pods
    export XCODE_DEVELOPER_USR_PATH=/Applications/Xcode.app/Contents/Developer/usr/bin/..
    /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --module Clappr --output-partial-info-plist /Users/<project_folder>/build/tvOS-appletvos/Build/Intermediates.noindex/Pods.build/Release-appletvos/Clappr-iOS.build/SeekbarView-PartialInfo.plist --auto-activate-custom-fonts --target-device tv --minimum-deployment-target 10.0 --output-format human-readable-text --compile /Users/<project_folder>/build/tvOS-appletvos/Build/Products/Release-appletvos/Clappr-iOS/Clappr.framework/SeekbarView.nib /Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib
/* com.apple.ibtool.errors */
/Users/<project_folder>/Pods/Clappr/Sources/Clappr_iOS/Classes/Plugin/Core/MediaControl/Seekbar/Views/SeekbarView.xib: error: iOS xibs do not support target device type "tv".

It is selecting a xib that, at the dependency (Clappr), doesn't belong to tvOS target.

Also, when I try to build using the iOS target, it answers me the following:

The following build commands failed:
    CompileSwift normal armv7
    CompileSwiftSources normal armv7 com.apple.xcode.tools.swift.compiler
    CompileSwift normal arm64
    CompileSwift normal armv7
    CompileSwift normal arm64

The fastlane lane used to run the build for tvOS is the following:

private_lane :xc_build do |params|
  xcodebuild(
    workspace: "ProjectName.xcworkspace",
    scheme: params[:scheme],
    configuration: 'Release',
    sdk: params[:sdk],
    derivedDataPath: params[:derivedDataPath],
    clean: true,
    build: true,
    xcargs: params[:xcargs]
  )
end

lane :build_tvos do
  remove_previous_builds_of(platform: "tvOS")

  #It breaks on the following command
  xc_build(
    scheme: 'ProjectScheme_tvOS',
    sdk: 'appletvos',
    derivedDataPath: 'build/tvOS-appletvos',
    xcargs: "GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES"
  )

  xc_build(
    scheme: 'ProjectScheme_tvOS',
    sdk: 'appletvsimulator',
    derivedDataPath: 'build/tvOS-appletvsimulator',
    xcargs: "GCC_PREPROCESSOR_DEFINITIONS='${inherited}' BITCODE_GENERATION_MODE=bitcode ENABLE_BITCODE=YES"
  )

  #This uses lipo to build universal frameworks
  make_universal_framework(
    universal_framework_folder: "Framework/tvOS",
    device_framework_folder: "build/tvOS-appletvos/Build/Products/Release-appletvos",
    simulator_framework_folder: "build/tvOS-appletvsimulator/Build/Products/Release-appletvsimulator"
  )
end

Environment info:

 * iOS target has build seating valid architectures with the value arm64 arm64e armv7 armv7s and tvOS has value: arm64

 * Fastlane version 2.123.0

 * Cocoapods version 1.6.1

 * make_universal_framework uses lipo to build


问:
Concerning Node.js was Bootstrap npm package recently deprecated?
I am trying to install Bootstrap using the npm install method. I have been on this for a while now and am wondering if I am doing something wrong? the npm install is still included on Bootstrap site as well as github and the npm page.

From what I understand using bower has been deprecated. Had serious issues using gulp. Any assistance or a link to an updated tutorial would be greatly appreciated.

Following errors occured while trying to install via terminal:

```<code>~/GitHub/GitSite $ npm install boostrap
npm WARN deprecated boostrap@2.0.0: Package no longer supported.
Contact support@npmjs.com for more info.
npm WARN gitsite@1.0.0 No repository field.

+ boostrap@2.0.0
updated 1 package in 1.902s
~/GitHub/GitSite $ npm install boostrap jquery popper.js --save
npm WARN deprecated boostrap@2.0.0: Package no longer supported.
Contact support@npmjs.com for more info.
npm WARN gitsite@1.0.0 No repository field.

+ boostrap@2.0.0
+ jquery@3.3.1
+ popper.js@1.14.3
updated 3 packages in 2.216s
</code>```

In the download was included all the correct folders, however, in node_modules > boostrap there was a README file that said:

Deprecated Package

This package is no longer supported and has been deprecated. To avoid
  malicious use, npm is hanging on to the package name.

Please contact support@npmjs.com if you have questions about this
  package.

答:
~/GitHub/GitSite $ npm install boostrap

You made a typo buddy, npm install boostrap instead of npm install bootstrap
Try with the correct package name and it will work!

Body:
I am trying to install Bootstrap using the npm install method. I have been on this for a while now and am wondering if I am doing something wrong? the npm install is still included on Bootstrap site as well as github and the npm page.

From what I understand using bower has been deprecated. Had serious issues using gulp. Any assistance or a link to an updated tutorial would be greatly appreciated.

Following errors occured while trying to install via terminal:

~/GitHub/GitSite $ npm install boostrap
npm WARN deprecated boostrap@2.0.0: Package no longer supported.
Contact support@npmjs.com for more info.
npm WARN gitsite@1.0.0 No repository field.

+ boostrap@2.0.0
updated 1 package in 1.902s
~/GitHub/GitSite $ npm install boostrap jquery popper.js --save
npm WARN deprecated boostrap@2.0.0: Package no longer supported.
Contact support@npmjs.com for more info.
npm WARN gitsite@1.0.0 No repository field.

+ boostrap@2.0.0
+ jquery@3.3.1
+ popper.js@1.14.3
updated 3 packages in 2.216s

In the download was included all the correct folders, however, in node_modules > boostrap there was a README file that said:

Deprecated Package

This package is no longer supported and has been deprecated. To avoid
  malicious use, npm is hanging on to the package name.

Please contact support@npmjs.com if you have questions about this
  package.


问:
Excel: "if result is 0, insert something else" without IF
All I can find on the internet is simple examples where people don't consider that "A1" could be something really huge:

```<code>=IF(A1=0;"my_replacement";A1)
</code>```

I do not want to write A1 twice (in the comparison and in the else branch), isn't there something like "check the result of this super long expression. if it is 0, put something else instead"? Something like IFERROR but not for an error ... ?

答:
You can write your own function for this:

In VBA:

```<code>Function IsZero(r As Range, Replacement As String)
  If r.Value <> 0 Then
    IsZero = r.Value
  Else:
    IsZero = Replacement
  End If
End Function
</code>```

In Excel, you can have following examples:

Which is based on the formula:

```<code>=IsZero(A1;"test")
</code>```

Body:
All I can find on the internet is simple examples where people don't consider that "A1" could be something really huge:

=IF(A1=0;"my_replacement";A1)

I do not want to write A1 twice (in the comparison and in the else branch), isn't there something like "check the result of this super long expression. if it is 0, put something else instead"? Something like IFERROR but not for an error ... ?

Body:
You can write your own function for this:

In VBA:

Function IsZero(r As Range, Replacement As String)
  If r.Value <> 0 Then
    IsZero = r.Value
  Else:
    IsZero = Replacement
  End If
End Function

In Excel, you can have following examples:

Which is based on the formula:

=IsZero(A1;"test")


问:
How to upgrade Sustainsys.Saml2 from version 0.23.0 to version 2.0.0
I want to upgrade Sustainsys.Saml2 Nuget package from version 0.23.0 to version 2.0.0.

I have an error in next line of code: spOptions.SystemIdentityModelIdentityConfiguration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;.
The SPOptions class doesn't have a IdentityConfiguration property anymore.

var spOptions = new SPOptions();

spOptions.SystemIdentityModelIdentityConfiguration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

I want to know how to receive the same behaviour after updating to version 2.0.

答: It's currently not supported in 2.2 to ignore the audience restriction. I you need that, and still run on the .NET Framework you might as well use 1.0.0.</p>


问:
Windows authentication on a WCF service fails after password change
We have a windows service hosting some wcf web services that are authenticated with wsHttpBindings. A user experienced authentication issues and it turned out her password had expired. She then changed her password and restarted the computer. After this password change she was no longer able to access the web services. She received

```<code>System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
</code>```

On the server we had service tracing enabled and the error appears when the user attempted to call the service:

```<code>System.ComponentModel.Win32Exception (0x80004005): The Security Support Provider Interface (SSPI) negotiation failed.
</code>```

We then checked the Windows Logs -> Security in Event View on the server and find

An account failed to log on.

```<code>Subject:
    Security ID:        NULL SID
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0

Logon Type:         3

Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       user@compyany.com
    Account Domain:

Failure Information:
    Failure Reason:     Unknown user name or bad password.
    Status:         0xc000006d
    Sub Status:     0xc0000064
</code>```

We have tried resetting her password again but that did not help.

答:
```<code>Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials
</code>```

There was one entry in the list which was to the server we had problems accessing.
We deleted it and the user was able to access the service without issue.

It seems that the user had accessed the server using mstsc or similar and entered a upn username format user@company.com and saved the password. This did not get updated when she changed her password and for some reason wcf uses these credentials when accessing the service instead of the default.

Body:
We have a windows service hosting some wcf web services that are authenticated with wsHttpBindings. A user experienced authentication issues and it turned out her password had expired. She then changed her password and restarted the computer. After this password change she was no longer able to access the web services. She received

System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.

On the server we had service tracing enabled and the error appears when the user attempted to call the service:

System.ComponentModel.Win32Exception (0x80004005): The Security Support Provider Interface (SSPI) negotiation failed.

We then checked the Windows Logs -> Security in Event View on the server and find

An account failed to log on.

Subject:
    Security ID:        NULL SID
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0

Logon Type:         3

Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       user@compyany.com
    Account Domain:

Failure Information:
    Failure Reason:     Unknown user name or bad password.
    Status:         0xc000006d
    Sub Status:     0xc0000064

We have tried resetting her password again but that did not help.

Body:
Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

There was one entry in the list which was to the server we had problems accessing.
We deleted it and the user was able to access the service without issue.

It seems that the user had accessed the server using mstsc or similar and entered a upn username format user@company.com and saved the password. This did not get updated when she changed her password and for some reason wcf uses these credentials when accessing the service instead of the default.


问:
Vue.js / OpenSSL / Chrome: ERR_CERT_AUTHORITY_INVALID
I am running a micro service (using nginx, node.js, express, cors, https). Then I am sending post requests to this micro service via a web front-end (using vue.js and axios), which gives me errors!

When using a tool like Insomnia or Postman everything works fine, when using Google Chrome with the front-end, I get the following error in Inspect -> Network -> Status:

```<code>(failed) net::ERR_CERT_AUTHORITY_INVALID
</code>```

I have generated the certificate with OpenSSL using SAN with proper DNS and IP, but it doesn't work with Google Chrome:

```<code>openssl req \
    -newkey rsa:2048 \
    -x509 \
    -nodes \
    -keyout server.key \
    -new \
    -out server.crt \
    -subj /CN=mydomainname \
    -reqexts SAN \
    -extensions SAN \
    -config <(cat /etc/ssl/openssl.cnf \
        <(printf '[SAN]\nsubjectAltName=DNS:mydomainname,IP:123.123.123.123')) \
    -sha256 \
    -days 3650
</code>```

What else can I do to solve this?

答:
I could solve this through another approach, where I wouldn't use OpenSSL but only nginx as a proxy server and certbots https certificates, which work fine with Google Chrome. Therefore I have configured multiple proxy passes in nginx, so all of the external requests were being passed via https and then being forwarded to the local servers appropriately:</p>

```<code>location ^~ /api/ {
    proxy_pass http://localhost:3000/;
}

location / {
    proxy_pass http://localhost:8080/;
}
</code>```

Body:
I am running a micro service (using nginx, node.js, express, cors, https). Then I am sending post requests to this micro service via a web front-end (using vue.js and axios), which gives me errors!

When using a tool like Insomnia or Postman everything works fine, when using Google Chrome with the front-end, I get the following error in Inspect -> Network -> Status:

(failed) net::ERR_CERT_AUTHORITY_INVALID

I have generated the certificate with OpenSSL using SAN with proper DNS and IP, but it doesn't work with Google Chrome:

openssl req \
    -newkey rsa:2048 \
    -x509 \
    -nodes \
    -keyout server.key \
    -new \
    -out server.crt \
    -subj /CN=mydomainname \
    -reqexts SAN \
    -extensions SAN \
    -config <(cat /etc/ssl/openssl.cnf \
        <(printf '[SAN]\nsubjectAltName=DNS:mydomainname,IP:123.123.123.123')) \
    -sha256 \
    -days 3650

What else can I do to solve this?

Body:
I could solve this through another approach, where I wouldn't use OpenSSL but only nginx as a proxy server and certbots https certificates, which work fine with Google Chrome. Therefore I have configured multiple proxy passes in nginx, so all of the external requests were being passed via https and then being forwarded to the local servers appropriately:

location ^~ /api/ {
    proxy_pass http://localhost:3000/;
}

location / {
    proxy_pass http://localhost:8080/;
}


问:
LocalDateTime to specific timezone
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

```<code>LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
</code>```

答:
Since Java 8 the date/time API is pretty easy to work with.

In your case:

```<code>// your local date/time with no timezone information
LocalDateTime localNow = LocalDateTime.now();
// setting UTC as the timezone
ZonedDateTime zonedUTC = localNow.atZone(ZoneId.of("UTC"));
// converting to IST
ZonedDateTime zonedIST = zonedUTC.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
</code>```

You'll see a difference in the time (and possibly the date) between zonedUTC and zonedIST, reflecting the time zone offset between the two.

Note the usage of withZoneSameInstant here, e.g. as opposed to withZoneSameLocal.

Title: LocalDateTime to specific timezone

Body:
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

Body:
Since Java 8 the date/time API is pretty easy to work with.

In your case:

// your local date/time with no timezone information
LocalDateTime localNow = LocalDateTime.now();
// setting UTC as the timezone
ZonedDateTime zonedUTC = localNow.atZone(ZoneId.of("UTC"));
// converting to IST
ZonedDateTime zonedIST = zonedUTC.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));

You'll see a difference in the time (and possibly the date) between zonedUTC and zonedIST, reflecting the time zone offset between the two.

Note the usage of withZoneSameInstant here, e.g. as opposed to withZoneSameLocal.


问:
Find min and max of every column for every label in pandas.DataFrame
I have a DataFrame called df and it has 4 columns, like the one presented below:

```<code>A      B      C      Class
12     13     22     1
8      15     20     1
9      14     25     1
18     9      35     2
5      14     30     2
4      12     28     2
35     87     67     3
35     82     66     3
20     7      32     4
10     8      32     4
22     7      31     4
...    ...    ...    ...
</code>```

What I want is to find the min and max for every column with respect to the class.
In other words, I would like to get a result similar to the one below:

```<code>Class: 1
A: [8, 12]
B: [13, 15]
C: [20, 25]

Class: 2
A: [4, 18]
B: [9, 14]
C: [28, 35]

Class: 3
A: [35, 35]
B: [82, 87]
C: [66, 67]
...
</code>```

Body:
I have a DataFrame called df and it has 4 columns, like the one presented below:

A      B      C      Class
12     13     22     1
8      15     20     1
9      14     25     1
18     9      35     2
5      14     30     2
4      12     28     2
35     87     67     3
35     82     66     3
20     7      32     4
10     8      32     4
22     7      31     4
...    ...    ...    ...

What I want is to find the min and max for every column with respect to the class.
In other words, I would like to get a result similar to the one below:

Class: 1
A: [8, 12]
B: [13, 15]
C: [20, 25]

Class: 2
A: [4, 18]
B: [9, 14]
C: [28, 35]

Class: 3
A: [35, 35]
B: [82, 87]
C: [66, 67]
...

Body:
Another approach

df.groupby('Class').apply(lambda x: pd.Series([[min(x.A),max(x.A)],[min(x.B),max(x.B)],[min(x.C),max(x.C)]])).reset_index().rename(columns={0:'A',1:'B',2:'C'})

Output

   Class         A         B         C
0      1   [8, 12]  [13, 15]  [20, 25]
1      2   [4, 18]   [9, 14]  [28, 35]
2      3  [35, 35]  [82, 87]  [66, 67]
3      4  [10, 22]    [7, 8]  [31, 32]


问:
How to redirect from one page to another one with changing wp query and without reloading page?
The problem

There is a URL:
https://example.com/my-category/category

Need to create another one
https://example.com/shop

Behavior to achieve:

By visiting https://example.com/shop content and all query variables need to be identical like for https://example.com/my-category/category

https://example.com/my-category/category and https://example.com/shop - need to be the same.
Meta tags, title, and other content need to be identical.

Need to create an inner redirect

from https://example.com/shop

to https://example.com/my-category/category without reloading page.

This is the snippet what I've tried

flush_rewrite_rules();
add_rewrite_rule(
  '/shop?$',
  'index.php?product_cat=my-category',
  'top'
);

I expect to see the same page for these two URLs

https://example.com/my-category/category
and
https://example.com/shop

The second one needs to be redirected to the first one.

答:
The easiest way to achieve this is to edit your .htaccess file (on your server, at the root folder for http://example.com) and add a 301 Redirect as follows:

```<code>Redirect 301 /shop /my-category/category
</code>```

This means that when someone enters http://www.example.com/shop in the browser, it will be automatically redirected to http://www.example.com/my-category/category, and latter page will load.

Body:
The easiest way to achieve this is to edit your .htaccess file (on your server, at the root folder for http://example.com) and add a 301 Redirect as follows:

Redirect 301 /shop /my-category/category

This means that when someone enters http://www.example.com/shop in the browser, it will be automatically redirected to http://www.example.com/my-category/category, and latter page will load.


问:
Smartgwt DataSource with gwt requestfactory etc
Does anyone have a working example of using the new GWT constructs for RequestFactory with a SmartGWT DataSource for databound widgets ?

If possible I would like to make a generic data service that contains methods for listAll, getByExample, getByPrimaryKey etc. I beleibe it should be possible ???

If using RequestFactory would it make sense to ditch the datasource altogether and work directly with the widget fields ?

Cheers,
Andy

答:
http://forums.smartclient.com/showthread.php?t=10850&highlight=GwtRPCDatasource

This link provides an implementation of smartgwt datasource with RPC. My take is it should be easy to extend it to RequestFactory.

About ditching DataSource, I would advice against it. I have created an application with it and trust me, smartgwt widgets are very deeply ingrained with a datasource. A lot of vanilla functionality of the widgets depends on datasource. To ditch the datasouce all together and try and use the widgets gets pretty complicated. I always have felt that smartgwt skimps on documentation, and that will hit you hard.

So prefer a datasource unless you have a very gooood understanding of how smartgwt works!


问:
Generating angular/typescript class that specifies allowed values for property
Imagine I'm making a simple model that describes (for instance) the details of a query:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}
</code>```

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}
</code>```

Except of course the union operator works with types, not values.  I could conceptually try something like this:

```<code>export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}
</code>```

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

答:
You can create a type

```<code>Type sortDirection = 'asc' | 'desc';
</code>```

And use it in your class

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: sortDirection = 'asc';
}
</code>```

Body:
Imagine I'm making a simple model that describes (for instance) the details of a query:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}

Except of course the union operator works with types, not values.  I could conceptually try something like this:

export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

Body:
You can create a type

Type sortDirection = 'asc' | 'desc';

And use it in your class

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: sortDirection = 'asc';
}


问:
sed command to append string inside the double qoutes
I want to update a file on remote linux server. For this i am using sed command. in that i have to first search that line then update value

i have file with following content:

```<code>GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur"
GRUB_DISABLE_RECOVERY="true"
</code>```

so using sed command i have to append sharma in double qoutes
means after execution line will be  grub_cmdline_linux = "ankur sharma"

i have tried this command

```<code>sed -i 's+\(GRUB_CMDLINE_LINUX.*\)+\1 sharma+g' '/etc/default/grub.bak'
</code>```

by this command sharma is appending at the end of the line but it should be append inside the double qoutes

Expected output:

```<code>GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur sharma"
GRUB_DISABLE_RECOVERY="true"
</code>```

答:
```<code>$ sed 's/GRUB_CMDLINE_LINUX="[^"]*/& sharma/' file
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur sharma"
GRUB_DISABLE_RECOVERY="true"
</code>```

Body:
I want to update a file on remote linux server. For this i am using sed command. in that i have to first search that line then update value

i have file with following content:

GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur"
GRUB_DISABLE_RECOVERY="true"

so using sed command i have to append sharma in double qoutes
means after execution line will be  grub_cmdline_linux = "ankur sharma"

i have tried this command

sed -i 's+\(GRUB_CMDLINE_LINUX.*\)+\1 sharma+g' '/etc/default/grub.bak'

by this command sharma is appending at the end of the line but it should be append inside the double qoutes

Expected output:

GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur sharma"
GRUB_DISABLE_RECOVERY="true"


问:
class templates 'no matching function for call to Player::Player()'
I'm learning about data structures by making a simple card game.
In this code, i have a class Player, and a Queue containing all the players in the game.

the implementation of the Queue:

```<code>template < typename T >
    class Queue{
    int count;
    int front, rear;
    T entry[maxsize];
    public:
    Queue();
    bool empty();
    errorcode Append(T item);
    errorcode serve();
    errorcode retreive(T &item);
    };
</code>```

The Queue constructor:

```<code>template <typename T>
    Queue<T>::Queue(){
        count = 0;
        rear = maxsize-1;
        front=0;
    }
</code>```

And here is the Player class:

```<code>       class Player {
            int number;
            List<string> set;
        public:
            Player(int number, List<string> set) {
                this->number = number;
                this->set = set;
            }
            void draw();
            string play();
            .
            .
            .
        };
</code>```

in the main function, i declare the Queue using this code:

```<code>Queue<Player> pl;
</code>```

But i get the error 'no matching function for call to Player::Player()', this error is in the line where the queue constructor is implemented.

答:
It's what it says (and has little to do with templates).

Queue<Player> has a member Player entry[maxsize], which requires the default-construction of maxsize Player objects.

But since Player has no default constructor, this is impossible.

How about a nice vector instead? You don't really need/want to allocate the maximum number of Players up-front anyway, surely.

Body:
I'm learning about data structures by making a simple card game.
In this code, i have a class Player, and a Queue containing all the players in the game.

the implementation of the Queue:

template < typename T >
    class Queue{
    int count;
    int front, rear;
    T entry[maxsize];
    public:
    Queue();
    bool empty();
    errorcode Append(T item);
    errorcode serve();
    errorcode retreive(T &item);
    };

The Queue constructor:

template <typename T>
    Queue<T>::Queue(){
        count = 0;
        rear = maxsize-1;
        front=0;
    }

And here is the Player class:

       class Player {
            int number;
            List<string> set;
        public:
            Player(int number, List<string> set) {
                this->number = number;
                this->set = set;
            }
            void draw();
            string play();
            .
            .
            .
        };

in the main function, i declare the Queue using this code:

Queue<Player> pl;

But i get the error 'no matching function for call to Player::Player()', this error is in the line where the queue constructor is implemented.


问:
excel matching two arrays
I have a problem that seems pretty easy, but still cannot find a proper solution, I want to avoid using vba.

I have two tables in one spreadsheet. both have the same columns - Name, City, Province.
My goal is compare both and if three out of three values in a row match, then pull "1", if not, pull 0.

I have used the formulas below , but it does not work for my case .

=IF(AND(A2=P:P,G2=M:M,H2=L:L),1,0)

=INDEX(A:P,MATCH(A2,P:P,FALSE),MATCH(G2,M:M,FALSE),2)

=INDEX(L:P,MATCH(A5,P:P,0),MATCH(G5,M:M,0),MATCH(H5,L:L,0))

=SUMPRODUCT(--(L2:L60=H2),--(M2:M60=G2),--(P2:P60=A2),B2:B60)

It seems that the solution is quiet simple , but I cannot find it,

Thanks in advance!

答:
Assumption:  Values just need to exist, not that they need to be of equivalent row.

```<code>=If(IfError(Match(A2,P:P,0),0)*IfError(Match(G2,M:M,0),0)*IfError(Match(H2,L:L,0),0)>0,1,0)
</code>```

For each IfError, you will output a row number (>0) if you match, or if there is no match a zero will be output.  Multiply anything by zero and you get zero, whcih allows a 1 or 0 output for true/false in the overarching If-statement.

If they need to be of the same row, you can compare 2 matches, which rely on the transitive property (A=B, B=C, so A=C):

```<code>=If(And(Match(A2,P:P,0)=Match(G2,M:M,0),Match(G2,M:M,0)=Match(H2,L:L,0)),1,0)
</code>```

Edit1:

Per my comment (to this answer) about false negatives, a UDF or subroutine in VBA would be more appropriate, considering Match() returns the first row that has a match.

As this is not a VBA tagged post, this is a bit above the expected answer...  My recommendation would be to:

A)  Ensure you are comfortable using VBA.

B)  Make a post about creating a user-defined function (note that any post on here about VBA has an expectation that the poster can interact with an expert on the topic and will be putting forth effort to write the code themselves, as StackOverflow is not a code-for-you service).

To help give a lead on what may be in your UDF:

A loop to go through the values from first row to last row in the search column (i.e., L, M, & P)

A variable to dynamically identify the last row of your search column

An if-statement to compare values from your lookup values (i.e., A2, G2, H2) to the search values at the current iteration of the loop

An output of 1 (has match) or 0 (no match).

There are many ways to go about this with VBA; hopefully that's a good start for you, Irina!

Title: excel matching two arrays

Body:
Assumption:  Values just need to exist, not that they need to be of equivalent row.

=If(IfError(Match(A2,P:P,0),0)*IfError(Match(G2,M:M,0),0)*IfError(Match(H2,L:L,0),0)>0,1,0)

For each IfError, you will output a row number (>0) if you match, or if there is no match a zero will be output.  Multiply anything by zero and you get zero, whcih allows a 1 or 0 output for true/false in the overarching If-statement.

If they need to be of the same row, you can compare 2 matches, which rely on the transitive property (A=B, B=C, so A=C):

=If(And(Match(A2,P:P,0)=Match(G2,M:M,0),Match(G2,M:M,0)=Match(H2,L:L,0)),1,0)

Edit1:

Per my comment (to this answer) about false negatives, a UDF or subroutine in VBA would be more appropriate, considering Match() returns the first row that has a match.

As this is not a VBA tagged post, this is a bit above the expected answer...  My recommendation would be to:

A)  Ensure you are comfortable using VBA.

B)  Make a post about creating a user-defined function (note that any post on here about VBA has an expectation that the poster can interact with an expert on the topic and will be putting forth effort to write the code themselves, as StackOverflow is not a code-for-you service).

To help give a lead on what may be in your UDF:

A loop to go through the values from first row to last row in the search column (i.e., L, M, & P)

A variable to dynamically identify the last row of your search column

An if-statement to compare values from your lookup values (i.e., A2, G2, H2) to the search values at the current iteration of the loop

An output of 1 (has match) or 0 (no match).

There are many ways to go about this with VBA; hopefully that's a good start for you, Irina!


问:
Libreoffice jars not found running spring-boot from command-line
I'm trying to run a spring-boot application from command line that uses jodreports but it fails with some FileNotFoundExceptions related to Libreoffice dependencies. The files exists but what I find strange is that it seems to be looking up wrong paths.

```<code>Failed to scan [file:/<mypath>/.m2/repository/org/libreoffice/juh/5.2.0/jurt.jar]
</code>```

Notice that the path includes the folder /juh but the file is jurt.jar. Moreover, the file should be jurt-5.2.0.jar but the version number is not used in the filename. The missed files are also in the folders /juh, /jurt, /ridl, etc.

I'm launchig with the following command line (tried other combinations and none worked):

```<code>mvn spring-boot:start -P dev -s <path>\settings.xml -f .\application -Dspring.profiles.active=dev
</code>```

From my STS IDE the application boots without problem but I can't figure out how it does to accomplish ok.

I also have noticed that that the IDE console shows this first line:

```<code>[CPRO][DEBUG] [2019-05-29 13:50:03] [restartedMain] [org.springframework.boot.logging.ClasspathLoggingApplicationListener.onApplicationEvent(52)] Application started with classpath: [file:/D:/CTyPD/proyectos/repo/calcprod/application/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/service-impl/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/integration/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/service-api/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/repository/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/model/target/classes/, file:/C:/Users/rafael.cano/.m2/repository/org/libreoffice/juh/, file:/C:/Users/rafael.cano/.m2/repository/org/libreoffice/jurt/]
</code>```

which at the end  includes two libreoffice paths, but I can't find where they come from, and why the lines add these and not other dependencies.

Thanks in advance!

UPDATE
I didn't notice that the Libreofice messages were warnings. I've come up with a different command line and I'm getting different error messages. I will delete this post and ask in another one.

Thanks!

答:
As per my knowledge you don't required to mention settings.xml file path, that one will take care by maven.
You can run spring boot application in 2 ways.

Command line :

Go to application root folder and execute below command

mvn clean install -Pdev

then go to target folder and execute below command

java -jar app-name-*.(jar/war)

Spring Boot Maven Plugin:

mvn spring-boot:run -Pdev  OR
  mvn spring-boot:run -Dspring.profiles.active=dev

Spring Boot reference document

Body:
I'm trying to run a spring-boot application from command line that uses jodreports but it fails with some FileNotFoundExceptions related to Libreoffice dependencies. The files exists but what I find strange is that it seems to be looking up wrong paths.

Failed to scan [file:/<mypath>/.m2/repository/org/libreoffice/juh/5.2.0/jurt.jar]

Notice that the path includes the folder /juh but the file is jurt.jar. Moreover, the file should be jurt-5.2.0.jar but the version number is not used in the filename. The missed files are also in the folders /juh, /jurt, /ridl, etc.

I'm launchig with the following command line (tried other combinations and none worked):

mvn spring-boot:start -P dev -s <path>\settings.xml -f .\application -Dspring.profiles.active=dev

From my STS IDE the application boots without problem but I can't figure out how it does to accomplish ok.

I also have noticed that that the IDE console shows this first line:

[CPRO][DEBUG] [2019-05-29 13:50:03] [restartedMain] [org.springframework.boot.logging.ClasspathLoggingApplicationListener.onApplicationEvent(52)] Application started with classpath: [file:/D:/CTyPD/proyectos/repo/calcprod/application/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/service-impl/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/integration/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/service-api/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/repository/target/classes/, file:/D:/CTyPD/proyectos/repo/calcprod/model/target/classes/, file:/C:/Users/rafael.cano/.m2/repository/org/libreoffice/juh/, file:/C:/Users/rafael.cano/.m2/repository/org/libreoffice/jurt/]

which at the end  includes two libreoffice paths, but I can't find where they come from, and why the lines add these and not other dependencies.

Thanks in advance!

UPDATE
I didn't notice that the Libreofice messages were warnings. I've come up with a different command line and I'm getting different error messages. I will delete this post and ask in another one.

Thanks!


问:
Can't display 2 partials on one page
I’m trying to do the "simple todo list" task, but I don’t know how to display it on one page as on screenshot http://joxi.net/v29DKEVcBLB5mG (that is, there is a list of saved items and to the right is a form for adding a new one). If everything is separate it works for me, but when it renders 2 partial on one page - error undefined method each for #<Track:0x00007f8fc42c2698> (NoMethodError in Tracks#new)
Here is my new.html.erb

```<code><h1> Create a New Item!</h1>
<%= render 'table' %>
<%= render 'form' %>
</code>```

Table partial:

```<code><table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>All Tracks</th>
      <th>It's description</th>
      <th>Priority</th>
      <th>Date</th>
      <th>Delete</th>
      <th>Restore</th>
    </tr>
  </thead>
  <tbody>
    <% @track.each do |track| %>
    <tr>
      <td> <%= track.id %> </td>
      <td> <%= link_to track.item, edit_track_path(track.id) %> </td>
      <td> <%= track.description %> </td>
      <td> <%= track.priority %> </td>
      <td> <%= track.created_at.strftime('%d/%m/%Y') %> </td>
      <td><%= button_to "Delete", track_path(track.id), method: :delete %></td>
      <td><%= button_to "Restore", track_path(track.id), method: :put %></td>
    </tr>
    <% end %>
  </tbody>
</table>
</code>```

And _form partial:

```<code>  <%= form_for @track do |f| %>
  <p>
    <%= f.label :item %><br>
    <%= f.text_field :item %>
  </p>
  <p>
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.select :priority, priorities,
        prompt: "Select priority" %>
  </p>
  <p>
    <%= f.submit %>
  </p>
  <% end %>
    <%= link_to 'Back', tracks_path %>
    <%= link_to 'Home', root_path %>
</code>```

And Tracks controller:

```<code>class TracksController < ApplicationController
  before_action :find_track, only: [:show, :edit, :update, :destroy]

  def index
    @track = Track.all
  end

  def show
  end

  def new
    @track = Track.new
  end

  def create
    @track = Track.new(track_params)
    if @track.save
      flash[:success] = "It works!"
      redirect_to tracks_path
    else
      flash[:success] = "Its wrong!"
      render 'new'
    end
  end

  def update
    if @track.update(track_params)
      redirect_to @track
    else
      render 'edit'
    end
  end

  def edit
  end

  def destroy
    @track.destroy
    redirect_to tracks_path
  end

private
  def track_params
    params.require(:track).permit(:item, :description, :priority)
  end

  def find_track
    @track = Track.find(params[:id])
  end
end
</code>```

Thanks in advance!

答:
Since you render the page for Tracks#new action it should be

```<code>def new
  @tracks = Track.all
  @track = Track.new
end
</code>```

and

```<code><% @tracks.each do |track| %>
</code>```

in view iterator. Also you need to add @tracks = Track.all to the create action, otherwise you will not be able render tracks table on validation error.

Note, by convention we use plural from for collections and single for single record. You need to have both @tracks and @track in the new action since you want to render all pages and create a new one.

Btw, do you use index action anywhere? If no, you can safely remove it from controller and routes.rb

Title: Can't display 2 partials on one page

Body:
I’m trying to do the "simple todo list" task, but I don’t know how to display it on one page as on screenshot http://joxi.net/v29DKEVcBLB5mG (that is, there is a list of saved items and to the right is a form for adding a new one). If everything is separate it works for me, but when it renders 2 partial on one page - error undefined method each for #<Track:0x00007f8fc42c2698> (NoMethodError in Tracks#new)
Here is my new.html.erb

 Create a New Item!

<%= render 'table' %>
<%= render 'form' %>

Table partial:

      ID
      All Tracks
      It's description
      Priority
      Date
      Delete
      Restore

    <% @track.each do |track| %>

       <%= track.id %>
       <%= link_to track.item, edit_track_path(track.id) %>
       <%= track.description %>
       <%= track.priority %>
       <%= track.created_at.strftime('%d/%m/%Y') %>
      <%= button_to "Delete", track_path(track.id), method: :delete %>
      <%= button_to "Restore", track_path(track.id), method: :put %>

    <% end %>

And _form partial:

  <%= form_for @track do |f| %>

    <%= f.label :item %>

    <%= f.text_field :item %>

    <%= f.label :description %>

    <%= f.text_area :description %>

    <%= f.select :priority, priorities,
        prompt: "Select priority" %>

    <%= f.submit %>

  <% end %>
    <%= link_to 'Back', tracks_path %>
    <%= link_to 'Home', root_path %>

And Tracks controller:

class TracksController < ApplicationController
  before_action :find_track, only: [:show, :edit, :update, :destroy]

  def index
    @track = Track.all
  end

  def show
  end

  def new
    @track = Track.new
  end

  def create
    @track = Track.new(track_params)
    if @track.save
      flash[:success] = "It works!"
      redirect_to tracks_path
    else
      flash[:success] = "Its wrong!"
      render 'new'
    end
  end

  def update
    if @track.update(track_params)
      redirect_to @track
    else
      render 'edit'
    end
  end

  def edit
  end

  def destroy
    @track.destroy
    redirect_to tracks_path
  end

private
  def track_params
    params.require(:track).permit(:item, :description, :priority)
  end

  def find_track
    @track = Track.find(params[:id])
  end
end

Thanks in advance!

Body:
Since you render the page for Tracks#new action it should be

def new
  @tracks = Track.all
  @track = Track.new
end

and

<% @tracks.each do |track| %>

in view iterator. Also you need to add @tracks = Track.all to the create action, otherwise you will not be able render tracks table on validation error.

Note, by convention we use plural from for collections and single for single record. You need to have both @tracks and @track in the new action since you want to render all pages and create a new one.

Btw, do you use index action anywhere? If no, you can safely remove it from controller and routes.rb


问:
JNI system.loadlibrary problem - native C++ dll using C library
I have a pretty annoying compiling problem.

I am trying to do a System.loadlibrary on a C++ DLL in VS2010, which in turns uses a C DLL compiled in VS2008.

The error I am getting is:
java.lang.UnsatisfiedLinkError: The application has failed to start because
its side-by-side configuration is incorrect

This occurs whenever my C++ DLL tries to do a call to a function in the C DLL. Both compiles just fine, and both are in a folder accessible by Java Applet.

Is this possible to solve somehow? Do you need any more info?

答:
You should try and use the dependency walker on your DLLs.
From the side-by-side error I assume that one of the c runtime redist packages or one of the noredist packages is missing.
But the dep walker should show you this.

If this does not help you can get some more information from the event log of Windows since side by side errors are logged there, or you need to use sxstrace for more info.


问:
Async fetch of data not rerendering ReactJS datatable(or just not displaying new data)
The problem here is that, if my new data is fetched from my backend(RestAPI), the datatable does not display the new data even though I called this.setState and if I log the new state, the fetched data gets logged to the console, but is not displayed in my datatable.
When I hardcode the data in the constructors this.state = xxx, the data gets displayed just fine. So I think this has to be related to some rerendering problem? I debugged for hours, but I just couldn't find the problem. It would be really great if somebody could help me out here :)

I read very much articles and posts about not rerendering and the lifecycle of react components. As further info, when I log the state in the render method before the return values, it is at first null (as I initialised the state), and after the second rendering the data is in this.state.rowData as desired. But I simply cant find out why it doesnt get displayed in the datatable.

```<code>
    constructor(props) {
        super(props);
        this.state = {
            columnDefs: [{
                headerName: "Dump Name", field: "dumpName", sortable: true, filter: true
            }, {
                headerName: "Type", field: "type", sortable: true, filter: true
            }, {
                headerName: "Size", field: "length", sortable: true, filter: true
            }, {
                headerName: "Different CAN-IDs", field: "canIdCount", sortable: true, filter: true
            }, {
                headerName: "Created At", field: "createdAt", sortable: true, filter: true
            }],
            rowData: null
        }
    }

    componentDidMount = async () => {
        let collectionData = [];
        await getSniffs().then(function (sniffdata) {
            sniffdata.map(async function (row) {
                collectionData.push({
                    dumpName: row,
                    length: await getMessageCount(row).then(function (res) {
                        return res[0].all;
                    }),
                    canIdCount: await getIdCountDistinct(row).then(function (res) {
                        return res[0].count;
                    }),
                    createdAt: await getFirstTimestamp(row).then(function (res) {
                        return res[0].firstTimestamp;
                    }),
                    type: "CAN Message"
                });
            });
        }).then(() => this.setState({
            rowData: collectionData
        }));
    };

    render() {
        console.log(this.state);
        return (
            <div
                className="ag-theme-material"
                style={{
                    height: '500px',
                    width: '1000px' }}
            >
                <AgGridReact
                    // onRowClicked={this.onRowClicked.bind(this)}
                    columnDefs={this.state.columnDefs}
                    rowData={this.state.rowData}>
                </AgGridReact>
            </div>
            // : <Loading/>;
    )}
}

export default withRouter(SniffOverviewDatatable);

</code>```

The datatable just shows: No Row to show.
At first I think thats the correct result, but it should get updated and show my retrieved data.
The logs display exactly the desired data and array-structure.

Thanks for your time and I really hope to get some hints :)

EDIT:
Hey hey I just rewrote the componentDidMount function, but it didnt change a thing, im afraid. Data gets logged, but table doesnt get updated :/

Here is the new code of the function (used async/await):

```<code>componentDidMount = async () => {
            let rowData = [];
            try {
                const sniffs = await getSniffs();
                sniffs.map(async function (row) {
                    const msgCount = await getMessageCount(row);
                    const idCount = await getIdCountDistinct(row);
                    const firstTimestamp = await getFirstTimestamp(row);

                    rowData.push({
                        dumpName: row,
                        length: msgCount[0].all,
                        canIdCount: idCount[0].count,
                        createdAt: firstTimestamp[0].firstTimestamp,
                        type: "CAN Message"
                    });
                });
            } catch (e) {
                console.log(e);
            }
            this.setState({
                rowData
            });
        };
</code>```

答:
Have you already tried using setState with a callback function and some kind of immutability library such as immutability-helper? This would lead to code like this:</p>

```<code>import update from 'immutability-helper';
...

this.setState(prevState => update(prevState, {rowData: {$set: collectionData}});
...
</code>```

Body:
The problem here is that, if my new data is fetched from my backend(RestAPI), the datatable does not display the new data even though I called this.setState and if I log the new state, the fetched data gets logged to the console, but is not displayed in my datatable.
When I hardcode the data in the constructors this.state = xxx, the data gets displayed just fine. So I think this has to be related to some rerendering problem? I debugged for hours, but I just couldn't find the problem. It would be really great if somebody could help me out here :)

I read very much articles and posts about not rerendering and the lifecycle of react components. As further info, when I log the state in the render method before the return values, it is at first null (as I initialised the state), and after the second rendering the data is in this.state.rowData as desired. But I simply cant find out why it doesnt get displayed in the datatable.

    constructor(props) {
        super(props);
        this.state = {
            columnDefs: [{
                headerName: "Dump Name", field: "dumpName", sortable: true, filter: true
            }, {
                headerName: "Type", field: "type", sortable: true, filter: true
            }, {
                headerName: "Size", field: "length", sortable: true, filter: true
            }, {
                headerName: "Different CAN-IDs", field: "canIdCount", sortable: true, filter: true
            }, {
                headerName: "Created At", field: "createdAt", sortable: true, filter: true
            }],
            rowData: null
        }
    }

    componentDidMount = async () => {
        let collectionData = [];
        await getSniffs().then(function (sniffdata) {
            sniffdata.map(async function (row) {
                collectionData.push({
                    dumpName: row,
                    length: await getMessageCount(row).then(function (res) {
                        return res[0].all;
                    }),
                    canIdCount: await getIdCountDistinct(row).then(function (res) {
                        return res[0].count;
                    }),
                    createdAt: await getFirstTimestamp(row).then(function (res) {
                        return res[0].firstTimestamp;
                    }),
                    type: "CAN Message"
                });
            });
        }).then(() => this.setState({
            rowData: collectionData
        }));
    };

    render() {
        console.log(this.state);
        return (

                <AgGridReact
                    // onRowClicked={this.onRowClicked.bind(this)}
                    columnDefs={this.state.columnDefs}
                    rowData={this.state.rowData}>
                </AgGridReact>

            // : <Loading/>;
    )}
}

export default withRouter(SniffOverviewDatatable);

The datatable just shows: No Row to show.
At first I think thats the correct result, but it should get updated and show my retrieved data.
The logs display exactly the desired data and array-structure.

Thanks for your time and I really hope to get some hints :)

EDIT:
Hey hey I just rewrote the componentDidMount function, but it didnt change a thing, im afraid. Data gets logged, but table doesnt get updated :/

Here is the new code of the function (used async/await):

componentDidMount = async () => {
            let rowData = [];
            try {
                const sniffs = await getSniffs();
                sniffs.map(async function (row) {
                    const msgCount = await getMessageCount(row);
                    const idCount = await getIdCountDistinct(row);
                    const firstTimestamp = await getFirstTimestamp(row);

                    rowData.push({
                        dumpName: row,
                        length: msgCount[0].all,
                        canIdCount: idCount[0].count,
                        createdAt: firstTimestamp[0].firstTimestamp,
                        type: "CAN Message"
                    });
                });
            } catch (e) {
                console.log(e);
            }
            this.setState({
                rowData
            });
        };

Body:
Have you already tried using setState with a callback function and some kind of immutability library such as immutability-helper? This would lead to code like this:

import update from 'immutability-helper';
...

this.setState(prevState => update(prevState, {rowData: {$set: collectionData}});
...


问:
EOF inside string in big data
From iPython I run a read_csv on a relatively huge set of data (1gb++)

I am returned with

CParserError: Error tokenizing data. C error: EOF inside string starting at line 891743

I know there is an error with reading a particular string within the data but I just cannot dive down into detail to correct the error.

With reference from:

https://github.com/pydata/pandas/issues/5500

He dives down to the data level and corrects it there. But due to the size of the data I am working on, I cannot seem to get an idea on how I can correct the issue. I really cannot do the same.

答:
If you are using Linux, type into the terminal:

```<code>head -n891743 <filename> | tail -n1 > out
</code>```

This will write the 891743th row of your csv file into the "out" file.

Title: EOF inside string in big data

Body:
If you are using Linux, type into the terminal:

head -n891743 <filename> | tail -n1 > out

This will write the 891743th row of your csv file into the "out" file.


问:
Custom date range inline picker
Framework which I use (Angular 7) and ngx-bootstrap ^4.0.0

I want  to  make inline daterangepicker.

Package ngx-bootstrap have inline  datepicker (bs-datepicker-inline) and directive (bsDaterangepicker) for classic dialog daterangepicker.

I try use attribute container for  create daterangepicker in element wth relative position, but after select date is component closed. When i use hide event call method show, it's working but with 'blink'.

Do you have any experience with it?

Here is example.

答:
you can use the bsDatepicker from ngx-bootstrap like as shown below

```<code><input type="text"
            class="form-control"
            [minDate]="minDate"
            [maxDate]="maxDate"
            #dp="bsDatepicker"
            bsDatepicker [(bsValue)]="myDateValue">
</code>```

Working Demo

Title: Custom date range inline picker

Body:
you can use the bsDatepicker from ngx-bootstrap like as shown below

<input type="text"
            class="form-control"
            [minDate]="minDate"
            [maxDate]="maxDate"
            #dp="bsDatepicker"
            bsDatepicker [(bsValue)]="myDateValue">

Working Demo


问:
Presenting a fullscreen style view controller on top of a custom presentation style view controller, how to trigger viewDidDisappear?
I have a custom presentation style view controller B, modal presentation style set to UIModalPresentationCustom. I have presented B on vc A modally.

Now, on B I present a new vc C (modally) with UIModalPresentationFullscreen, B being the source now. How can I make sure that viewDidAppear/Disappear does get called on B and subsequently on A.

I am not using Storyboards. All of this is done programmatically.

答:
If your view controllers are set up in storyboard, you could do the following:

You could use an unwind segue:

In the viewController to that you want to return to, insert

```<code>@IBAction func unwindToTargetVC(segue: UIStoryboardSegue) { }
</code>```

In StoryBoard, go to the viewController from that you want to return and control-drag the viewController icon to the exit icon in the top bar.

You will be presented with IBAction options. Select here the unwind segue action that you have defined in your target viewController.

In the document outline of your viewController select the unwind segue and open to the attributes inspector. Enter here as identifier the name of your unwind segue.

Eventually you can trigger the segue, i.e. the return to your target viewController, by the following code:

```<code>@IBAction func returnToTargetViewControler(_ sender: Any) {
     performSegue(withIdentifier: "unwindToTargetVC", sender: self)
}
</code>```

Body:
If your view controllers are set up in storyboard, you could do the following:

You could use an unwind segue:

In the viewController to that you want to return to, insert

@IBAction func unwindToTargetVC(segue: UIStoryboardSegue) { }

In StoryBoard, go to the viewController from that you want to return and control-drag the viewController icon to the exit icon in the top bar.

You will be presented with IBAction options. Select here the unwind segue action that you have defined in your target viewController.

In the document outline of your viewController select the unwind segue and open to the attributes inspector. Enter here as identifier the name of your unwind segue.

Eventually you can trigger the segue, i.e. the return to your target viewController, by the following code:

@IBAction func returnToTargetViewControler(_ sender: Any) {
     performSegue(withIdentifier: "unwindToTargetVC", sender: self)
}


问:
Map array values to collection of items
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

```<code>$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];
</code>```

The collection :

```<code> $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);
</code>```

The end result :

```<code>$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];
</code>```

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

答:
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).</p>

```<code>$result = $items->map(function($item) use ($baseMap) {
    $array = [];

    foreach($baseMap as $oldKey => $newKey){
        if(isset($item[$oldKey])){
            $array[$newKey] = $item[$oldKey];
        }
    }

    return $array;
});

$result = $result->toArray();
</code>```

Title: Map array values to collection of items

Body:
How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap  as keys to the collection.

The baseMap :

$baseMap = [
            'name' => 'new_name',
            'year' => 'new_year',
        ];

The collection :

 $items = collect([
            [
                'name' => 'name1',
                'year' => '1000',
                'not_in_basemap' => 'foo'
            ],
            [
                'name' => 'name2',
                'year' => '2000',
                'not_in_basemap' => 'foo'
            ],
            //...
        ]);

The end result :

$result =[
            [
                'new_name' => 'name1',
                'new_year' => '1000',

            ],
            [
                'new_name'=> 'name2',
                'new_year' => '2000',

            ],
        ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

Body:
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).

$result = $items->map(function($item) use ($baseMap) {
    $array = [];

    foreach($baseMap as $oldKey => $newKey){
        if(isset($item[$oldKey])){
            $array[$newKey] = $item[$oldKey];
        }
    }

    return $array;
});

$result = $result->toArray();


问:
Pandas does not read CSV as it write it
I created a dataframe, and i wanted to export it as a CSV. i used the
df.to_csv() method.

When i read my csv that i created it's not parsed well and i have some
values of columns mixed between each others.

I tried to change the encoding, as well as the delimiter, but it
doesn't solve my problem.

here is a sample of my dataframe before being exported as a CSV :

```<code>                                           societe  ...     cluster
    6                      ACTION AIR ENVIRONNEMENT  ...  aquavalley
    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...  aquavalley
    9                                     ADEQUABIO  ...  aquavalley
    10                              ADICT SOLUTIONS  ...  aquavalley
</code>```

then i use to export it :

```<code>csv_df.to_csv(r"path.csv", sep="\t")
</code>```

and to read it :

```<code>pd.read_csv(r"path.csv", sep="\t", engine='python')
</code>```

and i obtain something like that

```<code>    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...        None
    215 Rue         34000 Mont...    contact@cc.com  ...        None
    9                                     ADEQUABIO  ...  aquavalley

</code>```

答:
Thank you for your fast answers. I solved my problem.

I thought i got rid of carriage return '\r' and new line '\n' by using df.replace('\r',' ') but it didn't work(still don't know why), so they were still here when i thought they were not.

Instead i used :

```<code>df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=[" "," "], regex=True)
</code>```

and after getting rid of it, i don't have any problem.

Thanks again for your help.

Title: Pandas does not read CSV as it write it

Body:
I created a dataframe, and i wanted to export it as a CSV. i used the
df.to_csv() method.

When i read my csv that i created it's not parsed well and i have some
values of columns mixed between each others.

I tried to change the encoding, as well as the delimiter, but it
doesn't solve my problem.

here is a sample of my dataframe before being exported as a CSV :

                                           societe  ...     cluster
    6                      ACTION AIR ENVIRONNEMENT  ...  aquavalley
    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...  aquavalley
    9                                     ADEQUABIO  ...  aquavalley
    10                              ADICT SOLUTIONS  ...  aquavalley

then i use to export it :

csv_df.to_csv(r"path.csv", sep="\t")

and to read it :

pd.read_csv(r"path.csv", sep="\t", engine='python')

and i obtain something like that

    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...        None
    215 Rue         34000 Mont...    contact@cc.com  ...        None
    9                                     ADEQUABIO  ...  aquavalley

Body:
Thank you for your fast answers. I solved my problem.

I thought i got rid of carriage return '\r' and new line '\n' by using df.replace('\r',' ') but it didn't work(still don't know why), so they were still here when i thought they were not.

Instead i used :

df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=[" "," "], regex=True)

and after getting rid of it, i don't have any problem.

Thanks again for your help.