问:
JQUERY AJAX find filename in response data
Hello im trying to load all file names from a folder.

im using this script and it returns a response object called data. When i use console.log on data it returns me to html below. how can i now collect all the file names out of there and write it into the variable fileNames?

my script:

```<code>var fileNames= "";
var folder = "csvData/";
    $.ajax({
          type: 'GET',
          url:  folder,

          success: function(data){
              console.log(data);
          },
          async:false
      });
</code>```

html inside of data response:
a the bottom you can see that a function is called for each file in the folder.

```<code><!DOCTYPE html>

<html dir="ltr" lang="de">

<head>
<meta charset="utf-8">
<meta name="color-scheme" content="light dark">
<meta name="google" value="notranslate">

<script>
function addRow(name, url, isdir,
    size, size_string, date_modified, date_modified_string) {
  if (name == "." || name == "..")
    return;

  var root = document.location.pathname;
  if (root.substr(-1) !== "/")
    root += "/";

  var tbody = document.getElementById("tbody");
  var row = document.createElement("tr");
  var file_cell = document.createElement("td");
  var link = document.createElement("a");

  link.className = isdir ? "icon dir" : "icon file";

  if (isdir) {
    name = name + "/";
    url = url + "/";
    size = 0;
    size_string = "";
  } else {
    link.draggable = "true";
    link.addEventListener("dragstart", onDragStart, false);
  }
  link.innerText = name;
  link.href = root + url;

  file_cell.dataset.value = name;
  file_cell.appendChild(link);

  row.appendChild(file_cell);
  row.appendChild(createCell(size, size_string));
  row.appendChild(createCell(date_modified, date_modified_string));

  tbody.appendChild(row);
}

function onDragStart(e) {
  var el = e.srcElement;
  var name = el.innerText.replace(":", "");
  var download_url_data = "application/octet-stream:" + name + ":" + el.href;
  e.dataTransfer.setData("DownloadURL", download_url_data);
  e.dataTransfer.effectAllowed = "copy";
}

function createCell(value, text) {
  var cell = document.createElement("td");
  cell.setAttribute("class", "detailsColumn");
  cell.dataset.value = value;
  cell.innerText = text;
  return cell;
}

function start(location) {
  var header = document.getElementById("header");
  header.innerText = header.innerText.replace("LOCATION", location);

  document.getElementById("title").innerText = header.innerText;
}

function onHasParentDirectory() {
  var box = document.getElementById("parentDirLinkBox");
  box.style.display = "block";

  var root = document.location.pathname;
  if (!root.endsWith("/"))
    root += "/";

  var link = document.getElementById("parentDirLink");
  link.href = root + "..";
}

function sortTable(column) {
  var theader = document.getElementById("theader");
  var oldOrder = theader.cells[column].dataset.order || '1';
  oldOrder = parseInt(oldOrder, 10)
  var newOrder = 0 - oldOrder;
  theader.cells[column].dataset.order = newOrder;

  var tbody = document.getElementById("tbody");
  var rows = tbody.rows;
  var list = [], i;
  for (i = 0; i < rows.length; i++) {
    list.push(rows[i]);
  }

  list.sort(function(row1, row2) {
    var a = row1.cells[column].dataset.value;
    var b = row2.cells[column].dataset.value;
    if (column) {
      a = parseInt(a, 10);
      b = parseInt(b, 10);
      return a > b ? newOrder : a < b ? oldOrder : 0;
    }

    // Column 0 is text.
    if (a > b)
      return newOrder;
    if (a < b)
      return oldOrder;
    return 0;
  });

  // Appending an existing child again just moves it.
  for (i = 0; i < list.length; i++) {
    tbody.appendChild(list[i]);
  }
}

// Add event handlers to column headers.
function addHandlers(element, column) {
  element.onclick = (e) => sortTable(column);
  element.onkeydown = (e) => {
    if (e.key == 'Enter' || e.key == ' ') {
      sortTable(column);
      e.preventDefault();
    }
  };
}

function onLoad() {
  addHandlers(document.getElementById('nameColumnHeader'), 0);
  addHandlers(document.getElementById('sizeColumnHeader'), 1);
  addHandlers(document.getElementById('dateColumnHeader'), 2);
}

window.addEventListener('DOMContentLoaded', onLoad);
</script>

<style>

  h1 {
    border-bottom: 1px solid #c0c0c0;
    margin-bottom: 10px;
    padding-bottom: 10px;
    white-space: nowrap;
  }

  table {
    border-collapse: collapse;
  }

  th {
    cursor: pointer;
  }

  td.detailsColumn {
    padding-inline-start: 2em;
    text-align: end;
    white-space: nowrap;
  }

  a.icon {
    padding-inline-start: 1.5em;
    text-decoration: none;
    user-select: auto;
  }

  a.icon:hover {
    text-decoration: underline;
  }

  a.file {
    background : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABEElEQVR42nRRx3HDMBC846AHZ7sP54BmWAyrsP588qnwlhqw/k4v5ZwWxM1hzmGRgV1cYqrRarXoH2w2m6qqiqKIR6cPtzc3xMSML2Te7XZZlnW7Pe/91/dX47WRBHuA9oyGmRknzGDjab1ePzw8bLfb6WRalmW4ip9FDVpYSWZgOp12Oh3nXJ7nxoJSGEciteP9y+fH52q1euv38WosqA6T2gGOT44vry7BEQtJkMAMMpa6JagAMcUfWYa4hkkzAc7fFlSjwqCoOUYAF5RjHZPVCFBOtSBGfgUDji3c3jpibeEMQhIMh8NwshqyRsBJgvF4jMs/YlVR5KhgNpuBLzk0OcUiR3CMhcPaOzsZiAAA/AjmaB3WZIkAAAAASUVORK5CYII=") left top no-repeat;
  }

  a.dir {
    background : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABt0lEQVR42oxStZoWQRCs2cXdHTLcHZ6EjAwnQWIkJyQlRt4Cd3d3d1n5d7q7ju1zv/q+mh6taQsk8fn29kPDRo87SDMQcNAUJgIQkBjdAoRKdXjm2mOH0AqS+PlkP8sfp0h93iu/PDji9s2FzSSJVg5ykZqWgfGRr9rAAAQiDFoB1OfyESZEB7iAI0lHwLREQBcQQKqo8p+gNUCguwCNAAUQAcFOb0NNGjT+BbUC2YsHZpWLhC6/m0chqIoM1LKbQIIBwlTQE1xAo9QDGDPYf6rkTpPc92gCUYVJAZjhyZltJ95f3zuvLYRGWWCUNkDL2333McBh4kaLlxg+aTmyL7c2xTjkN4Bt7oE3DBP/3SRz65R/bkmBRPGzcRNHYuzMjaj+fdnaFoJUEdTSXfaHbe7XNnMPyqryPcmfY+zURaAB7SHk9cXSH4fQ5rojgCAVIuqCNWgRhLYLhJB4k3iZfIPtnQiCpjAzeBIRXMA6emAqoEbQSoDdGxFUrxS1AYcpaNbBgyQBGJEOnYOeENKR/iAd1npusI4C75/c3539+nbUjOgZV5CkAU27df40lH+agUdIuA/EAgDmZnwZlhDc0wAAAABJRU5ErkJggg==") left top no-repeat;
  }

  a.up {
    background : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACM0lEQVR42myTA+w1RxRHz+zftmrbdlTbtq04qRGrCmvbDWp9tq3a7tPcub8mj9XZ3eHOGQdJAHw77/LbZuvnWy+c/CIAd+91CMf3bo+bgcBiBAGIZKXb19/zodsAkFT+3px+ssYfyHTQW5tr05dCOf3xN49KaVX9+2zy1dX4XMk+5JflN5MBPL30oVsvnvEyp+18Nt3ZAErQMSFOfelCFvw0HcUloDayljZkX+MmamTAMTe+d+ltZ+1wEaRAX/MAnkJdcujzZyErIiVSzCEvIiq4O83AG7LAkwsfIgAnbncag82jfPPdd9RQyhPkpNJvKJWQBKlYFmQA315n4YPNjwMAZYy0TgAweedLmLzTJSTLIxkWDaVCVfAbbiKjytgmm+EGpMBYW0WwwbZ7lL8anox/UxekaOW544HO0ANAshxuORT/RG5YSrjlwZ3lM955tlQqbtVMlWIhjwzkAVFB8Q9EAAA3AFJ+DR3DO/Pnd3NPi7H117rAzWjpEs8vfIqsGZpaweOfEAAFJKuM0v6kf2iC5pZ9+fmLSZfWBVaKfLLNOXj6lYY0V2lfyVCIsVzmcRV9Y0fx02eTaEwhl2PDrXcjFdYRAohQmS8QEFLCLKGYA0AeEakhCCFDXqxsE0AQACgAQp5w96o0lAXuNASeDKWIvADiHwigfBINpWKtAXJvCEKWgSJNbRvxf4SmrnKDpvZavePu1K/zu/due1X/6Nj90MBd/J2Cic7WjBp/jUdIuA8AUtd65M+PzXIAAAAASUVORK5CYII=") left top no-repeat;
  }

  html[dir=rtl] a {
    background-position-x: right;
  }

  #parentDirLinkBox {
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
</style>

<title id="title"></title>

</head>

<body>

<h1 id="header">Index von LOCATION</h1>

<div id="parentDirLinkBox" style="display:none">
  <a id="parentDirLink" class="icon up">
    <span id="parentDirText">[übergeordnetes Verzeichnis]</span>
  </a>
</div>

<table>
  <thead>
    <tr class="header" id="theader">
      <th id="nameColumnHeader" tabindex=0 role="button">Name</th>
      <th id="sizeColumnHeader" class="detailsColumn" tabindex=0 role="button">
        Größe
      </th>
      <th id="dateColumnHeader" class="detailsColumn" tabindex=0 role="button">
        Änderungsdatum
      </th>
    </tr>
  </thead>
  <tbody id="tbody">
  </tbody>
</table>

</body>

</html>
<script>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview This file defines a singleton which provides access to all data
 * that is available as soon as the page's resources are loaded (before DOM
 * content has finished loading). This data includes both localized strings and
 * any data that is important to have ready from a very early stage (e.g. things
 * that must be displayed right away).
 *
 * Note that loadTimeData is not guaranteed to be consistent between page
 * refreshes (https://crbug.com/740629) and should not contain values that might
 * change if the page is re-opened later.
 */

/** @type {!LoadTimeData} */
// eslint-disable-next-line no-var
var loadTimeData;

class LoadTimeData {
  constructor() {
    /** @type {?Object} */
    this.data_ = null;
  }

  /**
   * Sets the backing object.
   *
   * Note that there is no getter for |data_| to discourage abuse of the form:
   *
   *     var value = loadTimeData.data()['key'];
   *
   * @param {Object} value The de-serialized page data.
   */
  set data(value) {
    expect(!this.data_, 'Re-setting data.');
    this.data_ = value;
  }

  /**
   * @param {string} id An ID of a value that might exist.
   * @return {boolean} True if |id| is a key in the dictionary.
   */
  valueExists(id) {
    return id in this.data_;
  }

  /**
   * Fetches a value, expecting that it exists.
   * @param {string} id The key that identifies the desired value.
   * @return {*} The corresponding value.
   */
  getValue(id) {
    expect(this.data_, 'No data. Did you remember to include strings.js?');
    const value = this.data_[id];
    expect(typeof value !== 'undefined', 'Could not find value for ' + id);
    return value;
  }

  /**
   * As above, but also makes sure that the value is a string.
   * @param {string} id The key that identifies the desired string.
   * @return {string} The corresponding string value.
   */
  getString(id) {
    const value = this.getValue(id);
    expectIsType(id, value, 'string');
    return /** @type {string} */ (value);
  }

  /**
   * Returns a formatted localized string where $1 to $9 are replaced by the
   * second to the tenth argument.
   * @param {string} id The ID of the string we want.
   * @param {...(string|number)} var_args The extra values to include in the
   *     formatted output.
   * @return {string} The formatted string.
   */
  getStringF(id, var_args) {
    const value = this.getString(id);
    if (!value) {
      return '';
    }

    const args = Array.prototype.slice.call(arguments);
    args[0] = value;
    return this.substituteString.apply(this, args);
  }

  /**
   * Returns a formatted localized string where $1 to $9 are replaced by the
   * second to the tenth argument. Any standalone $ signs must be escaped as
   * $$.
   * @param {string} label The label to substitute through.
   *     This is not an resource ID.
   * @param {...(string|number)} var_args The extra values to include in the
   *     formatted output.
   * @return {string} The formatted string.
   */
  substituteString(label, var_args) {
    const varArgs = arguments;
    return label.replace(/\$(.|$|\n)/g, function(m) {
      expect(m.match(/\$[$1-9]/), 'Unescaped $ found in localized string.');
      return m === '$$' ? '$' : varArgs[m[1]];
    });
  }

  /**
   * Returns a formatted string where $1 to $9 are replaced by the second to
   * tenth argument, split apart into a list of pieces describing how the
   * substitution was performed. Any standalone $ signs must be escaped as $$.
   * @param {string} label A localized string to substitute through.
   *     This is not an resource ID.
   * @param {...(string|number)} var_args The extra values to include in the
   *     formatted output.
   * @return {!Array<!{value: string, arg: (null|string)}>} The formatted
   *     string pieces.
   */
  getSubstitutedStringPieces(label, var_args) {
    const varArgs = arguments;
    // Split the string by separately matching all occurrences of $1-9 and of
    // non $1-9 pieces.
    const pieces = (label.match(/(\$[1-9])|(([^$]|\$([^1-9]|$))+)/g) ||
                    []).map(function(p) {
      // Pieces that are not $1-9 should be returned after replacing $$
      // with $.
      if (!p.match(/^\$[1-9]$/)) {
        expect(
            (p.match(/\$/g) || []).length % 2 === 0,
            'Unescaped $ found in localized string.');
        return {value: p.replace(/\$\$/g, '$'), arg: null};
      }

      // Otherwise, return the substitution value.
      return {value: varArgs[p[1]], arg: p};
    });

    return pieces;
  }

  /**
   * As above, but also makes sure that the value is a boolean.
   * @param {string} id The key that identifies the desired boolean.
   * @return {boolean} The corresponding boolean value.
   */
  getBoolean(id) {
    const value = this.getValue(id);
    expectIsType(id, value, 'boolean');
    return /** @type {boolean} */ (value);
  }

  /**
   * As above, but also makes sure that the value is an integer.
   * @param {string} id The key that identifies the desired number.
   * @return {number} The corresponding number value.
   */
  getInteger(id) {
    const value = this.getValue(id);
    expectIsType(id, value, 'number');
    expect(value === Math.floor(value), 'Number isn\'t integer: ' + value);
    return /** @type {number} */ (value);
  }

  /**
   * Override values in loadTimeData with the values found in |replacements|.
   * @param {Object} replacements The dictionary object of keys to replace.
   */
  overrideValues(replacements) {
    expect(
        typeof replacements === 'object',
        'Replacements must be a dictionary object.');
    for (const key in replacements) {
      this.data_[key] = replacements[key];
    }
  }

  /**
   * Reset loadTimeData's data. Should only be used in tests.
   * @param {?Object} newData The data to restore to, when null restores to
   *    unset state.
   */
  resetForTesting(newData = null) {
    this.data_ = newData;
  }

  /**
   * @return {boolean} Whether loadTimeData.data has been set.
   */
  isInitialized() {
    return this.data_ !== null;
  }
}

  /**
   * Checks condition, throws error message if expectation fails.
   * @param {*} condition The condition to check for truthiness.
   * @param {string} message The message to display if the check fails.
   */
  function expect(condition, message) {
    if (!condition) {
      throw new Error(
          'Unexpected condition on ' + document.location.href + ': ' + message);
    }
  }

  /**
   * Checks that the given value has the given type.
   * @param {string} id The id of the value (only used for error message).
   * @param {*} value The value to check the type on.
   * @param {string} type The type we expect |value| to be.
   */
  function expectIsType(id, value, type) {
    expect(
        typeof value === type, '[' + value + '] (' + id + ') is not a ' + type);
  }

  expect(!loadTimeData, 'should only include this file once');
  loadTimeData = new LoadTimeData;

  // Expose |loadTimeData| directly on |window|, since within a JS module the
  // scope is local and not all files have been updated to import the exported
  // |loadTimeData| explicitly.
  window.loadTimeData = loadTimeData;

  console.warn('crbug/1173575, non-JS module files deprecated.');</script><script>loadTimeData.data = {"header":"Index von LOCATION","headerDateModified":"Änderungsdatum","headerName":"Name","headerSize":"Größe","language":"de","parentDirText":"[übergeordnetes Verzeichnis]","textdirection":"ltr"};</script><script>start("C:\\Users\\MYNAME-\\eclipse-workspace\\htmlCsvtable\\src\\htmlTableGeneration\\csvData\\");</script>
<script>onHasParentDirectory();</script>
<script>addRow("20220201221359.csv","20220201221359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</script>
<script>addRow("20220206091030.csv","20220206091030.csv",0,2958,"2.9 kB",1644181136,"06.02.22, 21:58:56");</script>
<script>addRow("20220206135359.csv","20220206135359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</script>
</code>```

