问:
On click expanding of rows of a data table in shiny application is not working, How to solve this
I have written a code to create a data table in shiny R which when I click the row of interest it should expand and show me the child rows.
However this is working only for the last row of my data table. In the previous rows only the headers of the child table is being shown and not the data.

My data table :
Data Table

My output: My result

callback = JS("table.column(1).nodes().to$().css({cursor: 'pointer'});

```<code>// Format cars object into another table
var format = function (d) {
    if (d != null) {
        var result = ('<table id=\"child_' + d[2] + '_' + d[3] +
            '\">').replace('.', '_') + '<thead><tr>'
        for (var col in d[4][0]) {
            result += '<th>' + col + '</th>'
        }
        result += '</tr></thead></table>'
        return result
    } else {
        return '';
    }
}

var format_datatable = function (d) {
    var dataset = [];
    for (i = 0; i <= d[4].length - 1; i++) {
        var datarow = $.map(d[4][i], function (value, index) {
            return [value];
        });
        dataset.push(datarow)
    }
    var subtable = $(('table#child_' + d[2] + '_' +
        d[3]).replace('.', '_')).DataTable({
        'data': dataset,
        'autoWidth': true,
        'deferRender': true,
        'info': false,
        'lengthChange': false,
        'ordering': true,
        'paging': false,
        'scrollX': false,
        'scrollY': false,
        'searching': false
    });
};

table.on('click', 'td.details-control', function () {
    var td = $(this),
        row = table.row(td.closest('tr'));
    if (row.child.isShown()) {
        row.child.hide();
        td.html('⊕');
    } else {
        row.child(format(row.data())).show();
        td.html('⊖');
        format_datatable(row.data())
    }
});
")
</code>```

答:
The problem is the presence of white spaces in the column Description (try to expand row 3, it should work because there's no white space). Thus the JS code generates ids of the child tables with white spaces, and these ids are not valid. In the code below, the white spaces are replaced by _, and it works. Moreover, replacing the dots (because an id with dots is not valid) by doing replace('.', '_') is not the way to go, because this replaces only the first occurence of a dot. You have to use a global replacement: replace(/\./g, '_'). I also do a global replacement for the white spaces: replace(/\s/g, '_').

```<code>dat <- data.frame(
  ' ' = rep('⊕',2),
  Sr = c(1, 2),
  Description = c("A - B", "X - Y"),
  Details = I(list(list(list(Chromosome = "chr18", SNP = "rs2")),
                   list(list(Chromosome = "chr19", SNP = "rs3"),
                        list(Chromosome = "chr20", SNP = "rs4")))),
  check.names = FALSE
)

callback = JS(
  "table.column(1).nodes().to$().css({cursor: 'pointer'});",
  "// Format the nested table into another table",
  "var format = function (d) {",
  "  if (d != null) {",
  "    var result = ('<table class=\"display compact\" id=\"child_' + ",
  "                 ((d[2] + '_' + d[3]).replace(/\\s/g, '_')) +",
  "                 '\">').replace(/\\./g, '_') + '<thead><tr>';",
  "    for (var col in d[4][0]) {",
  "      result += '<th>' + col + '</th>';",
  "    }",
  "    result += '</tr></thead></table>';",
  "    return result;",
  "  } else {",
  "    return '';",
  "  }",
  "}",
  "var format_datatable = function (d) {",
  "  var dataset = [];",
  "  for (i = 0; i < d[4].length; i++) {",
  "    var datarow = $.map(d[4][i], function (value, index) {",
  "      return [value];",
  "    });",
  "    dataset.push(datarow);",
  "  }",
  "  var subtable = $(('table#child_' + d[2] + '_' + d[3])",
  "                   .replace(/\\./g, '_').replace(/\\s/g, '_')).DataTable({",
  "                     'data': dataset,",
  "                     'autoWidth': true,",
  "                     'deferRender': true,",
  "                     'info': false,",
  "                     'lengthChange': false,",
  "                     'ordering': true,",
  "                     'paging': false,",
  "                     'scrollX': false,",
  "                     'scrollY': false,",
  "                     'searching': false,",
  "                     'sortClasses': false,",
  "                     'columnDefs': [{targets: '_all', className: 'dt-center'}]",
  "                   });",
  "};",
  "table.on('click', 'td.details-control', function () {",
  "  var td = $(this),",
  "      row = table.row(td.closest('tr'));",
  "  if (row.child.isShown()) {",
  "    row.child.hide();",
  "    td.html('⊕');",
  "  } else {",
  "    row.child(format(row.data())).show();",
  "    td.html('⊖');",
  "    format_datatable(row.data())",
  "  }",
  "});")

datatable(dat, callback = callback, escape = FALSE,
          options = list(
            columnDefs = list(
              list(visible = FALSE, targets = 4),
              list(orderable = FALSE, className = 'details-control', targets = 1)
            )
          ))
</code>```

Body:
I have written a code to create a data table in shiny R which when I click the row of interest it should expand and show me the child rows.
However this is working only for the last row of my data table. In the previous rows only the headers of the child table is being shown and not the data.

My data table :
Data Table

My output: My result

callback = JS("table.column(1).nodes().to$().css({cursor: 'pointer'});

// Format cars object into another table
var format = function (d) {
    if (d != null) {
        var result = ('
').replace('.', '_') + '

'
        for (var col in d[4][0]) {
            result += '' + col + '	'
        }
        result += '

'
        return result
    } else {
        return '';
    }
}

var format_datatable = function (d) {
    var dataset = [];
    for (i = 0; i <= d[4].length - 1; i++) {
        var datarow = $.map(d[4][i], function (value, index) {
            return [value];
        });
        dataset.push(datarow)
    }
    var subtable = $(('table#child_' + d[2] + '_' +
        d[3]).replace('.', '_')).DataTable({
        'data': dataset,
        'autoWidth': true,
        'deferRender': true,
        'info': false,
        'lengthChange': false,
        'ordering': true,
        'paging': false,
        'scrollX': false,
        'scrollY': false,
        'searching': false
    });
};

table.on('click', 'td.details-control', function () {
    var td = $(this),
        row = table.row(td.closest('tr'));
    if (row.child.isShown()) {
        row.child.hide();
        td.html('⊕');
    } else {
        row.child(format(row.data())).show();
        td.html('⊖');
        format_datatable(row.data())
    }
});
")

Body:
The problem is the presence of white spaces in the column Description (try to expand row 3, it should work because there's no white space). Thus the JS code generates ids of the child tables with white spaces, and these ids are not valid. In the code below, the white spaces are replaced by _, and it works. Moreover, replacing the dots (because an id with dots is not valid) by doing replace('.', '_') is not the way to go, because this replaces only the first occurence of a dot. You have to use a global replacement: replace(/\./g, '_'). I also do a global replacement for the white spaces: replace(/\s/g, '_').

dat <- data.frame(
  ' ' = rep('&oplus;',2),
  Sr = c(1, 2),
  Description = c("A - B", "X - Y"),
  Details = I(list(list(list(Chromosome = "chr18", SNP = "rs2")),
                   list(list(Chromosome = "chr19", SNP = "rs3"),
                        list(Chromosome = "chr20", SNP = "rs4")))),
  check.names = FALSE
)

callback = JS(
  "table.column(1).nodes().to$().css({cursor: 'pointer'});",
  "// Format the nested table into another table",
  "var format = function (d) {",
  "  if (d != null) {",
  "    var result = ('<table class=\"display compact\" id=\"child_' + ",
  "                 ((d[2] + '_' + d[3]).replace(/\\s/g, '_')) +",
  "                 '\">').replace(/\\./g, '_') + '<thead><tr>';",
  "    for (var col in d[4][0]) {",
  "      result += '<th>' + col + '</th>';",
  "    }",
  "    result += '</tr></thead></table>';",
  "    return result;",
  "  } else {",
  "    return '';",
  "  }",
  "}",
  "var format_datatable = function (d) {",
  "  var dataset = [];",
  "  for (i = 0; i < d[4].length; i++) {",
  "    var datarow = $.map(d[4][i], function (value, index) {",
  "      return [value];",
  "    });",
  "    dataset.push(datarow);",
  "  }",
  "  var subtable = $(('table#child_' + d[2] + '_' + d[3])",
  "                   .replace(/\\./g, '_').replace(/\\s/g, '_')).DataTable({",
  "                     'data': dataset,",
  "                     'autoWidth': true,",
  "                     'deferRender': true,",
  "                     'info': false,",
  "                     'lengthChange': false,",
  "                     'ordering': true,",
  "                     'paging': false,",
  "                     'scrollX': false,",
  "                     'scrollY': false,",
  "                     'searching': false,",
  "                     'sortClasses': false,",
  "                     'columnDefs': [{targets: '_all', className: 'dt-center'}]",
  "                   });",
  "};",
  "table.on('click', 'td.details-control', function () {",
  "  var td = $(this),",
  "      row = table.row(td.closest('tr'));",
  "  if (row.child.isShown()) {",
  "    row.child.hide();",
  "    td.html('&oplus;');",
  "  } else {",
  "    row.child(format(row.data())).show();",
  "    td.html('&CircleMinus;');",
  "    format_datatable(row.data())",
  "  }",
  "});")

datatable(dat, callback = callback, escape = FALSE,
          options = list(
            columnDefs = list(
              list(visible = FALSE, targets = 4),
              list(orderable = FALSE, className = 'details-control', targets = 1)
            )
          ))


来源: stackexchange

问:
chrome and firefox browser fails to launch windows folder from link
I have a link that directs to a windows folder by its directory link. It works for internet explorer, but it doesn't work for chrome or firefox. How do i fix this?

my link goes something like this

```<code><a href="\\directory\folder1\folder2">Click Here</a>
</code>```

It works in internet explorer but it doesnt work for chrome? and it doesn't work in firefox either?

答:
As much as I know, MSIE is tightly connected with the windows explorer, so when you click a link to the folder, it goes to that folder. Also, when you type a link in the explorer window, it automatically redirects you to the required site by using MSIE.
While in Mozilla Firefox you need to specify that this is a local folder. As much as I know, you have to use the "file:///" prefix for that</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a link that directs to a windows folder by its directory link. It works for internet explorer, but it doesn't work for chrome or firefox. How do i fix this?

my link goes something like this

Click Here

It works in internet explorer but it doesnt work for chrome? and it doesn't work in firefox either?


问:
How to make list of random integers accumulated by program output?
I have code output accumulated integers, so how i can make list of that, I tried list(temp) but it says "argument of type 'int' is not iterable" how to do this.</p>

答:
You have a lot of options.  You could make a variable that is an empty list.
Then you can use .append(int) to grow your list.</p>

```<code>randlist = []
for someloop:
    code that generates x
    randlist.append(x)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You have a lot of options.  You could make a variable that is an empty list.
Then you can use .append(int) to grow your list.

randlist = []
for someloop:
    code that generates x
    randlist.append(x)


问:
probelm with angular and firebase cloud messaging
I was trying to work with angular and firebase cloud messaging, and I followed this example step by step, then I am stucked with this error on the console. Can anyone help?
https://medium.com/@a.adendrata/push-notifications-with-angular-6-firebase-cloud-massaging-dbfb5fbc0eeb

Unhandled Promise rejection: PERMISSION_DENIED: Permission denied ; Zone:  ; Task: WebSocket.addEventListener:message ; Value: Error: PERMISSION_DENIED: Permission denied
    at index.cjs.js:13076
    at exceptionGuard (index.cjs.js:690)
    at Repo.push../node_modules/@firebase/database/dist/index.cjs.js.Repo.callOnCompleteCallback (index.cjs.js:13067)
    at index.cjs.js:12880
    at index.cjs.js:12019
    at PersistentConnection.push../node_modules/@firebase/database/dist/index.cjs.js.PersistentConnection.onDataMessage_ (index.cjs.js:12052)

答:
if you can show more code, this would be very helpful

this error is for permissions in firebase you can read this post

Firebase Permission Denied

you can try change this in firebase

{
  "rules": {
    ".read": true,
    ".write": true
  }
}


问:
Why is Eclipse hanging at 57% with the status "Verifying launch attributes..." when launching a run configuration?
After recently converting to Maven from Ant, run configurations that launched immediately pre-Maven take an excessive amount of time and consume an abnormal amount of resources while Eclipse prepares to launch the projects.

Eclipse shows this status message:

```<code>Verifying launch attributes...
</code>```

At 57% completion, Eclipse hangs for several minutes before finally launching the run configuration. Once launched, the project runs fine and without a problem.

I found this blog article that suggested to clean the local workspace, but that did not solve the problem, especially considering the author is using Git and I am not.

I am only using the latest m2e maven plugin, with the latest version of Eclipse.

What is causing Eclipse to block when launching these run configurations, and how can I fix it?

答:
One thing that makes a huge difference is how you tell Eclipse what tests you want to run.

When specifying the project name, our tests could take more than 5 minutes to be discovered (the 57%).

If we rather specify the directory containing the test source files, we are down to less than 30 seconds.

Body:
After recently converting to Maven from Ant, run configurations that launched immediately pre-Maven take an excessive amount of time and consume an abnormal amount of resources while Eclipse prepares to launch the projects.

Eclipse shows this status message:

Verifying launch attributes...

At 57% completion, Eclipse hangs for several minutes before finally launching the run configuration. Once launched, the project runs fine and without a problem.

I found this blog article that suggested to clean the local workspace, but that did not solve the problem, especially considering the author is using Git and I am not.

I am only using the latest m2e maven plugin, with the latest version of Eclipse.

What is causing Eclipse to block when launching these run configurations, and how can I fix it?


问:
Decimal separator comma (',') with numberDecimal inputType in EditText
The inputType numberDecimal in EditText uses the dot . as decimal separator. In Europe it's common to use  a comma , instead. Even though my locale is set as german the decimal separator is still the .

Is there a way to get the comma as decimal separator?

答:
All the other posts here had major holes in them, so here's a solution that will:

Enforce commas or periods based on region, will not let you type the opposite one.

If the EditText starts with some value, it replaces the correct separator as needed.

In the XML:

```<code><EditText
    ...
    android:inputType="numberDecimal"
    ... />
</code>```

Class variable:

```<code>private boolean isDecimalSeparatorComma = false;
</code>```

In onCreate, find the separator used in the current locale:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    NumberFormat nf = NumberFormat.getInstance();
    if (nf instanceof DecimalFormat) {
        DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
        char decSeparator = sym.getDecimalSeparator();
        isDecimalSeparatorComma = Character.toString(decSeparator).equals(",");
    }
}
</code>```

Also onCreate, Use this to update it if you're loading in a current value:

```<code>// Replace editText with commas or periods as needed for viewing
String editTextValue = getEditTextValue(); // load your current value
if (editTextValue.contains(".") && isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll("\\.",",");
} else if (editTextValue.contains(",") && !isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll(",",".");
}
setEditTextValue(editTextValue); // override your current value
</code>```

Also onCreate, Add the Listeners

```<code>editText.addTextChangedListener(editTextWatcher);

if (isDecimalSeparatorComma) {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));
} else {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
}
</code>```

editTextWatcher

```<code>TextWatcher editTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { }

    @Override
    public void afterTextChanged(Editable s) {
        String editTextValue = s.toString();

        // Count up the number of commas and periods
        Pattern pattern = Pattern.compile("[,.]");
        Matcher matcher = pattern.matcher(editTextValue);
        int count = 0;
        while (matcher.find()) {
            count++;
        }

        // Don't let it put more than one comma or period
        if (count > 1) {
            s.delete(s.length()-1, s.length());
        } else {
            // If there is a comma or period at the end the value hasn't changed so don't update
            if (!editTextValue.endsWith(",") && !editTextValue.endsWith(".")) {
                doSomething()
            }
        }
    }
};
</code>```

doSomething() example, convert to standard period for data manipulation

```<code>private void doSomething() {
    try {
        String editTextStr = editText.getText().toString();
        if (isDecimalSeparatorComma) {
            editTextStr = editTextStr.replaceAll(",",".");
        }
        float editTextFloatValue = editTextStr.isEmpty() ?
                0.0f :
                Float.valueOf(editTextStr);

        ... use editTextFloatValue
    } catch (NumberFormatException e) {
        Log.e(TAG, "Error converting String to Double");
    }
}
</code>```

Body:
All the other posts here had major holes in them, so here's a solution that will:

Enforce commas or periods based on region, will not let you type the opposite one.

If the EditText starts with some value, it replaces the correct separator as needed.

In the XML:

<EditText
    ...
    android:inputType="numberDecimal"
    ... />

Class variable:

private boolean isDecimalSeparatorComma = false;

In onCreate, find the separator used in the current locale:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    NumberFormat nf = NumberFormat.getInstance();
    if (nf instanceof DecimalFormat) {
        DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
        char decSeparator = sym.getDecimalSeparator();
        isDecimalSeparatorComma = Character.toString(decSeparator).equals(",");
    }
}

Also onCreate, Use this to update it if you're loading in a current value:

// Replace editText with commas or periods as needed for viewing
String editTextValue = getEditTextValue(); // load your current value
if (editTextValue.contains(".") && isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll("\\.",",");
} else if (editTextValue.contains(",") && !isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll(",",".");
}
setEditTextValue(editTextValue); // override your current value

Also onCreate, Add the Listeners

editText.addTextChangedListener(editTextWatcher);

if (isDecimalSeparatorComma) {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));
} else {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
}

editTextWatcher

TextWatcher editTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { }

    @Override
    public void afterTextChanged(Editable s) {
        String editTextValue = s.toString();

        // Count up the number of commas and periods
        Pattern pattern = Pattern.compile("[,.]");
        Matcher matcher = pattern.matcher(editTextValue);
        int count = 0;
        while (matcher.find()) {
            count++;
        }

        // Don't let it put more than one comma or period
        if (count > 1) {
            s.delete(s.length()-1, s.length());
        } else {
            // If there is a comma or period at the end the value hasn't changed so don't update
            if (!editTextValue.endsWith(",") && !editTextValue.endsWith(".")) {
                doSomething()
            }
        }
    }
};

doSomething() example, convert to standard period for data manipulation

private void doSomething() {
    try {
        String editTextStr = editText.getText().toString();
        if (isDecimalSeparatorComma) {
            editTextStr = editTextStr.replaceAll(",",".");
        }
        float editTextFloatValue = editTextStr.isEmpty() ?
                0.0f :
                Float.valueOf(editTextStr);

        ... use editTextFloatValue
    } catch (NumberFormatException e) {
        Log.e(TAG, "Error converting String to Double");
    }
}


问:
How to send API request to AWS Mturk API (Signature V4) using R
The MturkR package (https://github.com/cloudyr/MTurkR) will stop working on June 1st 2019 as AWS is deprecating the legacy API and this package is only configured for the legacy API.

I imagine many others will need a way to make calls to the MTurk API through R as I don't know of any other R package that can do this.

Can anyone provide some example code of how to make a call to the new mturk API through R? It uses Signature Version 4 which I know can be implemented with the aws.signature package for R but I can't figure out how to generate and send a request to the mturk API. Probably I don't have the request configured correctly, hence an example that works would be fantastic for myself and others. In this example I'm trying to request a GetAssignment operation (https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMturkAPI/ApiReference_GetAssignmentOperation.html).

I have tried to use aws.signature package to generate and send a request, but have not succeeded.

library(aws.signature)

hdrs <- list( Host = "mturk-requester.us-east-1.amazonaws.com",
             `x-amz-date` = "20110909T233600Z"
                 )

hdrs

r <- canonical_request(verb = "POST",
                  canonical_uri="/",
                  query_args=list(),
                  canonical_headers=hdrs,
                  request_body='
                  {
                  "AssignmentId": "3ZURAPD288NZQKK965W2FVL02P6F17"
                }')
r
```

This generates the text of a canonical request but I don't know how to send that to the API and I don't know if any more functions are needed to complete the signature.

Response:

r
  $headers
  [1] "host;x-amz-date"

$body
[1] "1d67d950ce9a1f712609c9c9d794b210d8c78bc0334e54f0fdcb4fd46d65f3f5"

$canonical
[1] "POST\n/\n\nhost:mturk-requester.us-east-1.amazonaws.com\nx-amz-date:20110909T233600Z\n\nhost;x-amz-date\n1d67d950ce9a1f712609c9c9d794b210d8c78bc0334e54f0fdcb4fd46d65f3f5"

$hash
[1] "16814afb1f9c9c5094a8b3ede035365a687c68c7b6dcbe0f688aaeb8b6656f10"

答: I had the same question. Someone published his updated version of MTurkR to Github: https://github.com/cloudyr/pyMTurkR</p>

Body:
The MturkR package (https://github.com/cloudyr/MTurkR) will stop working on June 1st 2019 as AWS is deprecating the legacy API and this package is only configured for the legacy API.

I imagine many others will need a way to make calls to the MTurk API through R as I don't know of any other R package that can do this.

Can anyone provide some example code of how to make a call to the new mturk API through R? It uses Signature Version 4 which I know can be implemented with the aws.signature package for R but I can't figure out how to generate and send a request to the mturk API. Probably I don't have the request configured correctly, hence an example that works would be fantastic for myself and others. In this example I'm trying to request a GetAssignment operation (https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMturkAPI/ApiReference_GetAssignmentOperation.html).

I have tried to use aws.signature package to generate and send a request, but have not succeeded.

library(aws.signature)

hdrs <- list( Host = "mturk-requester.us-east-1.amazonaws.com",
             `x-amz-date` = "20110909T233600Z"
                 )

hdrs

r <- canonical_request(verb = "POST",
                  canonical_uri="/",
                  query_args=list(),
                  canonical_headers=hdrs,
                  request_body='
                  {
                  "AssignmentId": "3ZURAPD288NZQKK965W2FVL02P6F17"
                }')
r

This generates the text of a canonical request but I don't know how to send that to the API and I don't know if any more functions are needed to complete the signature.

Response:

r
  $headers
  [1] "host;x-amz-date"

$body
[1] "1d67d950ce9a1f712609c9c9d794b210d8c78bc0334e54f0fdcb4fd46d65f3f5"

$canonical
[1] "POST\n/\n\nhost:mturk-requester.us-east-1.amazonaws.com\nx-amz-date:20110909T233600Z\n\nhost;x-amz-date\n1d67d950ce9a1f712609c9c9d794b210d8c78bc0334e54f0fdcb4fd46d65f3f5"

$hash
[1] "16814afb1f9c9c5094a8b3ede035365a687c68c7b6dcbe0f688aaeb8b6656f10"


问:
How to save image without cropping?
I'm using Dropzonejs with Cropperjs. The current flow is select an image, crop it and save it.

I want to select an image and give user two options

1) Crop then save

2) Cancel crop and save it without cropping.

The first option is available by default in cropperjs. But How can I add a cancel button which should send the image to dropzone without cropping. In simple words I want the original selected image in dropzone.

Dropzone JS Configuration Code:

```<code>Dropzone.autoDiscover = false;
// Dropzone Configurations
var dropzone = new Dropzone('#story-thumbnail-dropzone-upload', {
  parallelUploads: 1,
  thumbnailHeight: 120,
  thumbnailWidth: 120,
  // Number of Files to allow for UPLOAD
  maxFiles:1,
  init: function() {
        this.on("maxfilesexceeded", function(file) {
              this.removeAllFiles();
              this.addFile(file);
        });
  },
  transformFile: function(file, done) {

        var myDropZone = this;

        // Create the image editor overlay
        var editor = document.createElement('div');
        editor.style.position = 'fixed';
        editor.style.left = 0;
        editor.style.right = 0;
        editor.style.top = 0;
        editor.style.bottom = 0;
        editor.style.zIndex = 9999;
        editor.style.backgroundColor = '#000';

        // Create the confirm button
        var confirm = document.createElement('button');
        confirm.style.position = 'absolute';
        confirm.style.left = '10px';
        confirm.style.top = '10px';
        confirm.style.zIndex = 9999;
        confirm.textContent = 'Crop';
        confirm.addEventListener('click', function() {

            // Get the canvas with image data from Cropper.js
            var canvas = cropper.getCroppedCanvas({
                width: 256,
                height: 256
            });

            // Turn the canvas into a Blob (file object without a name)
            canvas.toBlob(function(blob) {

                // Update the image thumbnail with the new image data
                myDropZone.createThumbnail(
                    blob,
                    myDropZone.options.thumbnailWidth,
                    myDropZone.options.thumbnailHeight,
                    myDropZone.options.thumbnailMethod,
                    false,
                    function(dataURL) {

                        // Update the Dropzone file thumbnail
                        myDropZone.emit('thumbnail', file, dataURL);

                        // Return modified file to dropzone
                        done(blob);
                    }
                );

            });

            // Remove the editor from view
            editor.parentNode.removeChild(editor);

        });
        editor.appendChild(confirm);

        // Load the image
        var image = new Image();
        image.src = URL.createObjectURL(file);
        editor.appendChild(image);

        // Append the editor to the page
        document.body.appendChild(editor);

        // Create Cropper.js and pass image
        var cropper = new Cropper(image, {
            aspectRatio: 1
        });

    },
  filesizeBase: 1000,
  thumbnail: function(file, dataUrl) {
    if (file.previewElement) {
      file.previewElement.classList.remove("dz-file-preview");
      var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
      for (var i = 0; i < images.length; i++) {
        var thumbnailElement = images[i];
        thumbnailElement.alt = file.name;
        thumbnailElement.src = dataUrl;
      }
      setTimeout(function() { file.previewElement.classList.add("dz-image-preview"); }, 1);
    }
  }
});
</code>```

HTML:

```<code><div class="dropzone needsclick" id="story-thumbnail-dropzone-upload" action="/admin/upload-story-thumbnail">
  <div class="dz-message needsclick">
    Drop files here or click to upload.<BR>
  </div>
</div>
</code>```

答:
You can certainly do it by preserving the original file in a global variable easily and then pass that onto dropzone upon click event on your cancel button. I have modified the code and did it for you.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.0.0/cropper.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" />

    Drop files here or click to upload.

```

Title: How to save image without cropping?

Body:
I'm using Dropzonejs with Cropperjs. The current flow is select an image, crop it and save it.

I want to select an image and give user two options

1) Crop then save

2) Cancel crop and save it without cropping.

The first option is available by default in cropperjs. But How can I add a cancel button which should send the image to dropzone without cropping. In simple words I want the original selected image in dropzone.

Dropzone JS Configuration Code:

Dropzone.autoDiscover = false;
// Dropzone Configurations
var dropzone = new Dropzone('#story-thumbnail-dropzone-upload', {
  parallelUploads: 1,
  thumbnailHeight: 120,
  thumbnailWidth: 120,
  // Number of Files to allow for UPLOAD
  maxFiles:1,
  init: function() {
        this.on("maxfilesexceeded", function(file) {
              this.removeAllFiles();
              this.addFile(file);
        });
  },
  transformFile: function(file, done) {

        var myDropZone = this;

        // Create the image editor overlay
        var editor = document.createElement('div');
        editor.style.position = 'fixed';
        editor.style.left = 0;
        editor.style.right = 0;
        editor.style.top = 0;
        editor.style.bottom = 0;
        editor.style.zIndex = 9999;
        editor.style.backgroundColor = '#000';

        // Create the confirm button
        var confirm = document.createElement('button');
        confirm.style.position = 'absolute';
        confirm.style.left = '10px';
        confirm.style.top = '10px';
        confirm.style.zIndex = 9999;
        confirm.textContent = 'Crop';
        confirm.addEventListener('click', function() {

            // Get the canvas with image data from Cropper.js
            var canvas = cropper.getCroppedCanvas({
                width: 256,
                height: 256
            });

            // Turn the canvas into a Blob (file object without a name)
            canvas.toBlob(function(blob) {

                // Update the image thumbnail with the new image data
                myDropZone.createThumbnail(
                    blob,
                    myDropZone.options.thumbnailWidth,
                    myDropZone.options.thumbnailHeight,
                    myDropZone.options.thumbnailMethod,
                    false,
                    function(dataURL) {

                        // Update the Dropzone file thumbnail
                        myDropZone.emit('thumbnail', file, dataURL);

                        // Return modified file to dropzone
                        done(blob);
                    }
                );

            });

            // Remove the editor from view
            editor.parentNode.removeChild(editor);

        });
        editor.appendChild(confirm);

        // Load the image
        var image = new Image();
        image.src = URL.createObjectURL(file);
        editor.appendChild(image);

        // Append the editor to the page
        document.body.appendChild(editor);

        // Create Cropper.js and pass image
        var cropper = new Cropper(image, {
            aspectRatio: 1
        });

    },
  filesizeBase: 1000,
  thumbnail: function(file, dataUrl) {
    if (file.previewElement) {
      file.previewElement.classList.remove("dz-file-preview");
      var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
      for (var i = 0; i < images.length; i++) {
        var thumbnailElement = images[i];
        thumbnailElement.alt = file.name;
        thumbnailElement.src = dataUrl;
      }
      setTimeout(function() { file.previewElement.classList.add("dz-image-preview"); }, 1);
    }
  }
});

HTML:

    Drop files here or click to upload.

Body:
You can certainly do it by preserving the original file in a global variable easily and then pass that onto dropzone upon click event on your cancel button. I have modified the code and did it for you.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.0.0/cropper.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.1/cropper.min.js"></script>
</head>
<body>
  <div class="dropzone needsclick" id="story-thumbnail-dropzone-upload" action="/admin/upload-story-thumbnail">
    <div class="dz-message needsclick">
    Drop files here or click to upload.<BR>
    </div>
  </div>
</body>
</html>

<script>
var originalFile = null;
Dropzone.autoDiscover = false;
// Dropzone Configurations
var dropzone = new Dropzone('#story-thumbnail-dropzone-upload', {
    parallelUploads: 1,
    thumbnailHeight: 120,
    thumbnailWidth: 120,
    // Number of Files to allow for UPLOAD
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    },
    transformFile: function(file, done) {

      originalFile = file;

        var myDropZone = this;

        // Create the image editor overlay
        var editor = document.createElement('div');
        editor.classList.add('cropCanvas');
        editor.style.position = 'fixed';
        editor.style.left = 0;
        editor.style.right = 0;
        editor.style.top = 0;
        editor.style.bottom = 0;
        editor.style.zIndex = 9999;
        editor.style.backgroundColor = '#000';

        // Create the confirm button
        var confirm = document.createElement('button');
        confirm.style.left = '10px';
        confirm.style.top = '10px';
        confirm.style.zIndex = 9999;
        confirm.textContent = 'Crop';
        confirm.addEventListener('click', function() {

            // Get the canvas with image data from Cropper.js
            var canvas = cropper.getCroppedCanvas({
                width: 256,
                height: 256
            });

            // Turn the canvas into a Blob (file object without a name)
            canvas.toBlob(function(blob) {

                // Update the image thumbnail with the new image data
                myDropZone.createThumbnail(
                    blob,
                    myDropZone.options.thumbnailWidth,
                    myDropZone.options.thumbnailHeight,
                    myDropZone.options.thumbnailMethod,
                    false,
                    function(dataURL) {

                        // Update the Dropzone file thumbnail
                        myDropZone.emit('thumbnail', file, dataURL);

                        // Return modified file to dropzone
                        done(blob);
                      console.log(blob);
                    }
                );

            });

            // Remove the editor from view
            editor.parentNode.removeChild(editor);

        });

        // Create the cancel button
        var cancel = document.createElement('button');
        cancel.style.position = 'absolute';
        cancel.style.left = '50px';
        cancel.style.top = '0px';
        cancel.style.zIndex = 9999;
        cancel.textContent = 'Cancel';
        cancel.style.position = 'absolute';
        cancel.addEventListener('click', function() {

         done(originalFile);

         // Remove the editor from view
         editor.parentNode.removeChild(editor);

        });
        editor.appendChild(confirm);
        editor.appendChild(cancel);

        // Load the image
        var image = new Image();
        image.src = URL.createObjectURL(file);
        // Just added width for not having extra space to show the image in a limited available space
        // REMOVE THIS THEN!!!!
        image.width = '500px';
        editor.appendChild(image);

        // Append the editor to the page
        document.body.appendChild(editor);

        // Create Cropper.js and pass image
        var cropper = new Cropper(image, {
            aspectRatio: 1
        });

    },
    filesizeBase: 1000,
    thumbnail: function(file, dataUrl) {
        if (file.previewElement) {
            file.previewElement.classList.remove("dz-file-preview");
            var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
            for (var i = 0; i < images.length; i++) {
                var thumbnailElement = images[i];
                thumbnailElement.alt = file.name;
                thumbnailElement.src = dataUrl;
            }
            setTimeout(function() {
                file.previewElement.classList.add("dz-image-preview");
            }, 1);
        }
    }
});
</script>


