问:
Paste Range of filtered data in columns in the same order/format
I have the working code below that copies filtered data to filtered cells when I select data from one column.

When I try a range of multiple columns it copies the data back in a single column and pastes is like so: column1V1, column1V2, column1V3, etc

How can I paste the filtered data in the same order/format in other columns?

```<code>Sub Filtered_Cells()

    Dim from As Range

    Set from = Application.InputBox("Select range to copy selected cells to", Type:=8)

    from.Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Call Copy_Filtered_Cells

End Sub

Sub Copy_Filtered_Cells()

    Set from = Selection
    Set too = Application.InputBox("Select range to copy selected cells to", Type:=8)

    For Each Cell In from
        Cell.Copy
        For Each thing In too
            If thing.EntireRow.RowHeight > 0 Then
                thing.PasteSpecial
                Set too = thing.Offset(1).Resize(too.Rows.Count)
                Exit For
            End If
        Next
    Next

End Sub
</code>```

答:
Would this work for you?

Sub Copy_Filtered_Cells_New()

Dim from As Range, too As Range, fromRng As Range
Set from = Application.InputBox("Select range to copy cells from", Type:=8)
Set too = Application.InputBox("Select range to paste cells to", Type:=8)
Dim ws As Worksheet: Set ws = from.Worksheet
Dim arrRanges() As String: arrRanges = Split(from.SpecialCells(xlCellTypeVisible).address, ",")

Dim R As Long, X As Long, nextVisRow As Long

    For X = LBound(arrRanges) To UBound(arrRanges)  'For each visible range
        Set fromRng = ws.Range(arrRanges(X))
        With fromRng
            For R = 1 To .Rows.Count  'For each row in the selected range
                nextVisRow = NextVisibleRow(too.Cells(1, 1)) 'Get the next visible row for paste

                too.Offset(nextVisRow - too.row).Resize(1, .Columns.Count).Value = .Offset(R - 1).Resize(1, .Columns.Count).Value
                Set too = too.Offset(nextVisRow - too.row + 1)
            Next R
        End With
    Next X

End Sub

Function NextVisibleRow(rng As Range) As Long

Dim ws As Worksheet: Set ws = rng.Worksheet
Dim R As Long: R = rng.Cells(1, 1).row

    Do While True
        If Not ws.Rows(R).EntireRow.Hidden Then
            NextVisibleRow = R
            Exit Do
        End If
        R = R + 1
    Loop

End Function
```

Body:
I have the working code below that copies filtered data to filtered cells when I select data from one column.

When I try a range of multiple columns it copies the data back in a single column and pastes is like so: column1V1, column1V2, column1V3, etc

How can I paste the filtered data in the same order/format in other columns?

Sub Filtered_Cells()

    Dim from As Range

    Set from = Application.InputBox("Select range to copy selected cells to", Type:=8)

    from.Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Call Copy_Filtered_Cells

End Sub

Sub Copy_Filtered_Cells()

    Set from = Selection
    Set too = Application.InputBox("Select range to copy selected cells to", Type:=8)

    For Each Cell In from
        Cell.Copy
        For Each thing In too
            If thing.EntireRow.RowHeight > 0 Then
                thing.PasteSpecial
                Set too = thing.Offset(1).Resize(too.Rows.Count)
                Exit For
            End If
        Next
    Next

End Sub


来源: stackexchange

问:
Android XML Parsing error: Only one root element allowed
I want to parse an XML. I am posting my XML response below. In the
pre tag I am getting a JSON which i want to print but I am not able to parse with my code. I am posting my code to parse this XML.

```<code>private void xmlParsing(String qrCode) {
        try {
            qrCode = qrCode.replaceAll("[^\\x20-\\x7e]", "");
            //loge("qrCode : " + qrCode);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(qrCode.getBytes("utf-8")));

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("head");
            loge("--df--nList.getLength()---"+nList.getLength());
            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;

                }
            }

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

<head></head>
<body>
    <pre style="word-wrap: break-word; white-space: pre-wrap;">{"status":true,"message":"Login Successfull","data":{"user":{"id":2,"name":"Rommy Garg","email":"rommy@signitysolutions.com","user_group_id":"2","company_id":2,"last_login":"2019-05-29 05:48:27","last_logout":"2019-05-28 10:33:39","profile_pic":null,"created_at":"2018-12-20 10:12:23","updated_at":"2019-05-29 05:48:27","sf_reference_id":"0056F00000BqMZSQA3","sf_setup":1},"company_logo":"http:\/\/staging.sales-chap.com\/dist\/uploads\/company\/1545300743.jpg","client_id":1,"client_secret":"IQ09J2BdDuc3lSKUJlQAp8uhCXRq+s2EucsBOb9rfjo="}}```

```

but I am getting below error:

org.w3c.dom.DOMException: Only one root element allowed

答:
Well, as the error said, XML only allows a single root element. You could create a fake one around the string you recieve:</p>

```<code>qrCode = "<html>" + qrCode + "</html>";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to parse an XML. I am posting my XML response below. In the
pre tag I am getting a JSON which i want to print but I am not able to parse with my code. I am posting my code to parse this XML.

private void xmlParsing(String qrCode) {
        try {
            qrCode = qrCode.replaceAll("[^\\x20-\\x7e]", "");
            //loge("qrCode : " + qrCode);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(qrCode.getBytes("utf-8")));

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("head");
            loge("--df--nList.getLength()---"+nList.getLength());
            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;

                }
            }

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

{"status":true,"message":"Login Successfull","data":{"user":{"id":2,"name":"Rommy Garg","email":"rommy@signitysolutions.com","user_group_id":"2","company_id":2,"last_login":"2019-05-29 05:48:27","last_logout":"2019-05-28 10:33:39","profile_pic":null,"created_at":"2018-12-20 10:12:23","updated_at":"2019-05-29 05:48:27","sf_reference_id":"0056F00000BqMZSQA3","sf_setup":1},"company_logo":"http:\/\/staging.sales-chap.com\/dist\/uploads\/company\/1545300743.jpg","client_id":1,"client_secret":"IQ09J2BdDuc3lSKUJlQAp8uhCXRq+s2EucsBOb9rfjo="}}

but I am getting below error:

org.w3c.dom.DOMException: Only one root element allowed

Body:
Well, as the error said, XML only allows a single root element. You could create a fake one around the string you recieve:

qrCode = "<html>" + qrCode + "</html>";


问:
Saving Carbon from string to MySQL
I'm having trouble saving a timestamp to my MySQL database. In this case, the user writes a date in a text field, with the format dd/mm/yyyy, and I want it to be saved as a timestamp.

The problem is, it is always complaining about incorrect format.

So far, I've tried:

```<code>$d = DateTime::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");

// or
$d = Carbon::parse($request['b_date']);

// or

$d = Carbon::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");