答:
It seems you want to extract the file names from the calls to addRow.

Here's an example of how to extract them using a regular expression.

const findFiles = (text) => {
  let matches = [];
  let match;
  let regex = /addRow\("(.*?)"/g;

  while (match = regex.exec(text)) {
    matches.push(match[1]);
  }
  return matches;
};

// instead of this example "text" use the result from your AJAX call
const text = `<script>onHasParentDirectory();</scri` + `pt><script>addRow("20220201221359.csv","20220201221359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt><script>addRow("20220206091030.csv","20220206091030.csv",0,2958,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt><scri` + `pt>addRow("20220206135359.csv","20220206135359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt>`;

console.log(findFiles(text));```

Body:
Hello im trying to load all file names from a folder.

im using this script and it returns a response object called data. When i use console.log on data it returns me to html below. how can i now collect all the file names out of there and write it into the variable fileNames?

my script:

var fileNames= "";
var folder = "csvData/";
    $.ajax({
          type: 'GET',
          url:  folder,

          success: function(data){
              console.log(data);
          },
          async:false
      });

html inside of data response:
a the bottom you can see that a function is called for each file in the folder.

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="color-scheme" content="light dark">
<meta name="google" value="notranslate">

<title id="title"></title>

Index von LOCATION

    [übergeordnetes Verzeichnis]

      Name

        Größe

        Änderungsdatum


来源: stackexchange

问:
ASP.NET: How can I log User's View and Update Gridview in WebPage?
I have a LOG table like this.

Process_Type (Could be Update, View),
Username, Date

In my page I have only one Gridview.

I want to log user's information (username, date, process_type) in LOG table.

1.View

Should I use Page_Load() function? (Because Gridview binding on the load of page) I think I should update my table like this;

```<code>UPDATE LOG
SET PROCESS_TYPE = 'VIEW', USERNAME =  Request.ServerVariables["AUTH_USER"],
DATE = DateTime.Now
</code>```

2.UPDATE

Should I use Gridview1_OnRowUpdating() function ? I think I should update my table like this;

```<code>UPDATE LOG
SET PROCESS_TYPE = 'UPDATE', USERNAME =  Request.ServerVariables["AUTH_USER"],
DATE = DateTime.Now
</code>```

Is this a good plan for logging my simple page?

Or, How can I do that more easily?

答:
To log the View, you should use DataBound and for update use RowUpdated

```<code>protected void GridView1_DataBound(object sender, EventArgs e)
{
    // is Called when data is binded to gridview
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
    // is called when Row is Updated
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a LOG table like this.

Process_Type (Could be Update, View),
Username, Date

In my page I have only one Gridview.

I want to log user's information (username, date, process_type) in LOG table.

1.View

Should I use Page_Load() function? (Because Gridview binding on the load of page) I think I should update my table like this;

UPDATE LOG
SET PROCESS_TYPE = 'VIEW', USERNAME =  Request.ServerVariables["AUTH_USER"],
DATE = DateTime.Now

2.UPDATE

Should I use Gridview1_OnRowUpdating() function ? I think I should update my table like this;

UPDATE LOG
SET PROCESS_TYPE = 'UPDATE', USERNAME =  Request.ServerVariables["AUTH_USER"],
DATE = DateTime.Now

Is this a good plan for logging my simple page?

Or, How can I do that more easily?

Body:
To log the View, you should use DataBound and for update use RowUpdated

protected void GridView1_DataBound(object sender, EventArgs e)
{
    // is Called when data is binded to gridview
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
    // is called when Row is Updated
}


问:
What is the point of salt and hashing if database is accessible?
I just learned the concept of hashing ("Hey! don't forget the salt!") and using salt to make the password secured.

Hashing it is a one way encryption (actually not encryption but hashing) so it cannot be reversed engineered. Salting is prefixing or appending randomly created values to the password before hashing 'coz the problem in hashing (just hashing) is, some genius has provided a hash table of words from the dictionary so that they'll just compare the hash from that dictionary to the user's table from the database to login - W-wait? did I say table from the database? So it means somebody can access the database so we have to use salt? If that so, then why would the hacker recover the password if he already has access to the database? If I were him, I'll just get all the details I want from the database, why would I use the key I've stolen from a house to open the door if I can access the house already through the window?

So, why hash? why salt? I don't understand. Please, somebody help me.

Thanks in advance.

Important Note: I'm not against hashing or salting, I just want to clarify things.

答:
If you have the cleartext passwords and e-mail addresses from the database, you can wreak havoc! It's not about getting credentials to the site that is already hacked, it's about getting login information to other sites. </p>

<p>Most people don't use one password only for one site, so if you have the password for their primary e-mail address, you probably have access to ALL their accounts on every site (through password resetting).  </p>

Body:
If you have the cleartext passwords and e-mail addresses from the database, you can wreak havoc! It's not about getting credentials to the site that is already hacked, it's about getting login information to other sites.

Most people don't use one password only for one site, so if you have the password for their primary e-mail address, you probably have access to ALL their accounts on every site (through password resetting).


问:
How to improve "select min(my_col)" query in MySQL without adding and index
The query below takes about a minute to run on my MySQL instance (running on a fairly beefy machine with 64G memory, 2T disc, 2.30Ghz CPU with 8 cores and 16 logical, and the query is running on localhost).  This same query runs in less than a second on a SQL Server database I have access to.  Unfortunately, I do not have access to the SQL Server host or the DBA, etc.

```<code>select min(visit_start_date)
from visit_occurrence;
</code>```

The table has been set to ENGINE=MyISAM and default-storage-engine=INNODB and innodb_buffer_pool_size=16G are set in my.ini.

Is there some configuration I could be missing that would cause this query to run so slowly on MySQL? How can I fix it?

I have a large number of tables and queries I will need to support so I would really like to be able to fix this issue globally rather than having to create indexes everywhere I have slow queries.

The SQL Server database does not seem to have an index on the column being queried as shown below.

EDIT:

Untagged MS Sql Server, I had tagged it hoping for the help of our MS Sql Server colleagues with information that Sql Server had some way of structuring data and/or queries that would make this type of query run faster on that platform v other such as MySql

Removed image of code to more closely conform with community standards

You never know if there is a magic go-faster button if you don't ask (ENGINE=MyISAM is sometimes kind of like a magic go-faster button for some queries in MySql).  I'm kind of fishing for a potential hardware or clustering solution here.  Is Apache Ignite a potential solution here?

Thanks again to the community for all of your support and help.  I hope this fixes most of the issues that have been raised for this post.

SECOND EDIT:
Is the partitioning/sharding described in the links below a potential solution here?

https://user3141592.medium.com/how-to-scale-mysql-42ebd2841fa6

https://dev.mysql.com/doc/refman/8.0/en/partitioning-overview.html

THIRD EDIT: A note on community standards.

Part of our community standards is explicitly to be welcoming, inclusive, and to be nice.

https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?fbclid=IwAR1gr6r2qmXs506SAV3H_h6H8LoFy3mlXucfa-fqiiEXMHUR3aF_tdoZGsw

https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback).

The MS Sql Server tag was used here as one of the systems I'm comparing is MS Sql Server.  We're really working with very limited information here.  I have two systems: My MySql system, which is knowable as I'm running it, and the MS Sql Server running the same database in someone else's system that I have very little information about (all I have is a read only sql prompt).  I am comparing apples and oranges: The same query runs well on the orange (MS Sql Server) and does not run well on the apple (My MySql instance).  I'd like to know why so I can make an informed decision about how to get my queries to run in a reasonable amount of time. How do I get my apple to look like an orange?  Do I switch to MS Sql Server?  Do I need to deploy on different hardware?  Is the other system running some kind of in memory caching system on top of their database instance?  Most of these possibilities would require a non trivial amount of time to explore and validate.  So yes, I would like help from MS Sql Server experts that might know if there are caching options, transactional v warehouse options, etc. that could be set that would make a world of difference, that would be magic go-fast buttons.

The magic go-fast button comment was perhaps a little bit condescending.

The picture showing the indexes was shown as I was just trying to make the point that the other system does not seem to have an index on the column being queried.  I this case a picture was worth a thousand words.

答:
If the table says ENGINE=MyISAM, then that is what counts.  In almost all cases, this is a bad choice. innodb_buffer_pool_size=16G is not relevant except that it robs memory from MyISAM.

default-storage-engine=INNODB is relevant only when creating a table explicitly specifying the ENGINE=.

Are some of your tables MyISAM and some are InnoDB?  How much RAM do you have?

Most performance solutions necessarily involve an INDEX.  Please explain why you can't afford an index.  It could turn that query into less than 10ms, regardless of the number of rows in the table.

Sorry, but I don't accept "rather than having to create indexes everywhere I have slow queries".

Changing tables from MyISAM to InnoDB will, in some cases help with performance.  Suggest you change the engine as you add the indexes.

Show us some more queries, we can help you decide what indexes are needed.  select min(visit_start_date) from visit_occurrence; needs INDEX(date); other queries may not be so trivial.  Do not fall into the trap of "indexing every column".

More

In MySQL...

A single connection only uses one core, so more cores only helps when you have more connections.  (Some tiny exceptions exist in MySQL 8.0.)

Partitioning rarely helps with performance; do use that without getting advice.  (PS:  BY RANGE is perhaps the only useful variant.)

Replication is for read-scaling (and backup and ...)

Sharding is for write-scaling.  It requires a bunch of extra architectural things -- such as routing queries to the appropriate servers.  (MariaDB has Spider and FederatedX as possible tools.)  In any case, sharding is a non-trivial undertaking.

Clustering is for HA (High Availability, auto-failover, etc), while helping some with read and write scaling.  Cf: Galera, InnoDB Cluster.

Hardware is rarely more than a temporary solution to performance issues.

Caching leads to potentially inconsistent results, so beware.  Also, consider my mantra "don't bother putting a cache in front of a cache".

(I can advise further on any of these topics.)

ContentLicense: CC BY-SA 4.0

Body:
The query below takes about a minute to run on my MySQL instance (running on a fairly beefy machine with 64G memory, 2T disc, 2.30Ghz CPU with 8 cores and 16 logical, and the query is running on localhost).  This same query runs in less than a second on a SQL Server database I have access to.  Unfortunately, I do not have access to the SQL Server host or the DBA, etc.

select min(visit_start_date)
from visit_occurrence;

The table has been set to ENGINE=MyISAM and default-storage-engine=INNODB and innodb_buffer_pool_size=16G are set in my.ini.

Is there some configuration I could be missing that would cause this query to run so slowly on MySQL? How can I fix it?

I have a large number of tables and queries I will need to support so I would really like to be able to fix this issue globally rather than having to create indexes everywhere I have slow queries.

The SQL Server database does not seem to have an index on the column being queried as shown below.

EDIT:

Untagged MS Sql Server, I had tagged it hoping for the help of our MS Sql Server colleagues with information that Sql Server had some way of structuring data and/or queries that would make this type of query run faster on that platform v other such as MySql

Removed image of code to more closely conform with community standards

You never know if there is a magic go-faster button if you don't ask (ENGINE=MyISAM is sometimes kind of like a magic go-faster button for some queries in MySql).  I'm kind of fishing for a potential hardware or clustering solution here.  Is Apache Ignite a potential solution here?

Thanks again to the community for all of your support and help.  I hope this fixes most of the issues that have been raised for this post.

SECOND EDIT:
Is the partitioning/sharding described in the links below a potential solution here?

https://user3141592.medium.com/how-to-scale-mysql-42ebd2841fa6

https://dev.mysql.com/doc/refman/8.0/en/partitioning-overview.html

THIRD EDIT: A note on community standards.

Part of our community standards is explicitly to be welcoming, inclusive, and to be nice.

https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?fbclid=IwAR1gr6r2qmXs506SAV3H_h6H8LoFy3mlXucfa-fqiiEXMHUR3aF_tdoZGsw

https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback).