问:
awscli fails to work: No module named 'awscli'
I am trying to install awscli using pip3 on Linux Mint 17.2 Rafaela.

I am getting the error:

```<code>Traceback (most recent call last):
  File "/home/jonathan/.local/bin/aws", line 19, in <module>
    import awscli.clidriver
ImportError: No module named 'awscli'
</code>```

These are the steps I am taking, following the aws installation guide:

```<code>sudo pip install awscli --upgrade --user
</code>```

everything seems to install fine.

adding to my .bashrc

```<code>export PATH=~/.local/bin:$PATH
</code>```

then

```<code>source ~/.bashrc
</code>```

then i try the command

```<code>aws --version
</code>```

and i get

```<code>Traceback (most recent call last):
  File "/home/jonathan/.local/bin/aws", line 19, in <module>
    import awscli.clidriver
ImportError: No module named 'awscli'
</code>```

Can anyone help with this?

EDIT: For anyone visiting this question. There is no way I can test any of these answers because I have since removed this OS and installed Ubuntu. Also I have no need for awscli anymore.

答: I had this problem. On first attempt at installation I had not used the --upgrade option. When I retried the install with --upgrade it worked. Also you don't need to use sudo if you are using --user. </p>

Body:
I am trying to install awscli using pip3 on Linux Mint 17.2 Rafaela.