// so that I can
$p->b_date = $d;
</code>```

But it never lets me save it.
Here's the log:

```<code>[2019-05-29 15:14:02] local.ERROR: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1111-11-11 00:00:00' for column 'b_date' at row 1 ...
</code>```

I've been trying to do this for hours. What am I missing?

And how can '1111-11-11 00:00:00' be an invalid datetime value?

答:
Declaring the datatype as DateTime in the migrations script worked for me.

```<code>    ...

    Schema::create(...

        $table->dateTime('b_date'); // use dateTime instead of timestamp

        ...
</code>```

Setting it with carbon in the controller:

```<code>...

$p->b_date = Carbon::createFromFormat("d/m/Y H:i:s", $input['b_date'] . " 00:00:00");

...
</code>```

Title: Saving Carbon from string to MySQL

Body:
I'm having trouble saving a timestamp to my MySQL database. In this case, the user writes a date in a text field, with the format dd/mm/yyyy, and I want it to be saved as a timestamp.

The problem is, it is always complaining about incorrect format.

So far, I've tried:

$d = DateTime::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");

// or
$d = Carbon::parse($request['b_date']);

// or

$d = Carbon::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");

// so that I can
$p->b_date = $d;

But it never lets me save it.
Here's the log:

[2019-05-29 15:14:02] local.ERROR: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1111-11-11 00:00:00' for column 'b_date' at row 1 ...

I've been trying to do this for hours. What am I missing?

And how can '1111-11-11 00:00:00' be an invalid datetime value?

Body:
Declaring the datatype as DateTime in the migrations script worked for me.

    ...

    Schema::create(...

        $table->dateTime('b_date'); // use dateTime instead of timestamp

        ...

Setting it with carbon in the controller:

...

$p->b_date = Carbon::createFromFormat("d/m/Y H:i:s", $input['b_date'] . " 00:00:00");

...


答:
you can do it by generating a class convert it in java object of list.

first generate a class

-----------------------------------com.example.Example.java-----------------------------------

```<code>package com.example;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Example implements Serializable
{

@SerializedName("docmanId")
@Expose
private long docmanId;
@SerializedName("dz")
@Expose
private String dz;
private final static long serialVersionUID = 3195470113916852896L;

/**
* No args constructor for use in serialization
*
*/
public Example() {
}

/**
*
* @param docmanId
* @param dz
*/
public Example(long docmanId, String dz) {
super();
this.docmanId = docmanId;
this.dz = dz;
}

public long getDocmanId() {
return docmanId;
}

public void setDocmanId(long docmanId) {
this.docmanId = docmanId;
}

public Example withDocmanId(long docmanId) {
this.docmanId = docmanId;
return this;
}

public String getDz() {
return dz;
}

public void setDz(String dz) {
this.dz = dz;
}

public Example withDz(String dz) {
this.dz = dz;
return this;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("docmanId", docmanId).append("dz", dz).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(docmanId).append(dz).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Example) == false) {
return false;
}
Example rhs = ((Example) other);
return new EqualsBuilder().append(docmanId, rhs.docmanId).append(dz, rhs.dz).isEquals();
}

}
Now Tell it to parse a List (of Welcome) instead. Since List is generic you will typically use a **TypeReference**
List<Welcome> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Welcome>>(){});
</code>```

use http://www.jsonschema2pojo.org/ to convert your json to java class.

Title: How to get each value from JSON string

Body:
I have this JSON String and I need to get each docmanId and each dz so,I could loop through them and work with them.

I have tried using gson library to do that,but I dont seem to figure it out.

JSON Array :

[{"docmanId":1,"dz":"CR"},
{"docmanId":1,"dz":"EU"},
{"docmanId":1,"dz":"JD"},
{"docmanId":1,"dz":"LT"},
{"docmanId":10,"dz":"CR"},
{"docmanId":10,"dz":"EU"},
{"docmanId":10,"dz":"LT"},
{"docmanId":100,"dz":"CR"},
{"docmanId":100,"dz":"EU"},
{"docmanId":100,"dz":"JD"},
{"docmanId":100,"dz":"LT"},
{"docmanId":1000,"dz":"CR"},
{"docmanId":1000,"dz":"EU"},
{"docmanId":1000,"dz":"JD"},
{"docmanId":1000,"dz":"LT"},
{"docmanId":10000,"dz":"ES"},
{"docmanId":10000,"dz":"EU"},
{"docmanId":10000,"dz":"JD"},
{"docmanId":100000,"dz":"CR"},
{"docmanId":100000,"dz":"EU"},
{"docmanId":100000,"dz":"JD"},
{"docmanId":100000,"dz":"LT"},
{"docmanId":100001,"dz":"CR"},
{"docmanId":100001,"dz":"EU"},
{"docmanId":100001,"dz":"LT"},
{"docmanId":100002,"dz":"CR"},
{"docmanId":100002,"dz":"EU"},
{"docmanId":100002,"dz":"JD"},
{"docmanId":100003,"dz":"CR"},
{"docmanId":100003,"dz":"EU"},
{"docmanId":100003,"dz":"JD"},
{"docmanId":100003,"dz":"LT"},
{"docmanId":100004,"dz":"CR"},
{"docmanId":100004,"dz":"EU"},
{"docmanId":100004,"dz":"JD"},
{"docmanId":100005,"dz":"CR"},
{"docmanId":100005,"dz":"EU"},
{"docmanId":100005,"dz":"JD"},
{"docmanId":100005,"dz":"LT"},
{"docmanId":100006,"dz":"CR"},
{"docmanId":100006,"dz":"EU"},
{"docmanId":100006,"dz":"JD"},
{"docmanId":100006,"dz":"LT"},
{"docmanId":100007,"dz":"CR"},
{"docmanId":100007,"dz":"EU"},
{"docmanId":100007,"dz":"JD"}]

Body:
you can do it by generating a class convert it in java object of list.

first generate a class

-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Example implements Serializable
{

@SerializedName("docmanId")
@Expose
private long docmanId;
@SerializedName("dz")
@Expose
private String dz;
private final static long serialVersionUID = 3195470113916852896L;

/**
* No args constructor for use in serialization
*
*/
public Example() {
}

/**
*
* @param docmanId
* @param dz
*/
public Example(long docmanId, String dz) {
super();
this.docmanId = docmanId;
this.dz = dz;
}

public long getDocmanId() {
return docmanId;
}

public void setDocmanId(long docmanId) {
this.docmanId = docmanId;
}

public Example withDocmanId(long docmanId) {
this.docmanId = docmanId;
return this;
}

public String getDz() {
return dz;
}

public void setDz(String dz) {
this.dz = dz;
}

public Example withDz(String dz) {
this.dz = dz;
return this;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("docmanId", docmanId).append("dz", dz).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(docmanId).append(dz).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Example) == false) {
return false;
}
Example rhs = ((Example) other);
return new EqualsBuilder().append(docmanId, rhs.docmanId).append(dz, rhs.dz).isEquals();
}

}
Now Tell it to parse a List (of Welcome) instead. Since List is generic you will typically use a **TypeReference**
List<Welcome> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Welcome>>(){});

use http://www.jsonschema2pojo.org/ to convert your json to java class.


问:
google spreadsheet freeze column and row
I have google spreadsheet with some schedules.

I froze first 3 lines.

Question:

How can I froze last column in same sheet?

Note: want to froze RED area

Output:

答:
Answer given by @Vasim is wrong!

That answer sheet.setFrozenColumns(X) refer to total number of rows X to freeze from left end of the sheet.

So answer to your question is YOU CAN'T, right most columns cannot be frozen in GSheets,

hope this helps future interweb jedi!

p.s. (I's sure would like that this feature exists in GS)

ContentLicense: CC BY-SA 3.0


问:
PHP iMagick image compression
I'm fairly new to iMagick and have only found very limited documentation on the PHP library.  I'm happily resizing images and writing them back to the hard drive, but I'm failing completely to compress the images using JPG for instance.

This is the code I'm using so far:

```<code>function scale_image($size = 200,$extension)
{
    if(!file_exists(ALBUM_PATH . $this->path . $this->filename . $extension))
    {
        $im = new imagick(ALBUM_PATH . $this->path . $this->filename);

        $width = $im->getImageWidth();
        $height = $im->getImageHeight();
        if($width > $height)
            $im->resizeImage($size, 0, imagick::FILTER_LANCZOS, 1);
        else
            $im->resizeImage(0 , $size, imagick::FILTER_LANCZOS, 1);

        $im->setImageCompression(true);
        $im->setCompression(Imagick::COMPRESSION_JPEG);
        $im->setCompressionQuality(20);

        $im->writeImage(ALBUM_PATH . $this->path . $this->filename . $extension);
        $im->clear();
        $im->destroy();
    }
}
</code>```

答:
The full list of compression formats from a source code:

```<code>const COMPRESSION_NO = 1;
const COMPRESSION_BZIP = 2;
const COMPRESSION_FAX = 6;
const COMPRESSION_GROUP4 = 7;
const COMPRESSION_JPEG = 8;
const COMPRESSION_JPEG2000 = 9;
const COMPRESSION_LOSSLESSJPEG = 10;
const COMPRESSION_LZW = 11;
const COMPRESSION_RLE = 12;
const COMPRESSION_ZIP = 13;
const COMPRESSION_DXT1 = 3;
const COMPRESSION_DXT3 = 4;
const COMPRESSION_DXT5 = 5;
const COMPRESSION_ZIPS = 14;
const COMPRESSION_PIZ = 15;
const COMPRESSION_PXR24 = 16;
const COMPRESSION_B44 = 17;
const COMPRESSION_B44A = 18;
const COMPRESSION_LZMA = 19;
const COMPRESSION_JBIG1 = 20;
const COMPRESSION_JBIG2 = 21;
</code>```

Original documentation: http://www.imagemagick.org/script/command-line-options.php#compress

Title: PHP iMagick image compression

Body:
I'm fairly new to iMagick and have only found very limited documentation on the PHP library.  I'm happily resizing images and writing them back to the hard drive, but I'm failing completely to compress the images using JPG for instance.

This is the code I'm using so far:

function scale_image($size = 200,$extension)
{
    if(!file_exists(ALBUM_PATH . $this->path . $this->filename . $extension))
    {
        $im = new imagick(ALBUM_PATH . $this->path . $this->filename);

        $width = $im->getImageWidth();
        $height = $im->getImageHeight();
        if($width > $height)
            $im->resizeImage($size, 0, imagick::FILTER_LANCZOS, 1);
        else
            $im->resizeImage(0 , $size, imagick::FILTER_LANCZOS, 1);

        $im->setImageCompression(true);
        $im->setCompression(Imagick::COMPRESSION_JPEG);
        $im->setCompressionQuality(20);

        $im->writeImage(ALBUM_PATH . $this->path . $this->filename . $extension);
        $im->clear();
        $im->destroy();
    }
}

Body:
The full list of compression formats from a source code:

const COMPRESSION_NO = 1;
const COMPRESSION_BZIP = 2;
const COMPRESSION_FAX = 6;
const COMPRESSION_GROUP4 = 7;
const COMPRESSION_JPEG = 8;
const COMPRESSION_JPEG2000 = 9;
const COMPRESSION_LOSSLESSJPEG = 10;
const COMPRESSION_LZW = 11;
const COMPRESSION_RLE = 12;
const COMPRESSION_ZIP = 13;
const COMPRESSION_DXT1 = 3;
const COMPRESSION_DXT3 = 4;
const COMPRESSION_DXT5 = 5;
const COMPRESSION_ZIPS = 14;
const COMPRESSION_PIZ = 15;
const COMPRESSION_PXR24 = 16;
const COMPRESSION_B44 = 17;
const COMPRESSION_B44A = 18;
const COMPRESSION_LZMA = 19;
const COMPRESSION_JBIG1 = 20;
const COMPRESSION_JBIG2 = 21;

Original documentation: http://www.imagemagick.org/script/command-line-options.php#compress


问:
SwipeRefreshLayout trigger programmatically
Is there any way to trigger the SwipeRefreshLayout programmatically? The animation should start and the onRefresh method from the OnRefreshListener interface should get called.

答:
```<code>binding.swipeRefreshLayout.setRefreshing(true); // show loading
binding.swipeRefreshLayout.post(this::updateUI); // call method
binding.swipeRefreshLayout.setOnRefreshListener(this::updateUI); // call method
</code>```


问:
Countdown using jquery
I'm working on countdown it's working fine actually now I want to add 0 from 0-9 single digit every single digit I want to append 0. Now it is coming with a single digit like 6 hrs I want to be 06 hrs. Can anyone suggest to me.

const second = 1000,
  minute = second * 60,
  hour = minute * 60,
  day = hour * 24;

let countDown = new Date('July 17, 2019 00:00:00').getTime(),
  x = setInterval(function() {

    let now = new Date().getTime(),
      distance = countDown - now;

    document.getElementById('days').innerText = Math.floor(distance / (day)),
      document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
      document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
      document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);
  }, second)
if (second < 10 && minute < 10 && hour < 10 && day < 10) {
  countDown = "0" + countDown;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popup-counter {
 display: flex;
 }</code>```