The MS Sql Server tag was used here as one of the systems I'm comparing is MS Sql Server.  We're really working with very limited information here.  I have two systems: My MySql system, which is knowable as I'm running it, and the MS Sql Server running the same database in someone else's system that I have very little information about (all I have is a read only sql prompt).  I am comparing apples and oranges: The same query runs well on the orange (MS Sql Server) and does not run well on the apple (My MySql instance).  I'd like to know why so I can make an informed decision about how to get my queries to run in a reasonable amount of time. How do I get my apple to look like an orange?  Do I switch to MS Sql Server?  Do I need to deploy on different hardware?  Is the other system running some kind of in memory caching system on top of their database instance?  Most of these possibilities would require a non trivial amount of time to explore and validate.  So yes, I would like help from MS Sql Server experts that might know if there are caching options, transactional v warehouse options, etc. that could be set that would make a world of difference, that would be magic go-fast buttons.

The magic go-fast button comment was perhaps a little bit condescending.

The picture showing the indexes was shown as I was just trying to make the point that the other system does not seem to have an index on the column being queried.  I this case a picture was worth a thousand words.


问:
SystemVerilog constraint: constrain the read address has been written before
I want to write a constraint to make sure r_addr is only allowed when the same address has been used as w_addr before, but the following constraint doesn't work.  Do you have any suggestion?