I am getting the error:

Traceback (most recent call last):
  File "/home/jonathan/.local/bin/aws", line 19, in <module>
    import awscli.clidriver
ImportError: No module named 'awscli'

These are the steps I am taking, following the aws installation guide:

sudo pip install awscli --upgrade --user

everything seems to install fine.

adding to my .bashrc

export PATH=~/.local/bin:$PATH

then

source ~/.bashrc

then i try the command

aws --version

and i get

Traceback (most recent call last):
  File "/home/jonathan/.local/bin/aws", line 19, in <module>
    import awscli.clidriver
ImportError: No module named 'awscli'

Can anyone help with this?

EDIT: For anyone visiting this question. There is no way I can test any of these answers because I have since removed this OS and installed Ubuntu. Also I have no need for awscli anymore.


问:
base64 decoding of a dataframe
I have an encoded dataframe and I managed to get it decoded using following code in PySpark. Is there any simple way where I can have an additional column in the dataframe itself through Scala/PySpark?

```<code>import base64
import numpy as np
df = spark.read.parquet("file_path")
encodedColumn = base64.decodestring(df.take(1)[0].column2)
t1 = np.frombuffer(encodedColumn ,dtype='<f4')
</code>```

I looked up multiple similar questions, but couldnt get them to work.

Edit:
Got it working with help from a colleague.