Days

Hours

Minutes

Seconds

```

答:
Try like this.

Assign the values to the variable and check like it is less than 10 add a zero before it else leave as it is.

(hours < 10)?'0'+hours:hours,

const second = 1000,
  minute = second * 60,
  hour = minute * 60,
  day = hour * 24;

let countDown = new Date('July 17, 2019 00:00:00').getTime(),
  x = setInterval(function() {

    let now = new Date().getTime(),
      distance = countDown - now;
    var hours =  Math.floor((distance % (day)) / (hour));
    var days =  Math.floor(distance / (day));
    var minutes =  Math.floor((distance % (hour)) / (minute));
    var seconds =  Math.floor((distance % (minute)) / second);
    document.getElementById('days').innerText = (days < 10 )?'0'+days:days,
      document.getElementById('hours').innerText = (hours < 10)?'0'+hours:hours,
      document.getElementById('minutes').innerText = (minutes < 10)?'0'+minutes:minutes,
      document.getElementById('seconds').innerText = (seconds < 10)?'0'+seconds:seconds;
  }, second)
if (second < 10 && minute < 10 && hour < 10 && day < 10) {
  countDown = "0" + countDown;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popup-counter {
 display: flex;
 }</code>```

Days

Hours

Minutes

Seconds

```

Title: Countdown using jquery

Body:
I'm working on countdown it's working fine actually now I want to add 0 from 0-9 single digit every single digit I want to append 0. Now it is coming with a single digit like 6 hrs I want to be 06 hrs. Can anyone suggest to me.

const second = 1000,
  minute = second * 60,
  hour = minute * 60,
  day = hour * 24;

let countDown = new Date('July 17, 2019 00:00:00').getTime(),
  x = setInterval(function() {

    let now = new Date().getTime(),
      distance = countDown - now;

    document.getElementById('days').innerText = Math.floor(distance / (day)),
      document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
      document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
      document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);
  }, second)
if (second < 10 && minute < 10 && hour < 10 && day < 10) {
  countDown = "0" + countDown;
}

.popup-counter {
 display: flex;
 }

Days

Hours

Minutes

Seconds

Body:
Try like this.

Assign the values to the variable and check like it is less than 10 add a zero before it else leave as it is.

(hours < 10)?'0'+hours:hours,

const second = 1000,
  minute = second * 60,
  hour = minute * 60,
  day = hour * 24;

let countDown = new Date('July 17, 2019 00:00:00').getTime(),
  x = setInterval(function() {

    let now = new Date().getTime(),
      distance = countDown - now;
    var hours =  Math.floor((distance % (day)) / (hour));
    var days =  Math.floor(distance / (day));
    var minutes =  Math.floor((distance % (hour)) / (minute));
    var seconds =  Math.floor((distance % (minute)) / second);
    document.getElementById('days').innerText = (days < 10 )?'0'+days:days,
      document.getElementById('hours').innerText = (hours < 10)?'0'+hours:hours,
      document.getElementById('minutes').innerText = (minutes < 10)?'0'+minutes:minutes,
      document.getElementById('seconds').innerText = (seconds < 10)?'0'+seconds:seconds;
  }, second)
if (second < 10 && minute < 10 && hour < 10 && day < 10) {
  countDown = "0" + countDown;
}

.popup-counter {
 display: flex;
 }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="popup-counter">
  <div class="counter-timings">
    <div class="counter" id="days"></div>
    <h4>Days</h4>
  </div>
  <div class="counter-timings">
    <div class="counter" id="hours"></div>
    <h4>Hours</h4>
  </div>
  <div class="counter-timings">
    <div class="counter" id="minutes"></div>
    <h4>Minutes</h4>
  </div>
  <div class="counter-timings">
    <div class="counter" id="seconds"></div>
    <h4>Seconds</h4>
  </div>
</div>


问:
Django Template's Date Filter Causes Form Values To Disappear
I'm facing a weird dilemma. Django date:"Y/m/d" filter prevents the form values to show up if the form is not validated. Here's my ModelForm:

```<code>DATE_INPUT_FORMATS = ['%Y/%m/%d', '%Y-%m-%d']

class PromotionModelForm(ModelForm):
    last_promotion_date =
forms.DateField(input_formats=DATE_INPUT_FORMATS)

    class Meta:
        model = Professor
        fields = ['last_promotion_date']
</code>```

Here's my view:

```<code>def first-view(request):
    professor = get_object_or_404(Professor,
user__username=request.user)
    form = SomeForm(request.POST or None, instance=professor)
    if form.is_valid():
        form.save()
        context = {"form": form}
        return redirect('/first-view')
    else:
        return render(request, 'core/first-view.html',
context={'form':form})
</code>```

and here's the template:

```<code><form class="inner_box" method="POST" action="{% url 'core:first_view' %}" name="">
            {% csrf_token %}
          <table>
            <tr class="table_header">
              <th colspan="8" class="right">last_promotion_date</th>
              <td><input type="text" name="last_promotion_date" onfocus="displayDatePicker(this.id);" class="date_picker" value="{{ form.last_promotion_date.value|date:"Y/m/d"}}"</td>
            </tr>
</form>
</code>```

And here's the problem
if the form is not valid, and if I keep the date:"Y/m/d" filter, the form values which have that filter do not show up in the rendered response.
However, if I remove the date:"Y/m/d" filter from the template variables, the form is rendered including the invalid input.

The problem with the date:"Y/m/d" filter happens only when the form is not validated. The very same date values that get rendered in a 'GET' request, disappear in the response of a 'POST" request if the form is not validated.

It's quite puzzling. What am I missing here? Why the invalid form's values do not appear in the presence of date:"Y/m/d" filter?

答: If field won't validate, it's value probably won't be proper date object or anything that can be parsed to valid date. That's why using |date on value won't produce any result.

Body:
I'm facing a weird dilemma. Django date:"Y/m/d" filter prevents the form values to show up if the form is not validated. Here's my ModelForm:

DATE_INPUT_FORMATS = ['%Y/%m/%d', '%Y-%m-%d']

class PromotionModelForm(ModelForm):
    last_promotion_date =
forms.DateField(input_formats=DATE_INPUT_FORMATS)

    class Meta:
        model = Professor
        fields = ['last_promotion_date']

Here's my view:

def first-view(request):
    professor = get_object_or_404(Professor,
user__username=request.user)
    form = SomeForm(request.POST or None, instance=professor)
    if form.is_valid():
        form.save()
        context = {"form": form}
        return redirect('/first-view')
    else:
        return render(request, 'core/first-view.html',
context={'form':form})

and here's the template:

<form class="inner_box" method="POST" action="{% url 'core:first_view' %}" name="">
            {% csrf_token %}

              last_promotion_date
              <input type="text" name="last_promotion_date" onfocus="displayDatePicker(this.id);" class="date_picker" value="{{ form.last_promotion_date.value|date:"Y/m/d"}}"

</form>

And here's the problem
if the form is not valid, and if I keep the date:"Y/m/d" filter, the form values which have that filter do not show up in the rendered response.
However, if I remove the date:"Y/m/d" filter from the template variables, the form is rendered including the invalid input.

The problem with the date:"Y/m/d" filter happens only when the form is not validated. The very same date values that get rendered in a 'GET' request, disappear in the response of a 'POST" request if the form is not validated.

It's quite puzzling. What am I missing here? Why the invalid form's values do not appear in the presence of date:"Y/m/d" filter?


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
Try this with LINQ,</p>

```<code>int num = 92345;
            string strNum = Convert.ToString(num);

            var divisibleby2 = from c in strNum
                               where int.Parse(c.ToString()) % 2 == 0
                               select c.ToString();

            var notDivisibleby2 = from c in strNum
                               where int.Parse(c.ToString()) % 2 != 0
                                  select c.ToString();

            int int_divisibleby2num = int.Parse(String.Join("", divisibleby2.ToArray()));
            int int_Notdivisibleby2num = int.Parse(String.Join("", notDivisibleby2.ToArray()));