```<code>class try;
    rand int w_addr;
    rand int r_addr;
    int ua[$];
    int aa[int];
    constraint unique_addr_c{
        aa.size() == 0 || aa.exists(r_addr);
    }
endclass

module test;

    try a;

    initial begin
        a=new;
        repeat(20) begin
            if(a.randomize);
            $display("add=%0d", a.w_addr);
            $display("add=%0d", a.r_addr);
            a.ua.push_back(a.w_addr);
            a.aa[a.w_addr] = 1;
        end
    end

endmodule
</code>```

答:
The following code works in mentor but not in synopsys</p>
```<code>class bus;
rand bit [31:0] address;
rand bit rd_wr_en;
rand bit [1:0] interleaving;
endclass

class my_bus;
rand bus b1[20];

function new();
 foreach(b1[n])
  b1[n] = new();
endfunction

constraint c {
  foreach (b1[n])
   if (n>0)
    if(b1[n-b1[n].interleaving].rd_wr_en ==1)
    {
     b1[n].address == b1[n-b1[n].interleaving].address;
     b1[n].rd_wr_en == 0;
    }

   }

endclass
module tb;
my_bus b2;
 initial begin
 b2 = new();
 repeat (10) begin
   b2.randomize;
   foreach(b2.b1[n])
   $display ( "%p", b2.b1[n]);
   end
 end
endmodule
</code>```

Body:
I want to write a constraint to make sure r_addr is only allowed when the same address has been used as w_addr before, but the following constraint doesn't work.  Do you have any suggestion?

class try;
    rand int w_addr;
    rand int r_addr;
    int ua[$];
    int aa[int];
    constraint unique_addr_c{
        aa.size() == 0 || aa.exists(r_addr);
    }
endclass

module test;

    try a;

    initial begin
        a=new;
        repeat(20) begin
            if(a.randomize);
            $display("add=%0d", a.w_addr);
            $display("add=%0d", a.r_addr);
            a.ua.push_back(a.w_addr);
            a.aa[a.w_addr] = 1;
        end
    end

endmodule

Body:
The following code works in mentor but not in synopsys

class bus;
rand bit [31:0] address;
rand bit rd_wr_en;
rand bit [1:0] interleaving;
endclass

class my_bus;
rand bus b1[20];

function new();
 foreach(b1[n])
  b1[n] = new();
endfunction

constraint c {
  foreach (b1[n])
   if (n>0)
    if(b1[n-b1[n].interleaving].rd_wr_en ==1)
    {
     b1[n].address == b1[n-b1[n].interleaving].address;
     b1[n].rd_wr_en == 0;
    }

   }

endclass
module tb;
my_bus b2;
 initial begin
 b2 = new();
 repeat (10) begin
   b2.randomize;
   foreach(b2.b1[n])
   $display ( "%p", b2.b1[n]);
   end
 end
endmodule


问:
How to update App version of a NativeScript Angular app?
I am looking for a possible ways to update/set App Versions of my NativeScript Angular app. I found few ways but, I was not able to successfully update my app to newer versions.

I used this set-version plugin but could not get it to work.

Thank you in advance!

答:
if you want to update your Angular version in your App, read this. It is the official documentation. You can choose your current version and the latest version you want and appear the steps you need to follow.

https://update.angular.io/


问:
How to split df with a column of dictionary need to split all its values and keys into respective coulmn
```<code>{'labels': ['travel', 'dancing', 'cooking'],
'scores': [0.9938651323318481, 0.0032737774308770895, 0.002861034357920289],
'sequence': 'one day I will see the world'}
</code>```

i have this a df['prediction'] column i want to split this result into three different column as df['travel'],df['dancing'],df['cooking'] and their respective scores i am sorry if the question is not appropriaterequired result

required result

答:
What you can do is iterate over this dict and make another dictionary

say s is the source dictionary and x is the new dictionary that you want

x = {}
x['sequence']=s['sequence']
for i, l in enumerate(s['labels']):
  x[l] = s['scores'][i]
```

This should solve your problem.

Body:
{'labels': ['travel', 'dancing', 'cooking'],
'scores': [0.9938651323318481, 0.0032737774308770895, 0.002861034357920289],
'sequence': 'one day I will see the world'}

i have this a df['prediction'] column i want to split this result into three different column as df['travel'],df['dancing'],df['cooking'] and their respective scores i am sorry if the question is not appropriaterequired result

required result

Body:
What you can do is iterate over this dict and make another dictionary

say s is the source dictionary and x is the new dictionary that you want

x = {}
x['sequence']=s['sequence']
for i, l in enumerate(s['labels']):
  x[l] = s['scores'][i]

This should solve your problem.


问:
How to change domain name (entire url) in react-router-dom
If I am in http://localhost:3000/Authpage I want to redirect to new URL http://www.example.com/

Usehostory() -> histor.push() is appending new url to old url.
http://localhost:3000/Authpage/http://www.example.com/

But I need new location something like below
http://www.example.com/

答:
you have 2 options
use  tag to redirect the user into a new web page.
or use one of the javascript methods like window.open("yourUrl.com")
but be careful when you are using javascript methods to redirect the user because the safari browser would not let you use some of them( because of some security filters)</p>


问:
Python Black code formatter doesn't format docstring line length?
I am running the Black code formatter against a Python script however it doesn't reformat the line length for docstrings. For example, given the following code:

def my_func():
    """
    This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring.
    """
    return
```