```<code>def binaryToFloatArray(stringValue: String): Array[Float] = {
val t:Array[Byte] = Base64.getDecoder().decode(stringValue)
val b = ByteBuffer.wrap(t).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
val copy = new Array[Float](2048)
b.get(copy)
return copy
}
val binaryToFloatArrayUDF = udf(binaryToFloatArray _)
val finalResultDf = dftest.withColumn("myFloatArray", binaryToFloatArrayUDF(col("_2"))).drop("_2")
</code>```

答:
You have base64 and unbase64 functions for this.

http://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=streaming#pyspark.sql.functions.base64

You could

```<code>    from pyspark.sql.functions import unbase64,base64
    got = spark.createDataFrame([(1, "Jon"), (2, "Danny"), (3, "Tyrion")], ("id", "name"))

+---+------+
| id|  name|
+---+------+
|  1|   Jon|
|  2| Danny|
|  3|Tyrion|
+---+------+

encoded_got = got.withColumn('encoded_base64_name', base64(got.name))

+---+------+-------------------+
| id|  name|encoded_base64_name|
+---+------+-------------------+
|  1|   Jon|               Sm9u|
|  2| Danny|           RGFubnk=|
|  3|Tyrion|           VHlyaW9u|
+---+------+-------------------+

decoded_got = encoded_got.withColumn('decoded_base64', unbase64(encoded_got.encoded_base64).cast("string"))
# Need to use cast("string") to convert from binary to string

+---+------+--------------+--------------+
| id|  name|encoded_base64|decoded_base64|
+---+------+--------------+--------------+
|  1|   Jon|          Sm9u|           Jon|
|  2| Danny|      RGFubnk=|         Danny|
|  3|Tyrion|      VHlyaW9u|        Tyrion|
+---+------+--------------+--------------+
</code>```

Title: base64 decoding of a dataframe

Body:
I have an encoded dataframe and I managed to get it decoded using following code in PySpark. Is there any simple way where I can have an additional column in the dataframe itself through Scala/PySpark?

import base64
import numpy as np
df = spark.read.parquet("file_path")
encodedColumn = base64.decodestring(df.take(1)[0].column2)
t1 = np.frombuffer(encodedColumn ,dtype='<f4')