</code>```

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
Try this with LINQ,

int num = 92345;
            string strNum = Convert.ToString(num);

            var divisibleby2 = from c in strNum
                               where int.Parse(c.ToString()) % 2 == 0
                               select c.ToString();

            var notDivisibleby2 = from c in strNum
                               where int.Parse(c.ToString()) % 2 != 0
                                  select c.ToString();

            int int_divisibleby2num = int.Parse(String.Join("", divisibleby2.ToArray()));
            int int_Notdivisibleby2num = int.Parse(String.Join("", notDivisibleby2.ToArray()));


问:
Xamarin Forms: maintain selected tab over activity restarts
My main page uses a TabbedPage to group existing news into different lists. The tabs aren't fixed; they're built from a data binding operations against a collection that's retried through a web service call.

I'd like to persist the selected tab across activity restarts, but it seems like I'm missing something. Since there's no selected tab property (which can be set through data binding), I've tried to handle the PageChanged and the CurrentPageChangedCommand events. I'm using the PageChanged to set the selected tab to the previous selected tab and the CurrentPageChangedCommand is being used to update the persisted selected tab (I'm using the Application.Properties to make sure the selected tab survives app restarts).

Unfortunately, the events generated by the tab will always set tab 0 as the selected tab! Here's what I'm seeing (let's assume that my app was killed white tab 3 was active):

When data is bound to the TabbedPage.ItemsSource property, the tab will automatically fire the CurrentPageChangedCommand, passing the first tab (tab at position 0).

My code handles the event and updates the current persisted selected tab by changing the selected tab in the Properties dictionary. So now, instead of 3 (which was the value persisted when my app was killed), it will have 0.

Then the tab will fire the PagesChanged

When my code handles this event, it will try to update the selected tab. However, when it access the selected tab from the Properties dictionary, it will get the default tab (0) and not 3. This happens because the CurrentPageChangedCommand was fired before the PagesChanged event (step 2), completely overriding the previously persisted tab index.

This default behaviour will also give a bad user experience when the user refreshes the current list (pull to refresh) because he always ends up seeing tab 0 list.

So, any clues on how to solve this? How have you guys solved this?

Thanks.

答:
It seems it can't be achieved using MVVM as CurrentPage is not a bindable property and CurrentPageChanged is an event.

However, there's no need to handle the PagesChanged event. You could record the index in the changed event like:

```<code>private void MyTabbedPage_CurrentPageChanged(object sender, EventArgs e)
{
    Application.Current.Properties["index"] = this.Children.IndexOf(CurrentPage);
    Application.Current.SavePropertiesAsync();
}
</code>```

Then you could set your tabbed page's current page after you have loaded all the tabs:

```<code>object index;
Application.Current.Properties.TryGetValue("index", out index);
if (index != null)
{
    CurrentPage = Children[int.Parse(index.ToString())];
}
// Subscribe the event
CurrentPageChanged += MyTabbedPage_CurrentPageChanged;
</code>```

I placed the code above in the custom tabbed page's constructor and it could change the selected tab at initial time.

Update:

If you want to change the tabbed page's children dynamically, you could define a property to avoid the event being fired when you change the children:

```<code>bool shouldChangeIndex = true;

private void MyTabbedPage_CurrentPageChanged(object sender, EventArgs e)
{
    if (shouldChangeIndex)
    {
        var index = this.Children.IndexOf(CurrentPage);
        Application.Current.Properties["index"] = index;
        Application.Current.SavePropertiesAsync();
    }
}

// Simulate the adjusting
shouldChangeIndex = false;
Children.Clear();
Children.Add(new MainPage());
Children.Add(new SecondPage());
shouldChangeIndex = true;