When running Black against this script, the line length does not change. How can I ensure docstrings get formatted when running Black?

答:
maintainer here! :wave:

The short answer is no you cannot configure Black to fix line length issues in docstrings currently.

It's not likely Black will split or merge lines in docstrings as it would be far too risky, structured data can and does exist in docstrings. While I would hope the added newlines wouldn't break the consumers it's still a valid concern.

There's currently an open issue asking for this (although it also wants the line length limit for docstrings and strings to be 79) GH-2289, and specifically for docstrings GH-2865. You can also read GH-1713 which is about splitting comments (and likewise has mixed feelings from maintainers).

For the time being, perhaps you can look into https://github.com/PyCQA/docformatter which does seem to wrap docstrings (see the --wrap-descriptions and --wrap-summaries options)

P.S. if you're curious whether we'll add a flag to split docstrings or comments, it's once again unlikely since we seek to minimize formatting configurability. Especially as the pre-existing flags only disable certain elements of Black's style (barring --line-length which exists as there's no real consensus what it should be). Feel free to state your arguments in the linked issues tho!

Body:
I am running the Black code formatter against a Python script however it doesn't reformat the line length for docstrings. For example, given the following code:

def my_func():
    """
    This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring.
    """
    return

When running Black against this script, the line length does not change. How can I ensure docstrings get formatted when running Black?


问:
How do I add characters in dates to make them look normal without affecting the rest of the line?
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

```<code>sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output
</code>```

This solution makes sense, but affects the rest of the line.

Body:
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output

This solution makes sense, but affects the rest of the line.

Body:
Since only bash is tagged, here's a solution using bash's string indexing:

while IFS=\; read -r x y z
do printf '%s;%s;%s\n' \
  "${x::4}-${x:4:2}-${x:6:2} ${x:8:2}:${x:10:2}:${x:12:2}" \
  "${y::4}-${y:4:2}-${y:6:2} ${y:8:2}:${y:10:2}:${y:12:2}" \
  "$z"
done


问:
How to create python regex to match only if at least 3 defined words are exist and allow other random words as well?
Here is my example:

```<code>re.compile("({tables}) ({middle})  ({end})"format(tables=config.kvkk_tables,middle=config.middle_sentence,end=config.end_of_sentence),re.IGNORECASE))
</code>```

One of tables, middle and end string must be in sentence. When this condition matched we do not want to check any other things allow any random words and characters.

```<code>tables = "oms.claim|oms.order"

middle = "request|requested"

end = "respond|responded|answer|answered"
</code>```

First Example:(Example needs to be matched) since there are at least 1 word from tables, middle and end.

"Hello could you please define my username for oms.claim table as it
is requested by order department and needs to be answered
immediately."

Second Example:(Example needs to be NOT matched) since there are not any word from end string.

"Hi, oms.order table requested from me, could you please help me about
that?"

What I tried and failed:

```<code>@bolt_app.message(re.compile("({tables}) ({middle} |(:?) {end})".
                         format(tables=config.kvkk_tables,middle=config.middle_sentence,end=config.end_of_sentence),re.IGNORECASE))
</code>```

答:
Finally, I figured it out.

```<code>re.compile("{tables}.* {middles}.* {end}".format(tables=config.kvkk_tables, middles=config.middles, end=config.end_of_sentence),re.IGNORECASE)
</code>```

So key point was using .*

This site is helped me a lot to test python regex

Note: I also covered my string definition in config.py with paranthesis like below:

```<code>tables = "(oms.claim|oms.order)"

middle = "(request|requested)"

end = "(respond|responded|answer|answered)"
</code>```

Body:
Here is my example:

re.compile("({tables}) ({middle})  ({end})"format(tables=config.kvkk_tables,middle=config.middle_sentence,end=config.end_of_sentence),re.IGNORECASE))

One of tables, middle and end string must be in sentence. When this condition matched we do not want to check any other things allow any random words and characters.

tables = "oms.claim|oms.order"

middle = "request|requested"

end = "respond|responded|answer|answered"

First Example:(Example needs to be matched) since there are at least 1 word from tables, middle and end.

"Hello could you please define my username for oms.claim table as it
is requested by order department and needs to be answered
immediately."

Second Example:(Example needs to be NOT matched) since there are not any word from end string.

"Hi, oms.order table requested from me, could you please help me about
that?"

What I tried and failed:

@bolt_app.message(re.compile("({tables}) ({middle} |(:?) {end})".
                         format(tables=config.kvkk_tables,middle=config.middle_sentence,end=config.end_of_sentence),re.IGNORECASE))

Body:
Finally, I figured it out.

re.compile("{tables}.* {middles}.* {end}".format(tables=config.kvkk_tables, middles=config.middles, end=config.end_of_sentence),re.IGNORECASE)

So key point was using .*

This site is helped me a lot to test python regex

Note: I also covered my string definition in config.py with paranthesis like below:

tables = "(oms.claim|oms.order)"

middle = "(request|requested)"

end = "(respond|responded|answer|answered)"


问:
Failing to add controls to a page dynamically
I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:

```<code>while (dr.Read())
{
     ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());
     myPanel.Controls.Add(imgSel);
}
</code>```

The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.

I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.

I've run the above code in the Page_Init and Page_Load events, both with the same result.

EDIT:
Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working.  But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?

EDIT 2:
Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.

EDIT 3:
After trying this method both with and without the constructor.  I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.

答:
Update: As Steve pointed out, the overload of LoadControl that uses the type won't take into account the controls in the ascx. This is also mentioned in this answer: Dynamically Loading a UserControl with LoadControl Method (Type, object[]).

As I mentioned before, the get/set are more in line with the asp.net model, so I recommend using that with the LoadControl variation that receives the user control path. That said, the Steve's version is an interesting alternative: http://www.grumpydev.com/2009/01/05/passing-parameters-using-loadcontrol/.

My take is the LoadControl with type is meant to be used with web custom controls instead.

If it is an user control you should use LoadControl(usercontrolpath) to get the instance of the user control.

You can use a constructor by doing:

```<code>var name = dr["Name"].ToString();
var imgSel = LoadControl(typeof(ImageSelect), new object[]{ name });
myPanel.Controls.Add(imgSel);
</code>```

Notice that depending on the project model you are using, you need to add a Reference to the aspx to use it with the typeof variation:

```<code><%@ Reference Control="~/somepath/myusercontrol.ascx" %>
</code>```

Ps. I usually use the set/get for controls as I find them more in line with the asp.net model

OwnerDisplayName: Neil N

ContentLicense: CC BY-SA 2.5

Body:
I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:

while (dr.Read())
{
     ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());
     myPanel.Controls.Add(imgSel);
}

The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.

I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.

I've run the above code in the Page_Init and Page_Load events, both with the same result.

EDIT:
Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working.  But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?

EDIT 2:
Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.

EDIT 3:
After trying this method both with and without the constructor.  I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.

LastEditorDisplayName: Freddy Rios

Body:
Update: As Steve pointed out, the overload of LoadControl that uses the type won't take into account the controls in the ascx. This is also mentioned in this answer: Dynamically Loading a UserControl with LoadControl Method (Type, object[]).

As I mentioned before, the get/set are more in line with the asp.net model, so I recommend using that with the LoadControl variation that receives the user control path. That said, the Steve's version is an interesting alternative: http://www.grumpydev.com/2009/01/05/passing-parameters-using-loadcontrol/.

My take is the LoadControl with type is meant to be used with web custom controls instead.

If it is an user control you should use LoadControl(usercontrolpath) to get the instance of the user control.

You can use a constructor by doing:

var name = dr["Name"].ToString();
var imgSel = LoadControl(typeof(ImageSelect), new object[]{ name });
myPanel.Controls.Add(imgSel);

Notice that depending on the project model you are using, you need to add a Reference to the aspx to use it with the typeof variation:

<%@ Reference Control="~/somepath/myusercontrol.ascx" %>

Ps. I usually use the set/get for controls as I find them more in line with the asp.net model

OwnerDisplayName: Freddy Rios


问:
Is there a way to prevent Android Studio or Intellij IDEA from downloading older version of gradle over and over?
I have the latest version of gradle (7.4) installed on my machine, every time I open a new project on Android Studio or Intellij to write Kotlin codes, it starts downloading old versions of gradle, is there a way to stop it or to run AS/IDEA offline ?</p>