I looked up multiple similar questions, but couldnt get them to work.

Edit:
Got it working with help from a colleague.

def binaryToFloatArray(stringValue: String): Array[Float] = {
val t:Array[Byte] = Base64.getDecoder().decode(stringValue)
val b = ByteBuffer.wrap(t).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
val copy = new Array[Float](2048)
b.get(copy)
return copy
}
val binaryToFloatArrayUDF = udf(binaryToFloatArray _)
val finalResultDf = dftest.withColumn("myFloatArray", binaryToFloatArrayUDF(col("_2"))).drop("_2")

Body:
You have base64 and unbase64 functions for this.

http://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=streaming#pyspark.sql.functions.base64

You could

    from pyspark.sql.functions import unbase64,base64
    got = spark.createDataFrame([(1, "Jon"), (2, "Danny"), (3, "Tyrion")], ("id", "name"))

+---+------+
| id|  name|
+---+------+
|  1|   Jon|
|  2| Danny|
|  3|Tyrion|
+---+------+

encoded_got = got.withColumn('encoded_base64_name', base64(got.name))

+---+------+-------------------+
| id|  name|encoded_base64_name|
+---+------+-------------------+
|  1|   Jon|               Sm9u|
|  2| Danny|           RGFubnk=|
|  3|Tyrion|           VHlyaW9u|
+---+------+-------------------+

decoded_got = encoded_got.withColumn('decoded_base64', unbase64(encoded_got.encoded_base64).cast("string"))
# Need to use cast("string") to convert from binary to string

+---+------+--------------+--------------+
| id|  name|encoded_base64|decoded_base64|
+---+------+--------------+--------------+
|  1|   Jon|          Sm9u|           Jon|
|  2| Danny|      RGFubnk=|         Danny|
|  3|Tyrion|      VHlyaW9u|        Tyrion|
+---+------+--------------+--------------+


问:
How to limit memory usage in docker-compose?
Here is part of my docker-compose.yaml file

```<code>version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M
</code>```

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

```<code>CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%
</code>```

答:
If you not intend to use docker swarm stack deployments, always stick to the latest 2.x version supported by the docker engine version you operate. Docker versions 17.12 and later support compose file version 2.4. Docker-Compose has all features the cli provides, while swarm still lacks some of those: see https://github.com/moby/moby/issues/25303.

If you use docker-compose, all swarm related elements in a 3.x file will be ignorend, except secrets (or was it configs?!). If you start to mix 3.x only elements with 2.x only elements, your configuration will become invalid.

Body:
Here is part of my docker-compose.yaml file

version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%


问:
How to programmatically resend messages that have faulted with EasyNetQ?
I am wondering how to resend messages that have faulted with EasyNetQ, programmatically, without using HosePipe, that is to resend to their original target queue using their original sending exchange.

Is it possible, how?

答:
The solution I came up with is:</p>

```<code>public static class AdvancedBusExtensions
{
    public static async Task ResendErrorsAsync(this IAdvancedBus source, string errorQueueName)
    {
        var errorQueue = await source.QueueDeclareAsync(errorQueueName);
        var message = await source.GetMessageAsync(errorQueue);
        while (message != null)
        {
            var utf8Body = Encoding.UTF8.GetString(message.Body);
            var error = JsonConvert.DeserializeObject<Error>(utf8Body);
            var errorBodyBytes = Encoding.UTF8.GetBytes(error.Message);
            var exchange = await source.ExchangeDeclareAsync(error.Exchange, x =>
            {
                // This can be adjusted to fit the exchange actual configuration
                x.AsDurable(true);
                x.AsAutoDelete(false);
                x.WithType("topic");
            });
            await source.PublishAsync(exchange, error.RoutingKey, true, error.BasicProperties, errorBodyBytes);
            message = await source.GetMessageAsync(errorQueue);
        }
    }
}
</code>```

Body:
The solution I came up with is:

public static class AdvancedBusExtensions
{
    public static async Task ResendErrorsAsync(this IAdvancedBus source, string errorQueueName)
    {
        var errorQueue = await source.QueueDeclareAsync(errorQueueName);
        var message = await source.GetMessageAsync(errorQueue);
        while (message != null)
        {
            var utf8Body = Encoding.UTF8.GetString(message.Body);
            var error = JsonConvert.DeserializeObject<Error>(utf8Body);
            var errorBodyBytes = Encoding.UTF8.GetBytes(error.Message);
            var exchange = await source.ExchangeDeclareAsync(error.Exchange, x =>
            {
                // This can be adjusted to fit the exchange actual configuration
                x.AsDurable(true);
                x.AsAutoDelete(false);
                x.WithType("topic");
            });
            await source.PublishAsync(exchange, error.RoutingKey, true, error.BasicProperties, errorBodyBytes);
            message = await source.GetMessageAsync(errorQueue);
        }
    }
}


问:
How to set some value in express backend server.js file and use it in create-react-app code?
I have a simple create-react-app with a express backend with only 1 file (server.js) whose job is to just execute build folder and start the web app.

server.js code looks like below:

```<code>const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express()
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})

// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})
</code>```

Below is how my react app starts?

```<code>"scripts": {
    "postinstall": "npm run build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "NODE_ENV=prod node server.js",
    "develop": "react-scripts start"
  },
</code>```

What I'm trying to achieve now?

1.) My create-react-app is having some components like drop-downs, radio-buttons etc and based upon some selections fetch rest-api calls are done in react code app.js etc and accordingly data came in the response is loaded on the page.

2.) Now, there are two rest-api end-points. One is dev and one is prod.
For eg: www.example-dev.com/ , www.example-prod.com/.

3.) So, based upon what cloud environment is determined in server.js code using process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' on which my create-react-app is running, i want to call respective rest-api end point like www.example-{env}.com/

4.) So, i want to know the right way to set this value in server.js and use it in the react-app some component class wherever i want.

For eg:

Below is some react component piece of code, where i want to use env value set in server.js:

```<code> handleOnChange = async selectedObj => {

      let responseObj = await callRestAPI(`www.example-${env}.com`);
      this.props.onChange(selectedObj);
  };
</code>```

Please help.

答:
There are multiple ways to do this, here are few different ways

Using create react app docs REACT_APP thing

Use a templating engine for index.html

have endpoint as /config

create a js file dynamically, include it in your index.html

1 to 3 ways you can find doc online

for 4th way here is how you can do

```<code>fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : ${process.env.ENVIRONMENT_NAME}}`);
</code>```

Make sure you do this before express.static

With your code above, here is how it looks

```<code>const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express();
const fs = require('fs');
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})

fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : "${process.env.ENVIRONMENT_NAME}"}`);

// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})
</code>```

update your index.html to use our new js file

```<code><script src="./config.js"></script>
</code>```

in your react component, you can access by

```<code>console.log(window.SERVER_DATA)
</code>```

working example:

https://codesandbox.io/embed/express-5o8ei

Body:
I have a simple create-react-app with a express backend with only 1 file (server.js) whose job is to just execute build folder and start the web app.

server.js code looks like below:

const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express()
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})

// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})

Below is how my react app starts?

"scripts": {
    "postinstall": "npm run build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "NODE_ENV=prod node server.js",
    "develop": "react-scripts start"
  },

What I'm trying to achieve now?

1.) My create-react-app is having some components like drop-downs, radio-buttons etc and based upon some selections fetch rest-api calls are done in react code app.js etc and accordingly data came in the response is loaded on the page.

2.) Now, there are two rest-api end-points. One is dev and one is prod.
For eg: www.example-dev.com/ , www.example-prod.com/.

3.) So, based upon what cloud environment is determined in server.js code using process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' on which my create-react-app is running, i want to call respective rest-api end point like www.example-{env}.com/

4.) So, i want to know the right way to set this value in server.js and use it in the react-app some component class wherever i want.

For eg:

Below is some react component piece of code, where i want to use env value set in server.js:

 handleOnChange = async selectedObj => {

      let responseObj = await callRestAPI(`www.example-${env}.com`);
      this.props.onChange(selectedObj);
  };

Please help.

Body:
There are multiple ways to do this, here are few different ways

Using create react app docs REACT_APP thing

Use a templating engine for index.html

have endpoint as /config

create a js file dynamically, include it in your index.html

1 to 3 ways you can find doc online

for 4th way here is how you can do

fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : ${process.env.ENVIRONMENT_NAME}}`);

Make sure you do this before express.static

With your code above, here is how it looks

const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express();
const fs = require('fs');
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})

fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : "${process.env.ENVIRONMENT_NAME}"}`);

// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})

update your index.html to use our new js file

<script src="./config.js"></script>

in your react component, you can access by

console.log(window.SERVER_DATA)

working example:

https://codesandbox.io/embed/express-5o8ei


问:
Java scanner to read character frequency from file
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.</p>

```<code>public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}
</code>```

答:
I would recommend using a simple map instead of a priority queue. Using Files.lines() and Java Stream you can use this:

```<code>public static Map<String, Long> build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    }
    try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
        return lines.map(s -> s.split("")).flatMap(Arrays::stream)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}
</code>```

If you need the order of the characters you can use a LinkedHashMap, which stays in insertion order. Change the collector of my above example to this:

```<code>Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())
</code>```

Body:
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.

public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}

Body:
I would recommend using a simple map instead of a priority queue. Using Files.lines() and Java Stream you can use this:

public static Map<String, Long> build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    }
    try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
        return lines.map(s -> s.split("")).flatMap(Arrays::stream)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}