object index;
Application.Current.Properties.TryGetValue("index", out index);
if (index != null)
{
    CurrentPage = Children[int.Parse(index.ToString())];
}
</code>```

Body:
It seems it can't be achieved using MVVM as CurrentPage is not a bindable property and CurrentPageChanged is an event.

However, there's no need to handle the PagesChanged event. You could record the index in the changed event like:

private void MyTabbedPage_CurrentPageChanged(object sender, EventArgs e)
{
    Application.Current.Properties["index"] = this.Children.IndexOf(CurrentPage);
    Application.Current.SavePropertiesAsync();
}

Then you could set your tabbed page's current page after you have loaded all the tabs:

object index;
Application.Current.Properties.TryGetValue("index", out index);
if (index != null)
{
    CurrentPage = Children[int.Parse(index.ToString())];
}
// Subscribe the event
CurrentPageChanged += MyTabbedPage_CurrentPageChanged;

I placed the code above in the custom tabbed page's constructor and it could change the selected tab at initial time.

Update:

If you want to change the tabbed page's children dynamically, you could define a property to avoid the event being fired when you change the children:

bool shouldChangeIndex = true;

private void MyTabbedPage_CurrentPageChanged(object sender, EventArgs e)
{
    if (shouldChangeIndex)
    {
        var index = this.Children.IndexOf(CurrentPage);
        Application.Current.Properties["index"] = index;
        Application.Current.SavePropertiesAsync();
    }
}

// Simulate the adjusting
shouldChangeIndex = false;
Children.Clear();
Children.Add(new MainPage());
Children.Add(new SecondPage());
shouldChangeIndex = true;

object index;
Application.Current.Properties.TryGetValue("index", out index);
if (index != null)
{
    CurrentPage = Children[int.Parse(index.ToString())];
}


问:
Cocktail party - audio source separation
I am trying to solve the "Cocktail Party Problem".

Here is a video beautifully explaining and solving this problem.

In the video he claims one line of code solved this problem.
So I got my hands on those same audio files he uses in the video from here, and I included the line of code that he uses in the video (line 5), but I get significantly worse results. The code I have basically just outputs the same original mixed audio files, in lower volume.

This is the code I have in Octave:

```<code>[x1, Fs1] = audioread('mixed1.wav');
[x2, Fs2] = audioread('mixed2.wav');
xx = [x1, x2]';
yy = sqrtm(inv(cov(xx')))*(xx-repmat(mean(xx,2),1,size(xx,2)));
[W,s,v] = svd((repmat(sum(yy.*yy,1),size(yy,1),1).*yy)*yy');
a = W*xx;
audiowrite('refined1.wav', a(1,:), Fs1);
audiowrite('refined2.wav', a(2,:), Fs1);
</code>```

I don't understand why this doesn't work. I mean, he actually shows in the video that it works, maybe not 100% accurate, but it definitely works quite well.

What did I do wrong and how do I fix it?

答:
Here is Octave code demonstrating how to:

Mix 2 sound files.

Separate them again.

```<code># Read original (unmixed) signals.
[o1, Fs1] = audioread('original1.wav');
[o2, Fs2] = audioread('original2.wav');

# Sampling rates Fs1, Fs2 should be equal!

# o Nx2 contains original signals
o = [o1, o2];

# A is a mixing matrix to make a linear combination of the input sounds.
# It can be arbitrarily changed (must be invertible).
A = [.8,.5 ; .1,.4];

# m Nx2 contains mixed signals
m = o * A;

# Save mixed files
audiowrite('mixed1.wav', m(:, 1), Fs1);
audiowrite('mixed2.wav', m(:, 2), Fs1);

# Uncomment to read your own mixed files.
#[m1, Fs1] = audioread('mymix1.wav');
#[m2, Fs2] = audioread('mymix2.wav');
#m = [m1, m2];

if 0
    # Precise solution
    # W1 is ideal unmixing matrix
    W1 = inv(A);

    # s Nx2 contains separated signals
    s = m * W1;
else
    # Compute W by a magic algo
    # See https://cs.nyu.edu/~roweis/kica.html
    xx = m';

    yy = sqrtm(inv(cov(xx')))*(xx-repmat(mean(xx,2),1,size(xx,2)));
    [W,s,v] = svd((repmat(sum(yy.*yy,1),size(yy,1),1).*yy)*yy');

    ss = W * yy;

    # Scale down by an empiric value
    s = ss * 0.5;

    # s Nx2 contains separated signals
    s = s';
end

audiowrite('separated1.wav', s(:, 1), Fs1);
audiowrite('separated2.wav', s(:, 2), Fs1);
</code>```

Unfortunately it does not work with real audio from 2 microphones.

Body:
I am trying to solve the "Cocktail Party Problem".

Here is a video beautifully explaining and solving this problem.

In the video he claims one line of code solved this problem.
So I got my hands on those same audio files he uses in the video from here, and I included the line of code that he uses in the video (line 5), but I get significantly worse results. The code I have basically just outputs the same original mixed audio files, in lower volume.

This is the code I have in Octave:

[x1, Fs1] = audioread('mixed1.wav');
[x2, Fs2] = audioread('mixed2.wav');
xx = [x1, x2]';
yy = sqrtm(inv(cov(xx')))*(xx-repmat(mean(xx,2),1,size(xx,2)));
[W,s,v] = svd((repmat(sum(yy.*yy,1),size(yy,1),1).*yy)*yy');
a = W*xx;
audiowrite('refined1.wav', a(1,:), Fs1);
audiowrite('refined2.wav', a(2,:), Fs1);

I don't understand why this doesn't work. I mean, he actually shows in the video that it works, maybe not 100% accurate, but it definitely works quite well.

What did I do wrong and how do I fix it?

Body:
Here is Octave code demonstrating how to:

Mix 2 sound files.

Separate them again.

# Read original (unmixed) signals.
[o1, Fs1] = audioread('original1.wav');
[o2, Fs2] = audioread('original2.wav');

# Sampling rates Fs1, Fs2 should be equal!

# o Nx2 contains original signals
o = [o1, o2];

# A is a mixing matrix to make a linear combination of the input sounds.
# It can be arbitrarily changed (must be invertible).
A = [.8,.5 ; .1,.4];

# m Nx2 contains mixed signals
m = o * A;

# Save mixed files
audiowrite('mixed1.wav', m(:, 1), Fs1);
audiowrite('mixed2.wav', m(:, 2), Fs1);

# Uncomment to read your own mixed files.
#[m1, Fs1] = audioread('mymix1.wav');
#[m2, Fs2] = audioread('mymix2.wav');
#m = [m1, m2];

if 0
    # Precise solution
    # W1 is ideal unmixing matrix
    W1 = inv(A);

    # s Nx2 contains separated signals
    s = m * W1;
else
    # Compute W by a magic algo
    # See https://cs.nyu.edu/~roweis/kica.html
    xx = m';

    yy = sqrtm(inv(cov(xx')))*(xx-repmat(mean(xx,2),1,size(xx,2)));
    [W,s,v] = svd((repmat(sum(yy.*yy,1),size(yy,1),1).*yy)*yy');

    ss = W * yy;

    # Scale down by an empiric value
    s = ss * 0.5;

    # s Nx2 contains separated signals
    s = s';
end

audiowrite('separated1.wav', s(:, 1), Fs1);
audiowrite('separated2.wav', s(:, 2), Fs1);

Unfortunately it does not work with real audio from 2 microphones.


问:
Illogical "Bad substitution" in singularity

Problem

One of the configuration scripts from a package in my singularity container contains this perfectly reasonable (to me) bit of bash to trim a trailing / off a path;

```<code>if [ "${MY_DIR_PATH: -1}" = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi
</code>```

It works fine natively on my machine, but when run from the %post section of a singularity container it fails with Bad substitution.
What's going wrong and what is the correct workaround?

Minimal working example

Save the text below as badSubs.def then try; sudo singularity build badSubs.sif badSubs.def.

```<code>BootStrap: docker
From: ubuntu:18.04

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    #echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    #umask 000

    echo "${GREEN}~~~ this should work fine! ~~~ ${NOCOLOUR}"
    MYSCRIPT=$SINGULAITY_ROOTFS/confuzzel
    touch $MYSCRIPT
    chmod u+x $MYSCRIPT
    echo '#! /bin/bash' >> $MYSCRIPT
    echo 'PATHY="/what/a/path/"' >> $MYSCRIPT
    echo 'if [ "${PATHY: -1}" = "/" ]; then ' >> $MYSCRIPT
    echo '    echo yay!' >> $MYSCRIPT
    echo '    PATHY="${PATHY%?}"' >> $MYSCRIPT
    echo 'fi' >> $MYSCRIPT
    echo 'echo $PATHY' >> $MYSCRIPT
    cat $MYSCRIPT
    ./confuzzel

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build badSubs.sif badSubs.def
    to run me do
    > singularity run badSubs.sif

</code>```

答:
OK, answering my own question because I found something that works;

```<code>if [ $(echo -n $MY_DIR_PATH | tail -c 1) = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi
</code>```

Inspired by https://stackoverflow.com/a/32872687/7690011

If someone wanted to answer/add to this answer in a way that explained why this worked I would accept that answer.

Body:
Problem

One of the configuration scripts from a package in my singularity container contains this perfectly reasonable (to me) bit of bash to trim a trailing / off a path;

if [ "${MY_DIR_PATH: -1}" = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi

It works fine natively on my machine, but when run from the %post section of a singularity container it fails with Bad substitution.
What's going wrong and what is the correct workaround?

Minimal working example

Save the text below as badSubs.def then try; sudo singularity build badSubs.sif badSubs.def.

BootStrap: docker
From: ubuntu:18.04

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    #echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    #umask 000

    echo "${GREEN}~~~ this should work fine! ~~~ ${NOCOLOUR}"
    MYSCRIPT=$SINGULAITY_ROOTFS/confuzzel
    touch $MYSCRIPT
    chmod u+x $MYSCRIPT
    echo '#! /bin/bash' >> $MYSCRIPT
    echo 'PATHY="/what/a/path/"' >> $MYSCRIPT
    echo 'if [ "${PATHY: -1}" = "/" ]; then ' >> $MYSCRIPT
    echo '    echo yay!' >> $MYSCRIPT
    echo '    PATHY="${PATHY%?}"' >> $MYSCRIPT
    echo 'fi' >> $MYSCRIPT
    echo 'echo $PATHY' >> $MYSCRIPT
    cat $MYSCRIPT
    ./confuzzel

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build badSubs.sif badSubs.def
    to run me do
    > singularity run badSubs.sif

Body:
OK, answering my own question because I found something that works;

if [ $(echo -n $MY_DIR_PATH | tail -c 1) = "/" ]; then
    MY_DIR_PATH="${MY_DIR_PATH%?}"
fi

Inspired by https://stackoverflow.com/a/32872687/7690011

If someone wanted to answer/add to this answer in a way that explained why this worked I would accept that answer.


问:
How to show 404 Page when user is typing any URL on login page if user is not authenticated?
I want user to be blocked by accessing invalid URL from login screen if user is not authenticated, for instance, consider user is on login screen and if user tries to access any random url localhost:3000/kanskd, he/she should be redirected to login screen. I am able to achieve what i need by placing NoMatch route component, however, it matches the route inside my application as well and it renders No match for those routes as well[Routes that i am mapping after NoMatch route does not work].

index.js

```<code>import Routes from './routes'

   <Switch>
       <Route exact path="/" render={() => {
          if(!store.getState().login.isAvailable) {
            return <Redirect to="/login"/>
          } else {
            return <Redirect to="/dashboard" />
          }
        }}
       />
       <Route exact path="/login" component={Login} />
       <Route component={NoMatch} />
       {Routes.map((prop, key) => {
          return <Route path={prop.path} key={key} component={prop.component}
                  />;
       })}

   </Switch>
</code>```

NoMatch.jsx

```<code>import React from 'react'
import { withRouter } from 'react-router-dom';

const NoMatch = ({ location }) => (
    <div>
      <h3>No match for <code>{location.pathname}</code></h3>
    </div>
)

export default withRouter(NoMatch);
</code>```

EDIT:

routes/index.js

```<code>import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/", name: "Dashboard", component: Dashboard }];

export default Routes;
</code>```

Once the user logs in, it routes him to Dashboard and in Dashboard, there are other multiple routes.

答:
So you have to solve 2 things here: show the NoMatch component when there is no match for a url and protect some routes from not logged users.

For the first one you should put your <Route component={NoMatch} /> just before the <Switch>closing tag, think of this like a switch in plain javascript, the last case is always the default case, if there is no other match the default will be executed, same as here.

The second problem requires a bit of extra code, you have to create a component that redirects the user if is not logged in, something like this (this is from the documentation react-router docs):

```<code>function PrivateRoute({ component: Component, isLoggedIn,...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}
</code>```

Then use this component for protected routes:

```<code><Switch>
    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Redirect to="/dashboard" />
       }
     }}
    />
    <Route exact path="/login" component={Login} />
    {Routes.map((prop, key) => {
       return <PrivateRoute path={prop.path} key={key} component={prop.component} isLoggedIn={isUserLoggedIn}
               />;
    })}
    <Route component={NoMatch} />
</Switch>
</code>```

isUserLoggedIn is a made up variable, you should replace it for you logged in checks methods

Edit:
The path should be /dashboard:

```<code>import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/dashboard", name: "Dashboard", component: Dashboard }];

export default Routes;
</code>```

if you want to maintain / as your path you should return the dashboard component inside your Route component instead of redirecting:

```<code>    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Dashboard/>
       }
     }}
    />
</code>```

Body:
I want user to be blocked by accessing invalid URL from login screen if user is not authenticated, for instance, consider user is on login screen and if user tries to access any random url localhost:3000/kanskd, he/she should be redirected to login screen. I am able to achieve what i need by placing NoMatch route component, however, it matches the route inside my application as well and it renders No match for those routes as well[Routes that i am mapping after NoMatch route does not work].

index.js

import Routes from './routes'

   <Switch>
       <Route exact path="/" render={() => {
          if(!store.getState().login.isAvailable) {
            return <Redirect to="/login"/>
          } else {
            return <Redirect to="/dashboard" />
          }
        }}
       />
       <Route exact path="/login" component={Login} />
       <Route component={NoMatch} />
       {Routes.map((prop, key) => {
          return <Route path={prop.path} key={key} component={prop.component}
                  />;
       })}

   </Switch>

NoMatch.jsx

import React from 'react'
import { withRouter } from 'react-router-dom';

const NoMatch = ({ location }) => (

No match for {location.pathname}

)

export default withRouter(NoMatch);

EDIT:

routes/index.js

import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/", name: "Dashboard", component: Dashboard }];

export default Routes;

Once the user logs in, it routes him to Dashboard and in Dashboard, there are other multiple routes.

Body:
So you have to solve 2 things here: show the NoMatch component when there is no match for a url and protect some routes from not logged users.

For the first one you should put your <Route component={NoMatch} /> just before the <Switch>closing tag, think of this like a switch in plain javascript, the last case is always the default case, if there is no other match the default will be executed, same as here.

The second problem requires a bit of extra code, you have to create a component that redirects the user if is not logged in, something like this (this is from the documentation react-router docs):

function PrivateRoute({ component: Component, isLoggedIn,...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}

Then use this component for protected routes:

<Switch>
    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Redirect to="/dashboard" />
       }
     }}
    />
    <Route exact path="/login" component={Login} />
    {Routes.map((prop, key) => {
       return <PrivateRoute path={prop.path} key={key} component={prop.component} isLoggedIn={isUserLoggedIn}
               />;
    })}
    <Route component={NoMatch} />
</Switch>

isUserLoggedIn is a made up variable, you should replace it for you logged in checks methods

Edit:
The path should be /dashboard:

import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/dashboard", name: "Dashboard", component: Dashboard }];

export default Routes;

if you want to maintain / as your path you should return the dashboard component inside your Route component instead of redirecting:

    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Dashboard/>
       }
     }}
    />


问:
Insert multiple records in Sqflite
How to insert quickly multiple records in sqflite? The standard quickly method is:

```<code>await database.insert(table, object.toMap())
</code>```

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

答:
As I mentioned in the comment, you can use Batch. Here is the sample.

```<code>Batch batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
</code>```

Now if you are looking for result (it will cost you some memory), you use

```<code>results = await batch.commit();
</code>```

And if you are looking for fast performance, just ignore the result and use

```<code>await batch.commit(noResult: true);
</code>```

Source

Title: Insert multiple records in Sqflite

Body:
How to insert quickly multiple records in sqflite? The standard quickly method is:

await database.insert(table, object.toMap())

But I don't think that insert record one to one with a cycle is a good idea.
Or I can insert all list with a transaction?

Body:
As I mentioned in the comment, you can use Batch. Here is the sample.

Batch batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);

Now if you are looking for result (it will cost you some memory), you use

results = await batch.commit();

And if you are looking for fast performance, just ignore the result and use

await batch.commit(noResult: true);

Source


问:
How to vectorize this for loops in python?
Code is as below

import numpy as np

data = np.random.randint(0, 10, 12).reshape(3, 4)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 2

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

print(dataMask)
```

I have a numpy array "data" with shape (h, w). Its elements is int number ∈[0, 10).

I create a array dataMask with shape (h, w, 10). dataMask[i, j, k] indicats the number of points whose value is k within an area in data. This area in data has center (i,j) and r = 2, and is a square.

How to vectorize those for loops in the code? Thank you!

答:
Here is one method using cumsum:

```<code>import numpy as np

data = np.random.randint(0, 10, 1200).reshape(30, 40)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 20

from time import time
T = []

T.append(time())

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

T.append(time())

m1 = np.zeros((h, w, 10), np.int)
np.put_along_axis(m1, data[...,None], 1, 2)
m2 = np.empty_like(m1)
m1 = m1.cumsum(1)
m2[: ,:-r+1] = m1[:, r-1:]
m2[:, -r+1:] = m1[:, -1, None]
m2[:, r+1:] -= m1[:, :-r-1]
m2 = m2.cumsum(0)
m1[:-r+1] = m2[r-1:]
m1[-r+1:] = m2[-1, None]
m1[r+1:] -= m2[:-r-1]

T.append(time())

assert (dataMask==m1).all()

print(np.diff(T))
</code>```

Example run with h,w,r = 30,40,20

```<code># time [seconds] used by
# OP            cumsum
[9.23162699e-01 3.41892242e-04]
</code>```

Body:
Code is as below

import numpy as np

data = np.random.randint(0, 10, 12).reshape(3, 4)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 2

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

print(dataMask)

I have a numpy array "data" with shape (h, w). Its elements is int number ∈[0, 10).

I create a array dataMask with shape (h, w, 10). dataMask[i, j, k] indicats the number of points whose value is k within an area in data. This area in data has center (i,j) and r = 2, and is a square.

How to vectorize those for loops in the code? Thank you!

Body:
Here is one method using cumsum:

import numpy as np

data = np.random.randint(0, 10, 1200).reshape(30, 40)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 20

from time import time
T = []

T.append(time())

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

T.append(time())

m1 = np.zeros((h, w, 10), np.int)
np.put_along_axis(m1, data[...,None], 1, 2)
m2 = np.empty_like(m1)
m1 = m1.cumsum(1)
m2[: ,:-r+1] = m1[:, r-1:]
m2[:, -r+1:] = m1[:, -1, None]
m2[:, r+1:] -= m1[:, :-r-1]
m2 = m2.cumsum(0)
m1[:-r+1] = m2[r-1:]
m1[-r+1:] = m2[-1, None]
m1[r+1:] -= m2[:-r-1]

T.append(time())

assert (dataMask==m1).all()

print(np.diff(T))

Example run with h,w,r = 30,40,20

# time [seconds] used by
# OP            cumsum
[9.23162699e-01 3.41892242e-04]


问:
Pass value to a private property
I have a couple of private properties defined like so..

```<code>private var tableConfig : TableViewConfig<Company, CompanyCell>?

private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }
</code>```

Now there are 2 other properties defined like so...

```<code>  var model: Model?
  var companyCell: TableviewCell?
</code>```

Now, if get the value in model as Industry and the value in companyCell as IndustryCell, how can I update these values to private var tableConfig : TableViewConfig.... and private var tabledata = [Company]().... so that they will ultimately have the values like so..

```<code>private var tableConfig : TableViewConfig<Industry, IndustryCell>?

private var tabledata = [Industry]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }
</code>```

答:
You can expose an init() or a method to set the value of private properties, i.e.

```<code>class SampleClass {
    private var tableConfig : TableViewConfig<Company, CompanyCell>?
    private var tabledata = [Company]() {
        didSet {
            tableConfig?.items = tabledata
        }
    }

    init(tableData: [Company]) {
        self.tabledata = tabledata
    }

    func add(item: Company) {
        self.tabledata.append(item)
    }
}
</code>```

You can create an init in case you want to initialise your private variable and use a method in case you want to update the private variables.

Title: Pass value to a private property

Body:
I have a couple of private properties defined like so..

private var tableConfig : TableViewConfig<Company, CompanyCell>?

private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }

Now there are 2 other properties defined like so...

  var model: Model?
  var companyCell: TableviewCell?

Now, if get the value in model as Industry and the value in companyCell as IndustryCell, how can I update these values to private var tableConfig : TableViewConfig.... and private var tabledata = [Company]().... so that they will ultimately have the values like so..

private var tableConfig : TableViewConfig<Industry, IndustryCell>?

private var tabledata = [Industry]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }

Body:
You can expose an init() or a method to set the value of private properties, i.e.

class SampleClass {
    private var tableConfig : TableViewConfig<Company, CompanyCell>?
    private var tabledata = [Company]() {
        didSet {
            tableConfig?.items = tabledata
        }
    }

    init(tableData: [Company]) {
        self.tabledata = tabledata
    }

    func add(item: Company) {
        self.tabledata.append(item)
    }
}

You can create an init in case you want to initialise your private variable and use a method in case you want to update the private variables.


问:
Passing arbitrary number of parameters using vector in C++
I'm dealing with C++ objects that use destructor to deallocate resources. When passing those objects to a function with an arbitrary number of parameters.
Is there any way to get rid of using pointers in this case?

One possible solution is passing a vector of pointers to those objects.
if I pass the objects themselves, the destructors will be called twice, one is the real objects, another is when the vector is deallocated.

```<code>#include<iostream>
#include<vector>
class integer {
    private:
        int data;
    public:
        integer(int value = 0): data(value) {}
        ~integer() {}
        void increase() {
            data++;
        }
        friend std::ostream& operator<<(std::ostream& os, const integer& x);
};
std::ostream& operator<<(std::ostream& os, const integer& x) {
    os << x.data;
    return os;
}
void foo(std::vector<integer*> vec) {
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}
int main() {
    integer x1(3);
    integer x2(4);
    integer x3(5);

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    foo({&x1, &x2, &x3});

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    return 0;
}
</code>```

Expected results:

```<code>3 4 5
4 5 6
</code>```

答:
I'm not sure what is wrong with pointers, but of course you can avoid pointers with reference_wrappers. (Don't forget to #include <functional>)

```<code>void foo(const std::vector<std::reference_wrapper<integer>>& vec)
{
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}
</code>```

Now you can call it like foo({x1, x2, x3}).

live demo

You can even get rid of the {} if you want:

```<code>template <typename... Args>
void foo(Args&... args)
{
    static_assert(std::conjunction_v<std::is_same<Args, integer>...>);
    (args.increase(), ...);
}
</code>```

(Don't forget to #include <type_traits>.)
Now you can call it like foo(x1, x2, x3).

Body:
I'm dealing with C++ objects that use destructor to deallocate resources. When passing those objects to a function with an arbitrary number of parameters.
Is there any way to get rid of using pointers in this case?

One possible solution is passing a vector of pointers to those objects.
if I pass the objects themselves, the destructors will be called twice, one is the real objects, another is when the vector is deallocated.

#include<iostream>
#include<vector>
class integer {
    private:
        int data;
    public:
        integer(int value = 0): data(value) {}
        ~integer() {}
        void increase() {
            data++;
        }
        friend std::ostream& operator<<(std::ostream& os, const integer& x);
};
std::ostream& operator<<(std::ostream& os, const integer& x) {
    os << x.data;
    return os;
}
void foo(std::vector<integer*> vec) {
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}
int main() {
    integer x1(3);
    integer x2(4);
    integer x3(5);

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    foo({&x1, &x2, &x3});

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    return 0;
}

Expected results:

3 4 5
4 5 6

Body:
I'm not sure what is wrong with pointers, but of course you can avoid pointers with reference_wrappers. (Don't forget to #include <functional>)

void foo(const std::vector<std::reference_wrapper<integer>>& vec)
{
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}

Now you can call it like foo({x1, x2, x3}).

live demo

You can even get rid of the {} if you want:

template <typename... Args>
void foo(Args&... args)
{
    static_assert(std::conjunction_v<std::is_same<Args, integer>...>);
    (args.increase(), ...);
}

(Don't forget to #include <type_traits>.)
Now you can call it like foo(x1, x2, x3).


问:
Building an App Shell For My Service Worker to cache using Handlebars
I am building a PWA using express-handlebars. I'm trying to follow the Google design practices and build an app shell in order to cache with a service worker. However, I'm a little stumped since Handlebars is a template engine which generates html. Is there a better way to build an app shell with express for service worker caching? Examples would be appreciated.</p>

答:
"Is there a better way" depends on many variables in your project and there's really no answer to that.

More important here is to understand the basic idea of an app shell, in my opinion at least. When you grok that you'll be able to tune your variables and pick the right tech freely. Generating HTML with Handlebars is completely fine if it suits your app. HTML is fast for the browser to render (vs JS heavy stuff) so it fits the shell idea perfectly.

With app shell your app is structured in the not constantly changing, static(ish) layout (menu, header, footer etc.) and dynamic part. With this separation the app shell idea can use Service Workers this way:

Server ships the app shell (usually only HTML/CSS)

Browser renders that very fast and caches it for offline use via Service Worker

After showing the shell, JS takes over and starts to fetch dynamic content (what is shown "inside" the shell)

Browser renders the dynamic part utilising some JS framework (usually)

These separate parts could be very loosely-coupled. You could use whatever means you want to create the app shell and something completely different for the dynamic part. Or, you could implement them with the same front-end framework. It doesn't really matter from the point of view of the app shell architecture. The point is, the shell should be available super-fast which you'll achieve more easily when you ship just HTML/CSS.


问:
Java fx-8. How to configure path to local image using fxml file
I have some troubles configuring path to local image in my javaFX application.
I want to use icon to my button, but it's not working for local images, only with external resources. This is my code:

```<code>            <Button fx:id="magicWangButton" mnemonicParsing="false" onAction="#magicWang" text="Magic wang">
                <graphic>
                    <ImageView fitHeight="20.0" fitWidth="20.0" pickOnBounds="true" preserveRatio="true">
                        <image>
                            <!--<Image url="/fxml/img/magic-wang.png" />-->

                            <Image url="https://i.stack.imgur.com/y1evM.png" />
                            <!--<Image url="/fxml/img/site-logo.png" />-->
                            <Image url="img/magic-wang.png"/>
                        </image>
                    </ImageView>
                </graphic>
            </Button>
</code>```

this string work's fine:

```<code><Image url="https://i.stack.imgur.com/y1evM.png" />
</code>```

, but others...
My image located in path: resources/fxml/img/
all fxml files located in fxml directory.
I saw other questions and answers but it uses configuration in java files, but it is not what I looking for.

答:
The trick is to start the url with "@" and call FXMLLoader.setLocation().

relative URLs:

@one24.png:

@image/two24.png

@../three24.png

absolute URLs:

@/four24.png

@/image/five24.png

Please note that I've implemented a utility class: FXMLLoaders

If you stick to the following naming conventions:

MyComponent.java

MyComponent.fxml (same package as MyComponent.java)

MyComponent.properties (same package as MyComponent.java)

you can use the following code:

For fx:root based FXML files:

```<code>public MyComponent() {
    FXMLLoaders.loadRoot(this);
}
</code>```

Otherwise:

```<code>Parent root = FXMLLoaders.load(FxmlSampleApplication.class);
</code>```

The library is available from Maven Central:

```<code><dependency>
    <groupId>org.drombler.commons</groupId>
    <artifactId>drombler-commons-fx-core</artifactId>
    <version>0.13</version>
</dependency>
</code>```

You can find a full sample which loads images on GitHub.

I've also written a blog post about this utility class and the naming conventions.

Body:
I have some troubles configuring path to local image in my javaFX application.
I want to use icon to my button, but it's not working for local images, only with external resources. This is my code:

            <Button fx:id="magicWangButton" mnemonicParsing="false" onAction="#magicWang" text="Magic wang">
                <graphic>
                    <ImageView fitHeight="20.0" fitWidth="20.0" pickOnBounds="true" preserveRatio="true">
                        <image>

                            <Image url="https://i.stack.imgur.com/y1evM.png" />

                            <Image url="img/magic-wang.png"/>
                        </image>
                    </ImageView>
                </graphic>
            </Button>

this string work's fine:

<Image url="https://i.stack.imgur.com/y1evM.png" />

, but others...
My image located in path: resources/fxml/img/
all fxml files located in fxml directory.
I saw other questions and answers but it uses configuration in java files, but it is not what I looking for.

Body:
The trick is to start the url with "@" and call FXMLLoader.setLocation().

relative URLs:

@one24.png:

@image/two24.png

@../three24.png

absolute URLs:

@/four24.png

@/image/five24.png

Please note that I've implemented a utility class: FXMLLoaders

If you stick to the following naming conventions:

MyComponent.java

MyComponent.fxml (same package as MyComponent.java)

MyComponent.properties (same package as MyComponent.java)

you can use the following code:

For fx:root based FXML files:

public MyComponent() {
    FXMLLoaders.loadRoot(this);
}

Otherwise:

Parent root = FXMLLoaders.load(FxmlSampleApplication.class);

The library is available from Maven Central:

<dependency>
    <groupId>org.drombler.commons</groupId>
    <artifactId>drombler-commons-fx-core</artifactId>
    <version>0.13</version>
</dependency>

You can find a full sample which loads images on GitHub.

I've also written a blog post about this utility class and the naming conventions.


问:
Slick Carousel get current slidesToShow depending on breakpoints
I use the kenwheeler/slick Carousel and i want to take the settings i put. I want to get the attribute slidesToShow. I try this way because of some breakpoints i put also and affects the value of the property above. The easy way is to get the settings object and check for the value of this property. Does anybody knows how to get any attribute of the Slick Settings on demand somehow like:

```<code>$('#slickCarouselId').attritubeName
</code>```

Thanks ...

答:
If I understand correctly you need

```<code>// get
let slides = $('#slickCarouselId').slick('slickGetOption', 'slidesToShow');
// set
$('#slickCarouselId').slick('slickSetOption', 'slidesToShow', 2, true);
</code>```

Last argument is passed to refresh UI

Body:
I use the kenwheeler/slick Carousel and i want to take the settings i put. I want to get the attribute slidesToShow. I try this way because of some breakpoints i put also and affects the value of the property above. The easy way is to get the settings object and check for the value of this property. Does anybody knows how to get any attribute of the Slick Settings on demand somehow like:

$('#slickCarouselId').attritubeName

Thanks ...

Body:
If I understand correctly you need

// get
let slides = $('#slickCarouselId').slick('slickGetOption', 'slidesToShow');
// set
$('#slickCarouselId').slick('slickSetOption', 'slidesToShow', 2, true);

Last argument is passed to refresh UI


问:
losing image quality while converting base 64

I have one pdf and I am converting pdf to image and displaying in UIImageView and then after I am converting that image to base 64 but while converting base 64 I am losing the image quality so is there any way to prevent from losing quality while converting to base 64

please tell me is there any solution for that

here is my code for convert

```<code>let previewImage1 = convertedImageView.getImage()
let btnImg = UIButton()
btnImg.setImage(previewImage1, for: .normal)
let btn1Imggg2 = btnImg.image(for: .normal)
let imageData2 = btnImg?.jpegData(compressionQuality: 0.0)
let imgString2 = imageData2!.base64EncodedString(options: .init(rawValue: 0))
</code>```

Even if i set compress quality to 0.0 still its compressing image

i have UIView Inside that i have ScrollView inside that i have ImageView and i am converting whole UIView as image and then convert into base64 the is the scenario hope this help you to understand

Code For UIView To UIImage

```<code> func getImage(scale: CGFloat? = nil) -> UIImage {
        let newScale = scale ?? UIScreen.main.scale
        self.scale(by: newScale)

        let format = UIGraphicsImageRendererFormat()
        format.scale = newScale

        let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: format)

        let image = renderer.image { rendererContext in
            self.layer.render(in: rendererContext.cgContext)
        }

        return image
    }
</code>```

答:
Okay, since you have a nested hierarchy (UIView -> UIScrollView -> UIImageView) and you wan't to capture that whole hierarchy as an image, it would be better to make an image from UIView (the topmost in the hierarchy, unless I understood wrong and you wan't the UIImageView part only)

```<code>let parentMostView = (the view you want to create into an image)

UIGraphicsBeginImageContextWithOptions(size: parentMostView.frame.size, NO, UIScreen.main.scale)

let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGrapgicsEndImageContext()
let imageAsData = image.pngData()
//do your base64 conversion here

</code>```

EDITED: Upon seeing your image creation code

I don't see any issues in your getImage(:) method. On what device are you testing(lower scale devices would create low resolution images because you are dependent on Device scale)? Try using a high static scale value(e.g 10) and replace Data conversion to .jpegData(compressionQuality: 1.0) or .pngData()

Body:
I have one pdf and I am converting pdf to image and displaying in UIImageView and then after I am converting that image to base 64 but while converting base 64 I am losing the image quality so is there any way to prevent from losing quality while converting to base 64

please tell me is there any solution for that

here is my code for convert

let previewImage1 = convertedImageView.getImage()
let btnImg = UIButton()
btnImg.setImage(previewImage1, for: .normal)
let btn1Imggg2 = btnImg.image(for: .normal)
let imageData2 = btnImg?.jpegData(compressionQuality: 0.0)
let imgString2 = imageData2!.base64EncodedString(options: .init(rawValue: 0))

Even if i set compress quality to 0.0 still its compressing image

i have UIView Inside that i have ScrollView inside that i have ImageView and i am converting whole UIView as image and then convert into base64 the is the scenario hope this help you to understand

Code For UIView To UIImage

 func getImage(scale: CGFloat? = nil) -> UIImage {
        let newScale = scale ?? UIScreen.main.scale
        self.scale(by: newScale)

        let format = UIGraphicsImageRendererFormat()
        format.scale = newScale

        let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: format)

        let image = renderer.image { rendererContext in
            self.layer.render(in: rendererContext.cgContext)
        }

        return image
    }

Body:
Okay, since you have a nested hierarchy (UIView -> UIScrollView -> UIImageView) and you wan't to capture that whole hierarchy as an image, it would be better to make an image from UIView (the topmost in the hierarchy, unless I understood wrong and you wan't the UIImageView part only)

let parentMostView = (the view you want to create into an image)

UIGraphicsBeginImageContextWithOptions(size: parentMostView.frame.size, NO, UIScreen.main.scale)

let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGrapgicsEndImageContext()
let imageAsData = image.pngData()
//do your base64 conversion here

EDITED: Upon seeing your image creation code

I don't see any issues in your getImage(:) method. On what device are you testing(lower scale devices would create low resolution images because you are dependent on Device scale)? Try using a high static scale value(e.g 10) and replace Data conversion to .jpegData(compressionQuality: 1.0) or .pngData()


问:
How to fill the polygons of the radar chart in ggradar in R
I'm plotting the radar chart using ggradar and I would like to fill the polygons of the chart with different colours. Does anyone know how to do this?

Also, how to remove the legend? I cannot remove the legend even thought I've added plot.legend=FALSE.

Here is the code I'm using.

```<code>ggradar(dg, group.point.size=1,
        axis.labels=c("Depression", "Stress", "Anxiety"), label.centre.y=FALSE, plot.legend=FALSE, values.radar =c("","",""))
</code>```

Thanks very much!

答:
Not a ggradar() solution -look here-, but you can work with ggplot() an ggiraphExtra() packages (data are the famous iris dataset, due you did not provide any data):

```<code>library(ggplot2)
library(ggiraphExtra)

radar <- ggRadar(data=iris,aes(group=Species), alpha = 0.3) + # alpha for polygon colors intensity
         theme_light() +                                      # white background etc.
         theme(legend.position = 'none')                      # no legend
radar
</code>```

You can tweak as you want.

And you can save it:

```<code>ggsave(filename="radar.png")
</code>```

Body:
I'm plotting the radar chart using ggradar and I would like to fill the polygons of the chart with different colours. Does anyone know how to do this?

Also, how to remove the legend? I cannot remove the legend even thought I've added plot.legend=FALSE.

Here is the code I'm using.

ggradar(dg, group.point.size=1,
        axis.labels=c("Depression", "Stress", "Anxiety"), label.centre.y=FALSE, plot.legend=FALSE, values.radar =c("","",""))

Thanks very much!

Body:
Not a ggradar() solution -look here-, but you can work with ggplot() an ggiraphExtra() packages (data are the famous iris dataset, due you did not provide any data):

library(ggplot2)
library(ggiraphExtra)

radar <- ggRadar(data=iris,aes(group=Species), alpha = 0.3) + # alpha for polygon colors intensity
         theme_light() +                                      # white background etc.
         theme(legend.position = 'none')                      # no legend
radar

You can tweak as you want.

And you can save it:

ggsave(filename="radar.png")


问:
How to setup a Jenkins slave agent on a Mac to retrieve files using Plastic?
I have a Jenkins server running on Ubuntu; sources are on Plastic and I already have a Windows slave making Android builds, so the Plastic server is well responding with Jenkins.

I try to build the project for IOS on Mac but the job fails when getting the sources with a java exception

java.io.IOException: error=2, No such file or directory

I tried to remove the source control for the job and just running some commands like :

cm status

It failed, so I updated the PATH environment variable to make it work. Now it's ok for manual commands but still not for the automatic plastic pull.

I configured the job to pull from it using the PlasticSCM Plugin using the selector :

```<code>repository "MyRepo"
  path "/"
    smartbranch "/My/Branch"
</code>```

Here is the complete error :

```<code>[test-mac] $ cm find changeset where date between '2019-05-27T11:14:36' and '2019-05-27T11:15:43' and branch='/My/Branch' on repositories 'MyRepo' --xml --dateformat=yyyy'-'MM'-'dd'T'HH':'mm':'ss
java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
Also:   hudson.remoting.Channel$CallSiteStackTrace: Remote call to JNLP4-connect connection from 192.168.1.46/192.168.1.46:49336
        at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1743)
        at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:357)
        at hudson.remoting.Channel.call(Channel.java:957)
        at hudson.Launcher$RemoteLauncher.launch(Launcher.java:1059)
        at hudson.Launcher$ProcStarter.start(Launcher.java:455)
        at com.codicesoftware.plugins.hudson.PlasticTool.tryExecute(PlasticTool.java:97)
        at com.codicesoftware.plugins.hudson.PlasticTool.execute(PlasticTool.java:57)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.execute(CommandRunner.java:20)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.executeAndRead(CommandRunner.java:36)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.executeAndRead(CommandRunner.java:25)
        at com.codicesoftware.plugins.hudson.commands.ChangesetsRetriever.getChangesets(ChangesetsRetriever.java:27)
        at com.codicesoftware.plugins.hudson.commands.ChangesetsRetriever.getDetailedHistory(ChangesetsRetriever.java:36)
        at com.codicesoftware.plugins.hudson.PlasticSCM.FindCsets(PlasticSCM.java:363)
        at com.codicesoftware.plugins.hudson.PlasticSCM.SetUpWorkspace(PlasticSCM.java:175)
        at com.codicesoftware.plugins.hudson.PlasticSCM.checkout(PlasticSCM.java:141)
        at hudson.scm.SCM.checkout(SCM.java:504)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1208)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:574)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:499)
        at hudson.model.Run.execute(Run.java:1816)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:97)
        at hudson.model.Executor.run(Executor.java:429)
Caused: java.io.IOException: Cannot run program "cm" (in directory "/Users/MyUser/Jenkins/workspace/test-mac"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at hudson.Proc$LocalProc.<init>(Proc.java:249)
    at hudson.Proc$LocalProc.<init>(Proc.java:218)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:936)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1313)
    at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1266)
    at hudson.remoting.UserRequest.perform(UserRequest.java:212)
    at hudson.remoting.UserRequest.perform(UserRequest.java:54)
    at hudson.remoting.Request$2.run(Request.java:369)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at hudson.remoting.Engine$1.lambda$newThread$0(Engine.java:93)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
I think the problem could be related to the following Jenkins bug:
https://issues.jenkins-ci.org/browse/JENKINS-17157  (Enviroment variables are not loaded in ssh using cygwin)

If your slave is connecting via SSH to your Jenkins server, the environment variables are lost so you can't run "cm" commands.
The following link may be useful: (https://support.cloudbees.com/hc/en-us/articles/229724088-How-to-set-up-a-Jenkins-agent-to-have-the-same-path-as-the-user-when-connected-via-Remote-Desktop-)

In the past, we tried to connect the slave via "Java Web Start" (not via SSH) and we were not able to reproduce this issue with the lost PATH variable (it's only happening when connecting via SSH).

On the macOS:
- Running:
eg:

```<code>sudo java -jar agent.jar -jnlpUrl http://MySERVER84/computer/macOsJava/slave-agent.jnlp -secret f5dcf86e0ceed3f22c08bc27fa07d680aff3e11c25452677af4fee218bcfb1aa -workDir "/tmp"
</code>```

Body:
I have a Jenkins server running on Ubuntu; sources are on Plastic and I already have a Windows slave making Android builds, so the Plastic server is well responding with Jenkins.

I try to build the project for IOS on Mac but the job fails when getting the sources with a java exception

java.io.IOException: error=2, No such file or directory

I tried to remove the source control for the job and just running some commands like :

cm status

It failed, so I updated the PATH environment variable to make it work. Now it's ok for manual commands but still not for the automatic plastic pull.

I configured the job to pull from it using the PlasticSCM Plugin using the selector :

repository "MyRepo"
  path "/"
    smartbranch "/My/Branch"

Here is the complete error :

[test-mac] $ cm find changeset where date between '2019-05-27T11:14:36' and '2019-05-27T11:15:43' and branch='/My/Branch' on repositories 'MyRepo' --xml --dateformat=yyyy'-'MM'-'dd'T'HH':'mm':'ss
java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
Also:   hudson.remoting.Channel$CallSiteStackTrace: Remote call to JNLP4-connect connection from 192.168.1.46/192.168.1.46:49336
        at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1743)
        at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:357)
        at hudson.remoting.Channel.call(Channel.java:957)
        at hudson.Launcher$RemoteLauncher.launch(Launcher.java:1059)
        at hudson.Launcher$ProcStarter.start(Launcher.java:455)
        at com.codicesoftware.plugins.hudson.PlasticTool.tryExecute(PlasticTool.java:97)
        at com.codicesoftware.plugins.hudson.PlasticTool.execute(PlasticTool.java:57)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.execute(CommandRunner.java:20)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.executeAndRead(CommandRunner.java:36)
        at com.codicesoftware.plugins.hudson.commands.CommandRunner.executeAndRead(CommandRunner.java:25)
        at com.codicesoftware.plugins.hudson.commands.ChangesetsRetriever.getChangesets(ChangesetsRetriever.java:27)
        at com.codicesoftware.plugins.hudson.commands.ChangesetsRetriever.getDetailedHistory(ChangesetsRetriever.java:36)
        at com.codicesoftware.plugins.hudson.PlasticSCM.FindCsets(PlasticSCM.java:363)
        at com.codicesoftware.plugins.hudson.PlasticSCM.SetUpWorkspace(PlasticSCM.java:175)
        at com.codicesoftware.plugins.hudson.PlasticSCM.checkout(PlasticSCM.java:141)
        at hudson.scm.SCM.checkout(SCM.java:504)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1208)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:574)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:499)
        at hudson.model.Run.execute(Run.java:1816)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:97)
        at hudson.model.Executor.run(Executor.java:429)
Caused: java.io.IOException: Cannot run program "cm" (in directory "/Users/MyUser/Jenkins/workspace/test-mac"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at hudson.Proc$LocalProc.<init>(Proc.java:249)
    at hudson.Proc$LocalProc.<init>(Proc.java:218)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:936)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1313)
    at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1266)
    at hudson.remoting.UserRequest.perform(UserRequest.java:212)
    at hudson.remoting.UserRequest.perform(UserRequest.java:54)
    at hudson.remoting.Request$2.run(Request.java:369)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at hudson.remoting.Engine$1.lambda$newThread$0(Engine.java:93)
    at java.lang.Thread.run(Thread.java:748)

Body:
I think the problem could be related to the following Jenkins bug:
https://issues.jenkins-ci.org/browse/JENKINS-17157  (Enviroment variables are not loaded in ssh using cygwin)

If your slave is connecting via SSH to your Jenkins server, the environment variables are lost so you can't run "cm" commands.
The following link may be useful: (https://support.cloudbees.com/hc/en-us/articles/229724088-How-to-set-up-a-Jenkins-agent-to-have-the-same-path-as-the-user-when-connected-via-Remote-Desktop-)

In the past, we tried to connect the slave via "Java Web Start" (not via SSH) and we were not able to reproduce this issue with the lost PATH variable (it's only happening when connecting via SSH).

On the macOS:
- Running:
eg:

sudo java -jar agent.jar -jnlpUrl http://MySERVER84/computer/macOsJava/slave-agent.jnlp -secret f5dcf86e0ceed3f22c08bc27fa07d680aff3e11c25452677af4fee218bcfb1aa -workDir "/tmp"