答:
You can modify the distributionUrl property in the gradle-wrapper.properties file to point to a local file. So download a single copy of the necessary Gradle version from https://services.gradle.org/distributions/. Then before you open a project in the IDE, edit its gradle-wrapper.properties file to point to this local copy. It will copy the local file instead of downloading it.

For example, change

distributionUrl=“http\://services.gradle.org/distributions/gradle-3.3-bin.zip”
```
<p>to</p>
<pre class="lang-properties prettyprint-override"><code>distributionUrl=file\:///C:/gradle-7.4-all.zip
</code>```

I found a post about doing this here.

Body:
You can modify the distributionUrl property in the gradle-wrapper.properties file to point to a local file. So download a single copy of the necessary Gradle version from https://services.gradle.org/distributions/. Then before you open a project in the IDE, edit its gradle-wrapper.properties file to point to this local copy. It will copy the local file instead of downloading it.

For example, change

distributionUrl=“http\://services.gradle.org/distributions/gradle-3.3-bin.zip”

to

distributionUrl=file\:///C:/gradle-7.4-all.zip

I found a post about doing this here.


问:
How can be transformed [EventLoopFuture<Type>] into EventLoopFuture<[Type]> in Vapor?
I try to transform [EventLoopFuture Type ] into EventLoopFuture<[Type]>.

Code example:

```<code>struct QuestionDTO2: Content {
  var text: String?
}

func getUserQuestions(req: Request) throws -> EventLoopFuture<[QuestionDTO2]> {
  let a = try req.content.decode(GetUserQuestions.self)
  return Question.query(on: req.db).all().flatMap {qs -> EventLoopFuture<[QuestionDTO2]> in
    return qs.map {q -> EventLoopFuture<QuestionDTO2> in
      QuestionDTO2(text: q.text)
    }
  }
}
</code>```

答:
So the solution is:</p>
```<code>return Question.query(on: req.db).all().map { qs -> [QuestionDTO2] in
    return qs.map { q -> QuestionDTO2 in (
        QuestionDTO2(text: q.text)
      )
    }
  }
</code>```

Body:
I try to transform [EventLoopFuture Type ] into EventLoopFuture<[Type]>.

Code example:

struct QuestionDTO2: Content {
  var text: String?
}

func getUserQuestions(req: Request) throws -> EventLoopFuture<[QuestionDTO2]> {
  let a = try req.content.decode(GetUserQuestions.self)
  return Question.query(on: req.db).all().flatMap {qs -> EventLoopFuture<[QuestionDTO2]> in
    return qs.map {q -> EventLoopFuture<QuestionDTO2> in
      QuestionDTO2(text: q.text)
    }
  }
}

Body:
So the solution is:

return Question.query(on: req.db).all().map { qs -> [QuestionDTO2] in
    return qs.map { q -> QuestionDTO2 in (
        QuestionDTO2(text: q.text)
      )
    }
  }


答:
You can create groups using diff + ne + cumsum. The idea is to check if the value appears consecutively and if not, check where it breaks. Then cumsum is used to assign distinct numerical value to groups:

```<code>groups = df['Count'].diff().ne(0).cumsum()
</code>```

From the given input, this creates:

```<code>87     1
88     1
89     1
90     1
172    2
187    3
188    3
189    3
233    4
265    5
266    5
281    6
305    7
306    7
385    7
386    7
407    8
408    8
409    8
410    8
</code>```

Note that this assigns "Counts" to different groups even if they are the same as long as they are not consecutive.

Then you can use groupby on df by these new groups. For example, the average of "Activity" for each group is:

```<code>out = df.groupby(groups)['Activity'].mean()

Count
1    8.434083
2    6.133890
3    3.407720
4    4.089260
5    4.600415
6    6.133890
7    3.322520
8    7.156205
</code>```

Also, in case the original grouping column is not numeric (or a mix of dtypes), an alternative would be to use shift (thanks @StevenS):

```<code>df['count'].ne(df['count'].shift()).fillna(0).cumsum().astype(int)
</code>```

Title: Group by based on repeating column values of panda df to sum/average other columns

Body:
I have a df looking like this:

    Activity    Count   angle_1frame_abs
87  11.2454 4   1.9863239600400613
88  14.3124 4   1.633204419481332
89  7.15621 4   1.7235925045363631
90  1.02232 4   1.4205234792290875
172 6.13389 1   1.9096280055821166
187 1.02232 3   1.7052938965382456
188 7.15621 3   1.708833899378485
189 2.04463 3   1.2728507985832682
233 4.08926 1   1.554572584797844
265 4.08926 2   1.512615236089327
266 5.11157 2   1.4850900583919704
281 6.13389 1   1.162132169753371
305 3.06694 2   2.3605660470439824
306 3.06694 2   1.5685525010916657
385 5.11157 2   1.6579646804948973
386 2.04463 2   2.121520877298791
407 5.11157 4   1.1528498264361269
408 12.2678 4   1.7986876725933032
409 9.20082 4   1.5502484587771188
410 2.04463 4   1.6302871732665316

The column "Count" has stretches of repeating values that I would like to use to group the df.

In the above example I would have 8 groups.

I struggle keeping repeating values as separate groups.

My final aim would be to either average (Activity) or sum (angle_1frame_abs) the other columns based on these groups.

My desired output would be something like this (note: the activity and angle_1frames_abs values are made up):

Activity Count angle_1_frames_abs
9   4   1.7
6   1   1.9
4   3   1.7
4   1   1.5
4   2   1.4
6   1   1.1
4   2   1.5
8   4   1.5

I have been trying something like this but this only gave me groups based on unique values in the "count" column.

df.groupby(["Count"]).angle_1frame_abs.sum().reset_index()

Body:
You can create groups using diff + ne + cumsum. The idea is to check if the value appears consecutively and if not, check where it breaks. Then cumsum is used to assign distinct numerical value to groups:

groups = df['Count'].diff().ne(0).cumsum()

From the given input, this creates:

87     1
88     1
89     1
90     1
172    2
187    3
188    3
189    3
233    4
265    5
266    5
281    6
305    7
306    7
385    7
386    7
407    8
408    8
409    8
410    8

Note that this assigns "Counts" to different groups even if they are the same as long as they are not consecutive.

Then you can use groupby on df by these new groups. For example, the average of "Activity" for each group is:

out = df.groupby(groups)['Activity'].mean()

Count
1    8.434083
2    6.133890
3    3.407720
4    4.089260
5    4.600415
6    6.133890
7    3.322520
8    7.156205

Also, in case the original grouping column is not numeric (or a mix of dtypes), an alternative would be to use shift (thanks @StevenS):

df['count'].ne(df['count'].shift()).fillna(0).cumsum().astype(int)


问:
Django tries to INSERT instead of UPDATE on save()
I have a model

```<code>class DeviceAdmin(models.Model):
    dev_id = models.AutoField(db_column='dev_id', primary_key=True)
...
</code>```

A view locates an object:

```<code>device = DeviceAdmin.objects.get(uuid=uuid)
</code>```

then it makes some changes (or maybe not)

```<code>if (...):
    device.os_type = 'windows'
...
</code>```

then it tries to save any changes:

```<code>device.save()
</code>```

Here's where Django attempts to insert anther row instead of updating, causing a DB error

```<code>django.db.utils.IntegrityError: duplicate key value violates unique constraint
</code>```

There's a kind of similar question with solution:

Once I set the primary_key field to an AutoField, the issue went away.

However, my primary key is already an AutoField.

So I stepped through django code with debugger, and fund this in file ...site-packages\django\models\base.py:

```<code>    # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
    if pk_set and not force_insert:
        base_qs = cls._base_manager.using(using)
        values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
                  for f in non_pks]
        forced_update = update_fields or force_update
        updated = self._do_update(base_qs, using, pk_val, values, update_fields,
                                  forced_update)
        if force_update and not updated:
            raise DatabaseError("Forced update did not affect any rows.")
        if update_fields and not updated:
            raise DatabaseError("Save with update_fields did not affect any rows.")
    if not updated:
        if meta.order_with_respect_to:
            # If this is a model with an order_with_respect_to
            # autopopulate the _order field
            field = meta.order_with_respect_to
            filter_args = field.get_filter_kwargs_for_object(self)
            order_value = cls._base_manager.using(using).filter(**filter_args).count()
            self._order = order_value

        fields = meta.local_concrete_fields
        if not pk_set:
            fields = [f for f in fields if f is not meta.auto_field]

        update_pk = meta.auto_field and not pk_set
        result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
        if update_pk:
            setattr(self, meta.pk.attname, result)
    return updated
</code>```