If you need the order of the characters you can use a LinkedHashMap, which stays in insertion order. Change the collector of my above example to this:

Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())


问:
jquery validation for Date "MM/YYYY"
I am using jQuery Validation Plugin ( http://jqueryvalidation.org ) for credit card validation. How can i make them to put exactly date in mm/yyyy format using this plugin?

```<code>jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$('form[name="submit_cc"]').validate({
  rules: {
    holder_name: {
      required: true,

    },
      cardnumber: {
      required: true,
      creditcard: true
    }

  }
});
</code>```

Thank you for answers.

答:
May will important to validate if the month is a month and the year is a year. I did a little change in the regex pattern to help.

```<code>$.validator.addMethod('cardexpiry', function( value, element ) {
  return value.match("(0[123456789]|10|11|12)([/])([1-2][0-9][0-9][0-9])");
}, "Precisa ser no formato mm/aaaa" );
</code>```

UPDATE FOR 2020's

```<code>$.validator.addMethod('cardexpiry', function( value, element ) {
  return value.match("(0[123456789]|10|11|12)([/])([2][0][2|3][0-9])");
}, "Parece que tem algo errado"   );
</code>```

Title: jquery validation for Date "MM/YYYY"

Body:
I am using jQuery Validation Plugin ( http://jqueryvalidation.org ) for credit card validation. How can i make them to put exactly date in mm/yyyy format using this plugin?

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$('form[name="submit_cc"]').validate({
  rules: {
    holder_name: {
      required: true,

    },
      cardnumber: {
      required: true,
      creditcard: true
    }

  }
});

Thank you for answers.

Body:
May will important to validate if the month is a month and the year is a year. I did a little change in the regex pattern to help.

$.validator.addMethod('cardexpiry', function( value, element ) {
  return value.match("(0[123456789]|10|11|12)([/])([1-2][0-9][0-9][0-9])");
}, "Precisa ser no formato mm/aaaa" );

UPDATE FOR 2020's

$.validator.addMethod('cardexpiry', function( value, element ) {
  return value.match("(0[123456789]|10|11|12)([/])([2][0][2|3][0-9])");
}, "Parece que tem algo errado"   );


答:
You can provide an environment variable that starts with REACT_APP_ for example REACT_APP_ENVIRONMENT_NAME

And in your react code you can access it like this:

```<code>let env = process.env.REACT_APP_ENVIRONMENT_NAME;
let responseObj = await callRestAPI(`www.example-${env}.com`);
</code>```

You can also update the build script to pass the variable like this

```<code>"build": "REACT_APP_ENVIRONMENT_NAME=$ENVIRONMENT_NAME react-scripts build",
</code>```

Title: How to set some value in express backend server.js file and use it in create-react-app code?

Body:
You can provide an environment variable that starts with REACT_APP_ for example REACT_APP_ENVIRONMENT_NAME

And in your react code you can access it like this:

let env = process.env.REACT_APP_ENVIRONMENT_NAME;
let responseObj = await callRestAPI(`www.example-${env}.com`);

You can also update the build script to pass the variable like this

"build": "REACT_APP_ENVIRONMENT_NAME=$ENVIRONMENT_NAME react-scripts build",


问:
Why is my SQLite database file not showing any data?
Aim -

I am trying to store longitude and latitude data from the geolocation API using React native. I created a .db file put it into the /assets/ folder in android. First, instead of the location data, I am trying to insert or retrieve any kind of data.
ERROR -

It shows that there is no table named Test when I try to console.log() it.

Problem -

Whenever I try to insert data into the database I don't see any new data added and also When I try to read an already populated database I see nothing. Where am I wrong? I am fairly new to this.

What is the response returned by the SQL transaction. I console.log it but couldn't understand.

Where should be the transaction function be located?

I am using DBbrowser for SQLite
OS - MacOS

CODE -

```<code>I am using this function to send or receive data.

sendData = () => {
        // var SQLite = require('react-native-sqlite-storage')
        var db = SQLite.openDatabase({name: 'a', createFromLocation : "~test.sqlite"}, this.openCB, this.errorCB);
        db.transaction(txn => {
        txn.executeSql(
        //   "INSERT INTO Test (latitude,longitude) VALUES(?,?)",
        'SELECT * FROM Test',
          [],      //Argument to pass for the prepared statement
          (res) => {
            // let row = res.rows.(1);
            console.log(res);
          }   //Callback function to handle the result response
        );
      });
    };

// I mapped this button to send data.

<TouchableOpacity onPress={this.sendData} style={styles.button}>
<Text> SEND DATA</Text
</TouchableOpacity>
</code>```

答:
You won't be able to modify a database stored in the assets folder.  The typical method is before ever trying to open the database to insert records, you first check to see if the database exists in your apps data folder (not sure if React has the same folder structures or not).  If the database doesn't exist in the data folder, then you copy your clean database from assets to the data folder, then open the database from the data folder.  As long as the app isn't deleted off the device, the database in the data folder will persist, along with all of the data you have inserted into it.  Once the app has been deleted and reinstalled, the database will have to be copied from assets once again and will be clean, with no new data in it.

I don't know if the same data folder structure applies to React, but in native Android I use:

```<code> "/data/data/com.mycompany.myapp/databases/"
</code>```

OR

```<code>DB_PATH = myContext.getFilesDir().getParentFile().getPath() + "/databases/";
</code>```

Body:
Aim -

I am trying to store longitude and latitude data from the geolocation API using React native. I created a .db file put it into the /assets/ folder in android. First, instead of the location data, I am trying to insert or retrieve any kind of data.
ERROR -

It shows that there is no table named Test when I try to console.log() it.

Problem -

Whenever I try to insert data into the database I don't see any new data added and also When I try to read an already populated database I see nothing. Where am I wrong? I am fairly new to this.

What is the response returned by the SQL transaction. I console.log it but couldn't understand.

Where should be the transaction function be located?

I am using DBbrowser for SQLite
OS - MacOS

CODE -

I am using this function to send or receive data.

sendData = () => {
        // var SQLite = require('react-native-sqlite-storage')
        var db = SQLite.openDatabase({name: 'a', createFromLocation : "~test.sqlite"}, this.openCB, this.errorCB);
        db.transaction(txn => {
        txn.executeSql(
        //   "INSERT INTO Test (latitude,longitude) VALUES(?,?)",
        'SELECT * FROM Test',
          [],      //Argument to pass for the prepared statement
          (res) => {
            // let row = res.rows.(1);
            console.log(res);
          }   //Callback function to handle the result response
        );
      });
    };

// I mapped this button to send data.

<TouchableOpacity onPress={this.sendData} style={styles.button}>
<Text> SEND DATA</Text
</TouchableOpacity>

Body:
You won't be able to modify a database stored in the assets folder.  The typical method is before ever trying to open the database to insert records, you first check to see if the database exists in your apps data folder (not sure if React has the same folder structures or not).  If the database doesn't exist in the data folder, then you copy your clean database from assets to the data folder, then open the database from the data folder.  As long as the app isn't deleted off the device, the database in the data folder will persist, along with all of the data you have inserted into it.  Once the app has been deleted and reinstalled, the database will have to be copied from assets once again and will be clean, with no new data in it.

I don't know if the same data folder structure applies to React, but in native Android I use:

 "/data/data/com.mycompany.myapp/databases/"

OR

DB_PATH = myContext.getFilesDir().getParentFile().getPath() + "/databases/";


问:
Kubernetes - delete all jobs in bulk
I can delete all jobs inside a custer running

```<code>kubectl delete jobs --all
</code>```

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?

答:
kubectl delete jobs --all --cascade=false is fast, but won't delete associated resources, such as Pods

https://github.com/kubernetes/kubernetes/issues/8598

Title: Kubernetes - delete all jobs in bulk

Body:
I can delete all jobs inside a custer running

kubectl delete jobs --all

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?


问:
Pandas: Handling Dataframes
A certain dataframe, has a similar break with the one below:

```<code>import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})
</code>```

How can I make a filter to return only the rows where the values in the document column are only 3 digits?

答:
```<code>df[df.document.apply(lambda x: len(str(x)) == 3)]
</code>```

Title: Pandas: Handling Dataframes

Body:
A certain dataframe, has a similar break with the one below:

import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})

How can I make a filter to return only the rows where the values in the document column are only 3 digits?


问:
How to programmatically transfer a lot of data between tables?
i have two tables where in the first one i have 14 millions and in the second one i have 1.5 million of data.

So i wonder how could i transfer this data to another table to be normalized ?
And how do i convert some type to another, for example: i have a field called 'year' but its type is varchar, but i want it an integer instead, how do i do that ?

I thought about do this using JDBC in a loop while from java, but i think this is not effeciently.

```<code>// 1.5 million of data
CREATE TABLE dbo.directorsmovies
    (
    movieid    INT NULL,
    directorid INT NULL,
    dname      VARCHAR (500) NULL,
    addition   VARCHAR (1000) NULL
    )

//14 million of data
CREATE TABLE dbo.movies
    (
    movieid      VARCHAR (20) NULL,
    title        VARCHAR (400) NULL,
    mvyear       VARCHAR (100) NULL,
    actorid      VARCHAR (20) NULL,
    actorname    VARCHAR (250) NULL,
    sex          CHAR (1) NULL,
    as_character VARCHAR (1500) NULL,
    languages    VARCHAR (1500) NULL,
    genres       VARCHAR (100) NULL
    )
</code>```

And this is my new tables:

```<code>DROP TABLE actor
CREATE TABLE actor (
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    sex VARCHAR(1) NOT NULL
)

DROP TABLE actor_character
CREATE TABLE actor_character(
    id INT PRIMARY KEY IDENTITY,
    character VARCHAR(100)
)

DROP TABLE director
CREATE TABLE director(
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    addition VARCHAR(150)
)

DROP TABLE movie
CREATE TABLE movie(
    id INT PRIMARY KEY IDENTITY,
    title VARCHAR(200) NOT NULL,
    year INT
)

DROP TABLE language
CREATE TABLE language(
    id INT PRIMARY KEY IDENTITY,
    language VARCHAR (100) NOT NULL
)

DROP TABLE genre
CREATE TABLE genre(
    id INT PRIMARY KEY IDENTITY,
    genre VARCHAR(100) NOT NULL
)

DROP TABLE director_movie
CREATE TABLE director_movie(
    idDirector INT,
    idMovie INT,
    CONSTRAINT fk_director_movie_1 FOREIGN KEY (idDirector) REFERENCES director(id),
    CONSTRAINT fk_director_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_director_movie PRIMARY KEY(idDirector,idMovie)
)

DROP TABLE genre_movie
CREATE TABLE genre_movie(
    idGenre INT,
    idMovie INT,
    CONSTRAINT fk_genre_movie_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_genre_movie_2 FOREIGN KEY (idGenre) REFERENCES genre(id),
    CONSTRAINT pk_genre_movie PRIMARY KEY (idMovie, idGenre)
)

DROP TABLE language_movie
CREATE TABLE language_movie(
    idLanguage INT,
    idMovie INT,
    CONSTRAINT fk_language_movie_1 FOREIGN KEY (idLanguage) REFERENCES language(id),
    CONSTRAINT fk_language_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_language_movie PRIMARY KEY (idLanguage, idMovie)
)

DROP TABLE movie_actor
CREATE TABLE movie_actor(
    idMovie INT,
    idActor INT,
    CONSTRAINT fk_movie_actor_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_movie_actor_2 FOREIGN KEY (idActor) REFERENCES actor(id),
    CONSTRAINT pk_movie_actor PRIMARY KEY (idMovie,idActor)
)
</code>```

UPDATE:
I'm using SQL Server 2008.
Sorry guys i forgot to mention that are different databases :

The not normalized is call disciplinedb and the my normalized call imdb.

Best regards,
Valter Henrique.

答: I just recently did this for ~150 Gb of data.  I used a pair of merge statements for each table.  The first merge statement said "if it's not in the destination table, copy it there" and the second said "if it's in the destination table, delete it from the source".  I put both in a while loop and only did 10000 rows in each operation at a time.  Keeping it on the server (and not transferring it through a client) is going to be a huge boon for performance.  Give it a shot!</p>

Body:
i have two tables where in the first one i have 14 millions and in the second one i have 1.5 million of data.

So i wonder how could i transfer this data to another table to be normalized ?
And how do i convert some type to another, for example: i have a field called 'year' but its type is varchar, but i want it an integer instead, how do i do that ?

I thought about do this using JDBC in a loop while from java, but i think this is not effeciently.

// 1.5 million of data
CREATE TABLE dbo.directorsmovies
    (
    movieid    INT NULL,
    directorid INT NULL,
    dname      VARCHAR (500) NULL,
    addition   VARCHAR (1000) NULL
    )

//14 million of data
CREATE TABLE dbo.movies
    (
    movieid      VARCHAR (20) NULL,
    title        VARCHAR (400) NULL,
    mvyear       VARCHAR (100) NULL,
    actorid      VARCHAR (20) NULL,
    actorname    VARCHAR (250) NULL,
    sex          CHAR (1) NULL,
    as_character VARCHAR (1500) NULL,
    languages    VARCHAR (1500) NULL,
    genres       VARCHAR (100) NULL
    )

And this is my new tables:

DROP TABLE actor
CREATE TABLE actor (
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    sex VARCHAR(1) NOT NULL
)

DROP TABLE actor_character
CREATE TABLE actor_character(
    id INT PRIMARY KEY IDENTITY,
    character VARCHAR(100)
)

DROP TABLE director
CREATE TABLE director(
    id INT PRIMARY KEY IDENTITY,
    name VARCHAR(200) NOT NULL,
    addition VARCHAR(150)
)

DROP TABLE movie
CREATE TABLE movie(
    id INT PRIMARY KEY IDENTITY,
    title VARCHAR(200) NOT NULL,
    year INT
)

DROP TABLE language
CREATE TABLE language(
    id INT PRIMARY KEY IDENTITY,
    language VARCHAR (100) NOT NULL
)

DROP TABLE genre
CREATE TABLE genre(
    id INT PRIMARY KEY IDENTITY,
    genre VARCHAR(100) NOT NULL
)

DROP TABLE director_movie
CREATE TABLE director_movie(
    idDirector INT,
    idMovie INT,
    CONSTRAINT fk_director_movie_1 FOREIGN KEY (idDirector) REFERENCES director(id),
    CONSTRAINT fk_director_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_director_movie PRIMARY KEY(idDirector,idMovie)
)

DROP TABLE genre_movie
CREATE TABLE genre_movie(
    idGenre INT,
    idMovie INT,
    CONSTRAINT fk_genre_movie_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_genre_movie_2 FOREIGN KEY (idGenre) REFERENCES genre(id),
    CONSTRAINT pk_genre_movie PRIMARY KEY (idMovie, idGenre)
)

DROP TABLE language_movie
CREATE TABLE language_movie(
    idLanguage INT,
    idMovie INT,
    CONSTRAINT fk_language_movie_1 FOREIGN KEY (idLanguage) REFERENCES language(id),
    CONSTRAINT fk_language_movie_2 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT pk_language_movie PRIMARY KEY (idLanguage, idMovie)
)

DROP TABLE movie_actor
CREATE TABLE movie_actor(
    idMovie INT,
    idActor INT,
    CONSTRAINT fk_movie_actor_1 FOREIGN KEY (idMovie) REFERENCES movie(id),
    CONSTRAINT fk_movie_actor_2 FOREIGN KEY (idActor) REFERENCES actor(id),
    CONSTRAINT pk_movie_actor PRIMARY KEY (idMovie,idActor)
)

UPDATE:
I'm using SQL Server 2008.
Sorry guys i forgot to mention that are different databases :

The not normalized is call disciplinedb and the my normalized call imdb.

Best regards,
Valter Henrique.


答:
Try // which will return the divisor of 1000, since 3 digit so the divisor should be 0

```<code>df[df.document//1000==0]
Out[474]:
      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333
</code>```

We convert to str then count the len

```<code>df[df.document.astype(str).str.len().eq(3)]
Out[476]:
      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333
</code>```

Update

```<code>df[df.document.astype(str).str.split('.').str[0].str.len().eq(3)]
</code>```

Title: Pandas: Handling Dataframes

Body:
Try // which will return the divisor of 1000, since 3 digit so the divisor should be 0