It seems that if there are no changes (and thus update doesn't do anything), then it will try to insert a duplicate record.

I tested this with adding a save right after get:

```<code>device = DeviceAdmin.objects.get(uuid=uuid)
device.save()
</code>```

and it's trying to insert a duplicate.

Does this mean, my code needs to keep track if an object has to be saved to DB or not?

What's the simplest way to get around this problem?

UPDATE:

As a test, I put a save immediately after finding an object with get, without any changes:

```<code>device = DeviceAdmin.objects.get(uuid=uuid)
device.save()
</code>```

Django should know that the object is an existing one. And yet, it tries to insert a duplicate.

Similarly, creating a new object and calling save twice:

```<code>device = DeviceAdmin(...) # create a new object (it has null `dev_id`)
device.save()             # insert the new object into DB; get 'dev_id'
                          #   for the newly inserted record
device.save()             # This shouldn't do anything!
</code>```

This second save attempts to insert a duplicate - as I can see if I step through the django code with debugger.

答:
One reason why this might occur is if your primary key field is defined with a default value. I don't see a default in your example, but I also don't see that the datatype is a uuid, so I thought I would provide this answer just in case.

If your model's pkey looks like this: models.UUIDField(primary_key=True, default=uuid.uuid4), calling save will always result in an INSERT rather than an UPDATE. I believe this is true even if you pass force_update=True to the save method. This was at one point submitted as a bug, but
is actually the intended behavior of Django 3 according to the docs.

There are a couple of ways you can handle this issue if you want to use a uuid as your primary key. The best way is probably to follow the recommendation of the docs and use either the update or update_or_create methods to update your model instances.

```<code>>>> MyModel.objects.update_or_create(pk=existing_pk, defaults={'name': 'new name'})
>>> MyModel.objects.filter(pk=existing_pk).update(name='new name')
</code>```

Alternatively, you could also remove the default argument from your primary key definition and ensure that each instance has a uuid assigned on save by overriding your model's save method - for example:

```<code>def save(self, *args, **kwargs):
    if not self.id:
        self.id = uuid.uuid1()
        super(DeviceAdmin, self).save(*args, **kwargs)
</code>```

Body:
I have a model

class DeviceAdmin(models.Model):
    dev_id = models.AutoField(db_column='dev_id', primary_key=True)
...

A view locates an object:

device = DeviceAdmin.objects.get(uuid=uuid)

then it makes some changes (or maybe not)

if (...):
    device.os_type = 'windows'
...

then it tries to save any changes:

device.save()

Here's where Django attempts to insert anther row instead of updating, causing a DB error

django.db.utils.IntegrityError: duplicate key value violates unique constraint

There's a kind of similar question with solution:

Once I set the primary_key field to an AutoField, the issue went away.

However, my primary key is already an AutoField.

So I stepped through django code with debugger, and fund this in file ...site-packages\django\models\base.py:

    # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
    if pk_set and not force_insert:
        base_qs = cls._base_manager.using(using)
        values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
                  for f in non_pks]
        forced_update = update_fields or force_update
        updated = self._do_update(base_qs, using, pk_val, values, update_fields,
                                  forced_update)
        if force_update and not updated:
            raise DatabaseError("Forced update did not affect any rows.")
        if update_fields and not updated:
            raise DatabaseError("Save with update_fields did not affect any rows.")
    if not updated:
        if meta.order_with_respect_to:
            # If this is a model with an order_with_respect_to
            # autopopulate the _order field
            field = meta.order_with_respect_to
            filter_args = field.get_filter_kwargs_for_object(self)
            order_value = cls._base_manager.using(using).filter(**filter_args).count()
            self._order = order_value

        fields = meta.local_concrete_fields
        if not pk_set:
            fields = [f for f in fields if f is not meta.auto_field]

        update_pk = meta.auto_field and not pk_set
        result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
        if update_pk:
            setattr(self, meta.pk.attname, result)
    return updated

It seems that if there are no changes (and thus update doesn't do anything), then it will try to insert a duplicate record.

I tested this with adding a save right after get:

device = DeviceAdmin.objects.get(uuid=uuid)
device.save()

and it's trying to insert a duplicate.

Does this mean, my code needs to keep track if an object has to be saved to DB or not?

What's the simplest way to get around this problem?

UPDATE:

As a test, I put a save immediately after finding an object with get, without any changes:

device = DeviceAdmin.objects.get(uuid=uuid)
device.save()

Django should know that the object is an existing one. And yet, it tries to insert a duplicate.

Similarly, creating a new object and calling save twice:

device = DeviceAdmin(...) # create a new object (it has null `dev_id`)
device.save()             # insert the new object into DB; get 'dev_id'
                          #   for the newly inserted record
device.save()             # This shouldn't do anything!

This second save attempts to insert a duplicate - as I can see if I step through the django code with debugger.

Body:
One reason why this might occur is if your primary key field is defined with a default value. I don't see a default in your example, but I also don't see that the datatype is a uuid, so I thought I would provide this answer just in case.

If your model's pkey looks like this: models.UUIDField(primary_key=True, default=uuid.uuid4), calling save will always result in an INSERT rather than an UPDATE. I believe this is true even if you pass force_update=True to the save method. This was at one point submitted as a bug, but
is actually the intended behavior of Django 3 according to the docs.

There are a couple of ways you can handle this issue if you want to use a uuid as your primary key. The best way is probably to follow the recommendation of the docs and use either the update or update_or_create methods to update your model instances.

>>> MyModel.objects.update_or_create(pk=existing_pk, defaults={'name': 'new name'})
>>> MyModel.objects.filter(pk=existing_pk).update(name='new name')

Alternatively, you could also remove the default argument from your primary key definition and ensure that each instance has a uuid assigned on save by overriding your model's save method - for example:

def save(self, *args, **kwargs):
    if not self.id:
        self.id = uuid.uuid1()
        super(DeviceAdmin, self).save(*args, **kwargs)


问:
Errors using MailChimp API adding email address to list
I am trying to add email addresses to my mailchimp mailing list but am getting an error saying

```<code>Access Denied
You don't have permission to access "http://us9.api.mailchimp.com/3.0/lists/######/members/" on this server.
Reference #18.1e89655f.1546511382.213522b5
</code>```

I have just created the API key and haven't done much with MailChimp before. I think the list ID is correct, I just grabbed it from the URL of my actual list in a browser https://us9.admin.mailchimp.com/lists/members/?id=######

```<code><?php

$email = '####@####.##';
$authToken = '#######################-us9';
$email_list = '######';

$postData = array(
    "email_address" => "$email",
    "status" => "subscribed",
    "merge_fields" => array(
    "NAME"=> "",
    "PHONE"=> "")
);

$ch = curl_init('https://us9.api.mailchimp.com/3.0/lists/'.$email_list.'/members/');

curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

$response = curl_exec($ch);

var_dump($response);

?>
</code>```

答:
It was a transient error for me, which went away after a couple of minutes. If it doesn't then somehow Akamai has probably blacklisted you and you need to contact Mailchimp (as Akamai does not handle Mailchimp specific requests directly).

If you look in the response headers, it says Server: AkamaiGHost, which I assume is the proxy Mailchimp is using. Also the response is text/html, which does not match Mailchimp's own documented error formats–another sign that it is the proxy blocking you and not Mailchimp itself.

Body:
I am trying to add email addresses to my mailchimp mailing list but am getting an error saying

Access Denied
You don't have permission to access "http://us9.api.mailchimp.com/3.0/lists/######/members/" on this server.
Reference #18.1e89655f.1546511382.213522b5

I have just created the API key and haven't done much with MailChimp before. I think the list ID is correct, I just grabbed it from the URL of my actual list in a browser https://us9.admin.mailchimp.com/lists/members/?id=######

<?php

$email = '####@####.##';
$authToken = '#######################-us9';
$email_list = '######';

$postData = array(
    "email_address" => "$email",
    "status" => "subscribed",
    "merge_fields" => array(
    "NAME"=> "",
    "PHONE"=> "")
);

$ch = curl_init('https://us9.api.mailchimp.com/3.0/lists/'.$email_list.'/members/');

curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

$response = curl_exec($ch);

var_dump($response);

?>


问:
Exception: The starting row of the range is too small
I'm using this code to search column 1 on a spreadsheet for the value 'Net Income'. I want this code to return the row position of with the value 'Net Income' so I can apply some formatting specific to that row based on that value. Here's the code I currently have:

```<code>const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);

  const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
  netIncomeRange.setFontWeight('bold');
</code>```

When I run the code, I get the error "Exception: The starting row of the range is too small." and cannot figure out how to fix this ):

*Edit - I was taught to search through the rows this way as the position of the 'Net Income' row will change over time and I would like the bold formatting to follow and apply to whatever row ends up with the value 'Net Income'.

答:
If you want to get an index of a value in array you can use the method array.findIndex(). Something like this:

```<code>const netIncomeRow = values.findIndex(x => x[0] == 'Net Income');
</code>```

Here is the function:

```<code>function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var values = sh.getDataRange().getValues();
  var index = values.findIndex(x => x[0]== 'Net Income') + 1;

  if (index) sh.getRange(index,1,1,sh.getLastColumn()).setFontWeight('Bold');
}
</code>```

Before:

After:

Body:
I'm using this code to search column 1 on a spreadsheet for the value 'Net Income'. I want this code to return the row position of with the value 'Net Income' so I can apply some formatting specific to that row based on that value. Here's the code I currently have:

const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);

  const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
  netIncomeRange.setFontWeight('bold');

When I run the code, I get the error "Exception: The starting row of the range is too small." and cannot figure out how to fix this ):

*Edit - I was taught to search through the rows this way as the position of the 'Net Income' row will change over time and I would like the bold formatting to follow and apply to whatever row ends up with the value 'Net Income'.

Body:
If you want to get an index of a value in array you can use the method array.findIndex(). Something like this:

const netIncomeRow = values.findIndex(x => x[0] == 'Net Income');

Here is the function:

function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var values = sh.getDataRange().getValues();
  var index = values.findIndex(x => x[0]== 'Net Income') + 1;

  if (index) sh.getRange(index,1,1,sh.getLastColumn()).setFontWeight('Bold');
}

Before:

After:


问:
How i get active browser page with puppeteer?
im trying to do a auto giveaways just by clicking on a button for participate everytime the timer reset. I don't find working how i can control multiple page at the same time. i found "bringToFront()" as I understood goes from page 1 => 2 ... I used this function and another one for get current page name and i can't get page function.

(const this => "giveway" = await browser.newPage();)

If someone can help me please thanks.
Here the main code you need:

```<code>const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});
const login = await browser.newPage();
const anotherPage = await browser.newPage();

var currentPage = getActivePage(browser, 3000);
var pageNum = 1;

//Imagine idk is a giveaway website.
await login.goto('example.com');
await anotherPage.goto('idk.com');

//
  if(loaded){
    //const participateBtn =  await (don't work) =>"currentPage" (can't find it with currentPage only with anotherPage) =>".$x" ("//button[@id='giveaway-enter']")
    const participateBtn =  await currentPage.$x("//button[@id='giveaway-enter']")
      do{
        if(pageNum <= 1){
            await participateBtn[0].click();
            console.log("Click! 1");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum == 2){
            await participateBtn[0].click();
            console.log("Click! 2");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum >= 3){
            await participateBtn[0].click();
            console.log("Click! 3");
            pageNum = 1;
        }
      }while(loaded)
   }

   //Function i found.
   async function getActivePage(browser, timeout) {
   var start = new Date().getTime();
   while(new Date().getTime() - start < timeout) {
    var pages = await browser.pages();
    var arr = [];
    for (const p of pages) {
        if(await p.evaluate(() => { return document.visibilityState == 'visible' })) {
            arr.push(p);
        }
    }
    if(arr.length == 1) return arr[0];
}
throw "Unable to get active page";
}
})();
</code>```

答:
You can get the default page (1st tab) with:

const currentPage = browser.pages().then(allPages => allPages[0]);
```

Body:
im trying to do a auto giveaways just by clicking on a button for participate everytime the timer reset. I don't find working how i can control multiple page at the same time. i found "bringToFront()" as I understood goes from page 1 => 2 ... I used this function and another one for get current page name and i can't get page function.

(const this => "giveway" = await browser.newPage();)

If someone can help me please thanks.
Here the main code you need:

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});
const login = await browser.newPage();
const anotherPage = await browser.newPage();

var currentPage = getActivePage(browser, 3000);
var pageNum = 1;

//Imagine idk is a giveaway website.
await login.goto('example.com');
await anotherPage.goto('idk.com');

//
  if(loaded){
    //const participateBtn =  await (don't work) =>"currentPage" (can't find it with currentPage only with anotherPage) =>".$x" ("//button[@id='giveaway-enter']")
    const participateBtn =  await currentPage.$x("//button[@id='giveaway-enter']")
      do{
        if(pageNum <= 1){
            await participateBtn[0].click();
            console.log("Click! 1");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum == 2){
            await participateBtn[0].click();
            console.log("Click! 2");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum >= 3){
            await participateBtn[0].click();
            console.log("Click! 3");
            pageNum = 1;
        }
      }while(loaded)
   }

   //Function i found.
   async function getActivePage(browser, timeout) {
   var start = new Date().getTime();
   while(new Date().getTime() - start < timeout) {
    var pages = await browser.pages();
    var arr = [];
    for (const p of pages) {
        if(await p.evaluate(() => { return document.visibilityState == 'visible' })) {
            arr.push(p);
        }
    }
    if(arr.length == 1) return arr[0];
}
throw "Unable to get active page";
}
})();


问:
How to mark classes as Obsolete on UML
I have a few classes on my UML diagram which should not be used, but still available.
Is there any way to mark these classes as obsolete?

I've seen <> notation somewhere, but can not find how to use it in MS Visio 2003.

And another question. Should these classes be on UML diagram at all? I can imagine answer on this question would be on "per case" basis, but I'm interested in hearing general opinions. And if you put obsolete classes on your UML diagrams, why you did it? or why not?

Thanks!

答:
I think that your model should include all your project and then you extract views from your model. If a class is not having any value in a specific view then this class should be removed from your class diagram view diagram but not from your model.

If you want to keep this class in your diagram then you can add a small comment (usually yellow square) or change the color of the class. I usually use green for class and then change the color to grey/green almost invisible but still visible color for non strategic classes.

Hope this help.

Title: How to mark classes as Obsolete on UML


问:
MediaPlayer App is crashing when i try to run
I'm beginner in android development and tried to create a simple mediaplayer app which plays media from local source.

But it's crashing when i try to open it.

This is my java code.

```<code>package com.example.media;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    Button play,pause;
    SeekBar s;
    MediaPlayer m;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        m=MediaPlayer.create(this,R.raw.live);

        play=findViewById(R.id.button3);
        pause=findViewById(R.id.button4);
        s.findViewById(R.id.seekBar);
        s.setMax(m.getDuration());
        s.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser)m.seekTo(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m.start();
            }
        });
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m.pause();
            }
        });

    }
}
</code>```

答:
You need to initialize the seekbar object instead of calling the findViewById method.

So just replace the dot with equal sign :

```<code>  s=findViewById(R.id.seekBar);
</code>```

Body:
I'm beginner in android development and tried to create a simple mediaplayer app which plays media from local source.

But it's crashing when i try to open it.

This is my java code.

package com.example.media;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    Button play,pause;
    SeekBar s;
    MediaPlayer m;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        m=MediaPlayer.create(this,R.raw.live);

        play=findViewById(R.id.button3);
        pause=findViewById(R.id.button4);
        s.findViewById(R.id.seekBar);
        s.setMax(m.getDuration());
        s.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser)m.seekTo(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m.start();
            }
        });
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m.pause();
            }
        });

    }
}

Body:
You need to initialize the seekbar object instead of calling the findViewById method.

So just replace the dot with equal sign :

  s=findViewById(R.id.seekBar);


问:
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
I have a Rancher Deskop(dockerd) on M1 MacOS and when I am trying to build below dockerfile I am getting an error such as below. Here is the command how I am trying to build the image docker build -t te-grafana-dashboards-toolchain --no-cache .

I tried to change the platforms but nonae of them worked for me. I am a bit lost about this platform issue for M1 but any help will be appreciated, What I am doing wrong? What might the root cause of this?

```<code>Removing intermediate container 70af516d5d6b
 ---> a69229847153
Step 5/6 : RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
 ---> Running in 13545862fffe
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
Removing intermediate container 13545862fffe
</code>```

Dockerfile

```<code>FROM --platform=linux/amd64 ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-amd64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-amd64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-amd64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
WORKDIR /workspace
</code>```

答:
this resolved my issue.</p>
```<code>FROM ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-arm64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-arm64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-arm64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb@latest; ln -s /root/go/bin/jb /usr/bin/jb
WORKDIR /workspace
</code>```

Body:
I have a Rancher Deskop(dockerd) on M1 MacOS and when I am trying to build below dockerfile I am getting an error such as below. Here is the command how I am trying to build the image docker build -t te-grafana-dashboards-toolchain --no-cache .

I tried to change the platforms but nonae of them worked for me. I am a bit lost about this platform issue for M1 but any help will be appreciated, What I am doing wrong? What might the root cause of this?

Removing intermediate container 70af516d5d6b
 ---> a69229847153
Step 5/6 : RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
 ---> Running in 13545862fffe
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
Removing intermediate container 13545862fffe

Dockerfile

FROM --platform=linux/amd64 ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-amd64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-amd64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-amd64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
WORKDIR /workspace

Body:
this resolved my issue.

FROM ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-arm64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-arm64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-arm64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb@latest; ln -s /root/go/bin/jb /usr/bin/jb
WORKDIR /workspace