df[df.document//1000==0]
Out[474]:
      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333

We convert to str then count the len

df[df.document.astype(str).str.len().eq(3)]
Out[476]:
      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333

Update

df[df.document.astype(str).str.split('.').str[0].str.len().eq(3)]


问:
Web Config Transform not working
In a .NET MVC 3.0 Application I have the following configuration in appSettings:

web.config

```<code><appSettings>
<add key="SMTPHost" value="mail.domain.com"/>
    <add key="SMTPUsername" value="user@gmail.com"/>
    <add key="SMTPPort" value="25"/>
    <add key="SMTPPwd" value="mypassword"/>
    <add key="EmailFrom" value="notific@gmail.com"/>
</appSettings>
</code>```

For debugging, I have the following configuration transform defined:

web.Debug.config

```<code><appSettings>
    <add  key="SMTPPort" value="58" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
</code>```

And I run the application in debug mode, but my SMTP port is still taking the value from the web.config, not web.Debug.config.

Can anyone suggest what could be wrong in this configuration?

答:
for VS 2017 I found the answer here not sure why nobody has referenced it above as it appears to be a very popular solution.  Very easy too.  Make sure you see the comment from IOrlandoni on Mar5 2019 for making it work in VS 2017 and all versions.

Basically its a two stepper.  First, you edit the .csproj file, appending the code below.  Second, you create a new web.base.config configuration and copy the existing web.config there.  After doing that any build will overwrite your web.config with your desired transformation.

```<code><Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets" />
<Target Name="BeforeBuild">
    <TransformXml Source="Web.Base.config"
        Transform="Web.$(Configuration).config" Destination="Web.config" />
</Target>
</code>```

Title: Web Config Transform not working

Body:
In a .NET MVC 3.0 Application I have the following configuration in appSettings:

web.config

<appSettings>
<add key="SMTPHost" value="mail.domain.com"/>
    <add key="SMTPUsername" value="user@gmail.com"/>
    <add key="SMTPPort" value="25"/>
    <add key="SMTPPwd" value="mypassword"/>
    <add key="EmailFrom" value="notific@gmail.com"/>
</appSettings>

For debugging, I have the following configuration transform defined:

web.Debug.config

<appSettings>
    <add  key="SMTPPort" value="58" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>

And I run the application in debug mode, but my SMTP port is still taking the value from the web.config, not web.Debug.config.

Can anyone suggest what could be wrong in this configuration?

Body:
for VS 2017 I found the answer here not sure why nobody has referenced it above as it appears to be a very popular solution.  Very easy too.  Make sure you see the comment from IOrlandoni on Mar5 2019 for making it work in VS 2017 and all versions.

Basically its a two stepper.  First, you edit the .csproj file, appending the code below.  Second, you create a new web.base.config configuration and copy the existing web.config there.  After doing that any build will overwrite your web.config with your desired transformation.

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets" />
<Target Name="BeforeBuild">
    <TransformXml Source="Web.Base.config"
        Transform="Web.$(Configuration).config" Destination="Web.config" />
</Target>


问:
MySQL ERROR 1005 : Can't create table (errno: 150)
Im a beginner in mysql, i don't understand my mistake
its a problem with the foreign key of "membre" and "club".

```<code>CREATE TABLE club(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) UNIQUE NOT NULL,
    INDEX club_nom_index (nom),
    adresse_id INT NOT NULL,
    nom_du_responsable VARCHAR(255) NULL,

    FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);

CREATE TABLE membre(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    prénom VARCHAR(255) NOT NULL,
    adresse_id INT NOT NULL,
    club_id INT NOT NULL,
    rang_qualification INT NOT NULL,
    numéro_téléphone VARCHAR(255) NULL,
    courriel VARCHAR(255) UNIQUE NULL,
    INDEX membre_courriel_index (courriel),
    nb_parties_gagnées INT NOT NULL,
    nb_parties_perdues INT NOT NULL,
    nb_parties_nulles INT NOT NULL,

    FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
    FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
    FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),

    INDEX nom_prénom_membre_index (nom, prénom),
    CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
    CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
    CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);

CREATE TABLE tournoi(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    INDEX tournoi_nom_index (nom),
    club_id INT NOT NULL,
    date_début DATE NOT NULL,
    date_fin DATE NOT NULL,

    FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),

    CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);

CREATE TABLE partie(
    id INT PRIMARY KEY AUTO_INCREMENT,
    membre1_id INT NOT NULL,
    membre2_id INT NOT NULL,
    résultat INT NULL,
    date_début DATE NULL,
    heure_début TIME NULL,
    id_tournoi INT NOT NULL,

    FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
        FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
    FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),

    INDEX membres_index(membre1_id, membre2_id),
    CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
    CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
    CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);

CREATE TABLE adresse(
    id INT PRIMARY KEY AUTO_INCREMENT,
    adresse VARCHAR(255) NOT NULL,
    rue VARCHAR(255) NOT NULL,
    ville VARCHAR(255) NOT NULL,
    code_postal CHAR(6) NULL,
    INDEX adresse_code_index (code_postal),
    province_état CHAR(3) NULL,
    pays CHAR(2) NOT NULL,

    CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
        [[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);

CREATE TABLE rang(
    qualification INT PRIMARY KEY AUTO_INCREMENT,
    description VARCHAR(255) UNIQUE NULL
);
</code>```

I was expecting the program to run but it keeps telling me that there is a problem with the foreign key in "membre" and "club".

答:
You must change the order of the create statements.

First table rang and second table adresse, because the other tables have references to these tables:

```<code>CREATE TABLE rang(
    qualification INT PRIMARY KEY AUTO_INCREMENT,
    description VARCHAR(255) UNIQUE NULL
);

CREATE TABLE adresse(
    id INT PRIMARY KEY AUTO_INCREMENT,
    adresse VARCHAR(255) NOT NULL,
    rue VARCHAR(255) NOT NULL,
    ville VARCHAR(255) NOT NULL,
    code_postal CHAR(6) NULL,
    INDEX adresse_code_index (code_postal),
    province_état CHAR(3) NULL,
    pays CHAR(2) NOT NULL,

    CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
        [[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);

CREATE TABLE club(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) UNIQUE NOT NULL,
    INDEX club_nom_index (nom),
    adresse_id INT NOT NULL,
    nom_du_responsable VARCHAR(255) NULL,

    FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);

CREATE TABLE membre(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    prénom VARCHAR(255) NOT NULL,
    adresse_id INT NOT NULL,
    club_id INT NOT NULL,
    rang_qualification INT NOT NULL,
    numéro_téléphone VARCHAR(255) NULL,
    courriel VARCHAR(255) UNIQUE NULL,
    INDEX membre_courriel_index (courriel),
    nb_parties_gagnées INT NOT NULL,
    nb_parties_perdues INT NOT NULL,
    nb_parties_nulles INT NOT NULL,

    FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
    FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
    FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),

    INDEX nom_prénom_membre_index (nom, prénom),
    CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
    CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
    CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);

CREATE TABLE tournoi(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    INDEX tournoi_nom_index (nom),
    club_id INT NOT NULL,
    date_début DATE NOT NULL,
    date_fin DATE NOT NULL,

    FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),

    CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);

CREATE TABLE partie(
    id INT PRIMARY KEY AUTO_INCREMENT,
    membre1_id INT NOT NULL,
    membre2_id INT NOT NULL,
    résultat INT NULL,
    date_début DATE NULL,
    heure_début TIME NULL,
    id_tournoi INT NOT NULL,

    FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
        FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
    FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),

    INDEX membres_index(membre1_id, membre2_id),
    CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
    CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
    CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);
</code>```

Body:
Im a beginner in mysql, i don't understand my mistake
its a problem with the foreign key of "membre" and "club".

CREATE TABLE club(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) UNIQUE NOT NULL,
    INDEX club_nom_index (nom),
    adresse_id INT NOT NULL,
    nom_du_responsable VARCHAR(255) NULL,

    FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);

CREATE TABLE membre(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    prénom VARCHAR(255) NOT NULL,
    adresse_id INT NOT NULL,
    club_id INT NOT NULL,
    rang_qualification INT NOT NULL,
    numéro_téléphone VARCHAR(255) NULL,
    courriel VARCHAR(255) UNIQUE NULL,
    INDEX membre_courriel_index (courriel),
    nb_parties_gagnées INT NOT NULL,
    nb_parties_perdues INT NOT NULL,
    nb_parties_nulles INT NOT NULL,

    FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
    FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
    FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),

    INDEX nom_prénom_membre_index (nom, prénom),
    CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
    CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
    CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);

CREATE TABLE tournoi(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    INDEX tournoi_nom_index (nom),
    club_id INT NOT NULL,
    date_début DATE NOT NULL,
    date_fin DATE NOT NULL,

    FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),

    CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);

CREATE TABLE partie(
    id INT PRIMARY KEY AUTO_INCREMENT,
    membre1_id INT NOT NULL,
    membre2_id INT NOT NULL,
    résultat INT NULL,
    date_début DATE NULL,
    heure_début TIME NULL,
    id_tournoi INT NOT NULL,

    FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
        FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
    FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),

    INDEX membres_index(membre1_id, membre2_id),
    CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
    CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
    CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);

CREATE TABLE adresse(
    id INT PRIMARY KEY AUTO_INCREMENT,
    adresse VARCHAR(255) NOT NULL,
    rue VARCHAR(255) NOT NULL,
    ville VARCHAR(255) NOT NULL,
    code_postal CHAR(6) NULL,
    INDEX adresse_code_index (code_postal),
    province_état CHAR(3) NULL,
    pays CHAR(2) NOT NULL,

    CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
        [[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);

CREATE TABLE rang(
    qualification INT PRIMARY KEY AUTO_INCREMENT,
    description VARCHAR(255) UNIQUE NULL
);

I was expecting the program to run but it keeps telling me that there is a problem with the foreign key in "membre" and "club".

Body:
You must change the order of the create statements.

First table rang and second table adresse, because the other tables have references to these tables:

CREATE TABLE rang(
    qualification INT PRIMARY KEY AUTO_INCREMENT,
    description VARCHAR(255) UNIQUE NULL
);

CREATE TABLE adresse(
    id INT PRIMARY KEY AUTO_INCREMENT,
    adresse VARCHAR(255) NOT NULL,
    rue VARCHAR(255) NOT NULL,
    ville VARCHAR(255) NOT NULL,
    code_postal CHAR(6) NULL,
    INDEX adresse_code_index (code_postal),
    province_état CHAR(3) NULL,
    pays CHAR(2) NOT NULL,

    CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
        [[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);

CREATE TABLE club(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) UNIQUE NOT NULL,
    INDEX club_nom_index (nom),
    adresse_id INT NOT NULL,
    nom_du_responsable VARCHAR(255) NULL,

    FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);

CREATE TABLE membre(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    prénom VARCHAR(255) NOT NULL,
    adresse_id INT NOT NULL,
    club_id INT NOT NULL,
    rang_qualification INT NOT NULL,
    numéro_téléphone VARCHAR(255) NULL,
    courriel VARCHAR(255) UNIQUE NULL,
    INDEX membre_courriel_index (courriel),
    nb_parties_gagnées INT NOT NULL,
    nb_parties_perdues INT NOT NULL,
    nb_parties_nulles INT NOT NULL,

    FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
    FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
    FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),

    INDEX nom_prénom_membre_index (nom, prénom),
    CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
    CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
    CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);

CREATE TABLE tournoi(
    id INT PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    INDEX tournoi_nom_index (nom),
    club_id INT NOT NULL,
    date_début DATE NOT NULL,
    date_fin DATE NOT NULL,

    FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),

    CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);

CREATE TABLE partie(
    id INT PRIMARY KEY AUTO_INCREMENT,
    membre1_id INT NOT NULL,
    membre2_id INT NOT NULL,
    résultat INT NULL,
    date_début DATE NULL,
    heure_début TIME NULL,
    id_tournoi INT NOT NULL,

    FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
        FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
    FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),

    INDEX membres_index(membre1_id, membre2_id),
    CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
    CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
    CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);