问:
Sending ajax request to controller it return the script in network response
I am using ajax to get data from controller. I am using jquery for ajax and making a simple call to a php function. I am getting the invoice template array from custom class name QbdDecta file through controller, when i return the array response()->json($ary) to my desire view , network response show me long script.

```<code><script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if (/\bsf-dump-compact\b/.test(oldClass)) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if (/\bsf-dump-expanded\b/.test(oldClass)) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } if (doc.createEvent && s.dispatchEvent) { var event = doc.createEvent('Event'); event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false); s.dispatchEvent(event); } a.lastChild.innerHTML = arrow; s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass); if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (-1 == a[s].className.indexOf(newClass)) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-expanded\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-compact\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt = root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = []; while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; } function a(e, f) { addEventListener(root, e, function (e, n) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } else { n = /\bsf-dump-ellipsis\b/.test(e.target.className) ? e.target.parentNode : e.target; if ((n = n.nextElementSibling) && 'A' == n.tagName) { if (!/\bsf-dump-toggle\b/.test(n.className)) { n = n.nextElementSibling || n; } f(n, e, true); } } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } function xpathString(str) { var parts = str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) { return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part + "'"; }); return "concat(" + parts.join(",") + ", '')"; } function xpathHasClass(className) { return "contains(concat(' ', normalize-space(@class), ' '), ' " + className +" ')"; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; } else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if (/\bsf-dump-compact\b/.test(r.className)) { toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } else if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault(); e = a.parentNode.parentNode; e.className = e.className.replace(/\bsf-dump-str-(expand|collapse)\b/, a.parentNode.className); } }); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; if ('SAMP' == elt.tagName) { a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x += elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); var className = elt.className; elt.className = 'sf-dump-expanded'; if (className ? 'sf-dump-expanded' !== className : (x > options.maxDepth)) { toggle(a); } } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[@#]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1); return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(), currentRect, searchRect; if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); if ('scrollIntoView' in currentNode) { currentNode.scrollIntoView(true); currentRect = currentNode.getBoundingClientRect(); searchRect = search.getBoundingClientRect(); if (currentRect.top < (searchRect.top + searchRect.height)) { window.scrollBy(0, -(searchRect.top + searchRect.height + 5)); } } } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = ' <input type="text" class="sf-dump-search-input"> <span class="sf-dump-search-count">0 of 0<\/span> <button type="button" class="sf-dump-search-input-previous" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 1331l-166 165q-19 19-45 19t-45-19L896 965l-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> <button type="button" class="sf-dump-search-input-next" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 808l-742 741q-19 19-45 19t-45-19L109 808q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput = search.querySelector('.sf-dump-search-input'); var counter = search.querySelector('.sf-dump-search-count'); var searchInputTimer = 0; var previousSearchQuery = ''; addEventListener(searchInput, 'keyup', function (e) { var searchQuery = e.target.value; /* Don't perform anything if the pressed key didn't change the query */ if (searchQuery === previousSearchQuery) { return; } previousSearchQuery = searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root); resetHighlightedNodes(root); if ('' === searchQuery) { counter.textContent = '0 of 0'; return; } var classMatches = [ "sf-dump-str", "sf-dump-key", "sf-dump-public", "sf-dump-protected", "sf-dump-private", ].map(xpathHasClass).join(' or '); var xpathResult = doc.evaluate('.//span[' + classMatches + '][contains(translate(child::text(), ' + xpathString(searchQuery.toUpperCase()) + ', ' + xpathString(searchQuery.toLowerCase()) + '), ' + xpathString(searchQuery.toLowerCase()) + ')]', root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node = xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state); }, 400); }); Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) { addEventListener(btn, 'click', function (e) { e.preventDefault(); -1 !== e.target.className.indexOf('next') ? state.next() : state.previous(); searchInput.focus(); collapseAll(root); showCurrent(state); }) }); addEventListener(root, 'keydown', function (e) { var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className); if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) { /* F3 or CMD/CTRL + F */ if (70 === e.keyCode && document.activeElement === searchInput) { /* * If CMD/CTRL + F is hit while having focus on search input, * the user probably meant to trigger browser search instead. * Let the browser execute its behavior: */ return; } e.preventDefault(); search.className = search.className.replace(/\bsf-dump-search-hidden\b/, ''); searchInput.focus(); } else if (isSearchActive) { if (27 === e.keyCode) { /* ESC key */ search.className += ' sf-dump-search-hidden'; e.preventDefault(); resetHighlightedNodes(root); searchInput.value = ''; } else if ( (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */ || 13 === e.keyCode /* Enter */ || 114 === e.keyCode /* F3 */ ) { e.preventDefault(); e.shiftKey ? state.previous() : state.next(); collapseAll(root); showCurrent(state); } } }); } if (0 >= options.maxStringLength) { return; } try { elt = root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t = []; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x = s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML; elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength); elt.className += ' sf-dump-str-collapse'; elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+ '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>'; } } } catch (e) { } }; })(document); </script><style> pre.sf-dump { display: block; white-space: pre; padding: 5px; overflow: initial !important; } pre.sf-dump:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; color: inherit; } pre.sf-dump img { max-width: 50em; max-height: 50em; margin: .5em 0 0 0; padding: 0; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAHUlEQVQY02O8zAABilCaiQEN0EeA8QuUcX9g3QEAAjcC5piyhyEAAAAASUVORK5CYII=) #D3D3D3; } pre.sf-dump .sf-dump-ellipsis { display: inline-block; overflow: visible; text-overflow: ellipsis; max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align: top; } pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width: none; } pre.sf-dump code { display:inline; padding:0; background:none; } .sf-dump-str-collapse .sf-dump-str-collapse { display: none; } .sf-dump-str-expand .sf-dump-str-expand { display: none; } .sf-dump-public.sf-dump-highlight, .sf-dump-protected.sf-dump-highlight, .sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight, .sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3); border: 1px solid #7DA0B1; border-radius: 3px; } .sf-dump-public.sf-dump-highlight-active, .sf-dump-protected.sf-dump-highlight-active, .sf-dump-private.sf-dump-highlight-active, .sf-dump-str.sf-dump-highlight-active, .sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0, 0.4); border: 1px solid #ffa500; border-radius: 3px; } pre.sf-dump .sf-dump-search-hidden { display: none !important; } pre.sf-dump .sf-dump-search-wrapper { font-size: 0; white-space: nowrap; margin-bottom: 5px; display: flex; position: -webkit-sticky; position: sticky; top: 5px; } pre.sf-dump .sf-dump-search-wrapper > * { vertical-align: top; box-sizing: border-box; height: 21px; font-weight: normal; border-radius: 0; background: #FFF; color: #757575; border: 1px solid #BBB; } pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input { padding: 3px; height: 21px; font-size: 12px; border-right: none; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: #000; min-width: 15px; width: 100%; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous { background: #F2F2F2; outline: none; border-left: none; font-size: 0; line-height: 0; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg { pointer-events: none; width: 12px; height: 12px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count { display: inline-block; padding: 0 5px; margin: 0; border-left: none; line-height: 21px; font-size: 12px; }pre.sf-dump, pre.sf-dump .sf-dump-default{background-color:#18171B; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all}pre.sf-dump .sf-dump-num{font-weight:bold; color:#1299DA}pre.sf-dump .sf-dump-const{font-weight:bold}pre.sf-dump .sf-dump-str{font-weight:bold; color:#56DB3A}pre.sf-dump .sf-dump-note{color:#1299DA}pre.sf-dump .sf-dump-ref{color:#A0A0A0}pre.sf-dump .sf-dump-public{color:#FFFFFF}pre.sf-dump .sf-dump-protected{color:#FFFFFF}pre.sf-dump .sf-dump-private{color:#FFFFFF}pre.sf-dump .sf-dump-meta{color:#B729D9}pre.sf-dump .sf-dump-key{color:#56DB3A}pre.sf-dump .sf-dump-index{color:#1299DA}pre.sf-dump .sf-dump-ellipsis{color:#FF8400}pre.sf-dump .sf-dump-ns{user-select:none;}pre.sf-dump .sf-dump-ellipsis-note{color:#1299DA}</style><pre class=sf-dump id=sf-dump-1661373416 data-indent-pad="  ">"<span class=sf-dump-str title="328 characters">{"items":{"litem_obj1":{"Description":"Normal Sales : 2020-02-01","Quantity":"1","UnitAmount":"102756.71","AccountCode":"3000","TaxType":"INPUT","TaxAmount":"0","DiscountRate":"0"},"litem_obj2":{"Description":"Refunds","Quantity":"1","UnitAmount":"-0","AccountCode":"3010","TaxType":"INPUT","TaxAmount":"0","DiscountRate":"0"}}}</span>"
```
```

<p><strong>Script</strong></p>

<pre class="lang-js prettyprint-override"><code>function getdate() {
  var date = document.getElementById('exchange_period').value;
  var arr = date.split(' - ');
  var start_date = arr[0];
  var end_date = arr[1];
  var url = BASE_URL + "invoices/decta/daily/" + start_date + '/' + end_date;
  $.ajax({
    url: url,
    type: "get",
    success: function(res) {
      response = JSON.parse(res);
      alert(response);
      alert(res);
      document.getElementById("message").value = response;
    }
  });
}
</code>```

QbdDecta.php

```<code>public function create_invoice($contact) {
    $invoice_template = $this->get_template();
    $ary=[
        'items' => $invoice_template['items'],
    ];
    return response()->json($ary);
}
</code>```

答:
Your AJAX request should be better like this:

```<code>$.ajax({
  url:url,
  method:'GET',
  dataType:'json',
  success:function(data) {
    // your success actions
  },
  error: function (request, status, error) {
    // your error actions
  }
});
</code>```

You don't have to parse the given response. You can just assign them to a div.

```<code>success:function(data) {
  $('#myDiv').html(data);
},
</code>```

Cheers,
Niklas

Body:
I am using ajax to get data from controller. I am using jquery for ajax and making a simple call to a php function. I am getting the invoice template array from custom class name QbdDecta file through controller, when i return the array response()->json($ary) to my desire view , network response show me long script.

"{"items":{"litem_obj1":{"Description":"Normal Sales : 2020-02-01","Quantity":"1","UnitAmount":"102756.71","AccountCode":"3000","TaxType":"INPUT","TaxAmount":"0","DiscountRate":"0"},"litem_obj2":{"Description":"Refunds","Quantity":"1","UnitAmount":"-0","AccountCode":"3010","TaxType":"INPUT","TaxAmount":"0","DiscountRate":"0"}}}"

Script

function getdate() {
  var date = document.getElementById('exchange_period').value;
  var arr = date.split(' - ');
  var start_date = arr[0];
  var end_date = arr[1];
  var url = BASE_URL + "invoices/decta/daily/" + start_date + '/' + end_date;
  $.ajax({
    url: url,
    type: "get",
    success: function(res) {
      response = JSON.parse(res);
      alert(response);
      alert(res);
      document.getElementById("message").value = response;
    }
  });
}

QbdDecta.php

public function create_invoice($contact) {
    $invoice_template = $this->get_template();
    $ary=[
        'items' => $invoice_template['items'],
    ];
    return response()->json($ary);
}

Body:
Your AJAX request should be better like this:

$.ajax({
  url:url,
  method:'GET',
  dataType:'json',
  success:function(data) {
    // your success actions
  },
  error: function (request, status, error) {
    // your error actions
  }
});

You don't have to parse the given response. You can just assign them to a div.

success:function(data) {
  $('#myDiv').html(data);
},

Cheers,
Niklas


来源: stackexchange

问:
How to run FFMPEG in laravel project
I can run this code via cmd. And my question is how can I run this command to my laravel project locally and also to my live server?

ffmpeg -i input1.webm -i input2.webm output.mp3

Thanks in advance.

答:
you install the ffmpeg .exe file on your system.

Then you use that code in your application so,first you need to install the application of ffmpeg

ContentLicense: CC BY-SA 4.0

Title: How to run FFMPEG in laravel project


问:
git ignore directory except for specified
I want to ignore entire public_html/ directory except one file inside

I give .gitignore as below:

```<code>public_html/*
!public_html/config/config.php
</code>```

However, when I run git status , I can not find config.php has been included.

答:
Change .gitignore to

```<code>public_html/*
</code>```

And force adding config.php into index.

```<code>git add -f public_html/config/config.php
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to ignore entire public_html/ directory except one file inside

I give .gitignore as below:

public_html/*
!public_html/config/config.php

However, when I run git status , I can not find config.php has been included.

Body:
Change .gitignore to

public_html/*

And force adding config.php into index.

git add -f public_html/config/config.php


问:
Array/Object destructuring
How do I destructure this JSON object, so I can get the "Name" property names.
I'm trying to get them showed on my DOM, but I have no clue how to access "Warehouses" object then it's arrays, and the objects into arrays.</p>

```<code>{
    "ErrorCode": 0,
    "ErrorMessage": null,
    "Warehouses": [
        {
            "Code": null,
            "Name": "Depozit Fabrica",
            "WarehouseID": "cb4fbab4-b8db-4807-a2b0-fad710f1fd9e"
        },
        {
            "Code": "3",
            "Name": "Depozit Magazin",
            "WarehouseID": "dfa08a15-e3a0-4d43-8af6-c24a9d43101c"
        },
        {
            "Code": null,
            "Name": "Depozit Ograda",
            "WarehouseID": "0dc8318d-305c-4e09-a31c-aa6fd44bf2ca"
        }
    ]
}
</code>```

答:
Solved it myself.

```<code>const url = "\url";
async function getData() {
  const response = await fetch(url);
  const data = await response.json();
  const { Warehouses } = data;

  // Loop through all warehouse's items

  for (var i = 0; i < Warehouses.length; i++) {
     const dataItems = Warehouses[i].Name;
   }
}
getData();
</code>```

Now the problem is I don't know how to show every Name element in DOM separately, like in a
 tag. I want to give them a click event listener further, so I can get more json data in DOM.

Title: Array/Object destructuring

Body:
How do I destructure this JSON object, so I can get the "Name" property names.
I'm trying to get them showed on my DOM, but I have no clue how to access "Warehouses" object then it's arrays, and the objects into arrays.

{
    "ErrorCode": 0,
    "ErrorMessage": null,
    "Warehouses": [
        {
            "Code": null,
            "Name": "Depozit Fabrica",
            "WarehouseID": "cb4fbab4-b8db-4807-a2b0-fad710f1fd9e"
        },
        {
            "Code": "3",
            "Name": "Depozit Magazin",
            "WarehouseID": "dfa08a15-e3a0-4d43-8af6-c24a9d43101c"
        },
        {
            "Code": null,
            "Name": "Depozit Ograda",
            "WarehouseID": "0dc8318d-305c-4e09-a31c-aa6fd44bf2ca"
        }
    ]
}

Body:
Solved it myself.

const url = "\url";
async function getData() {
  const response = await fetch(url);
  const data = await response.json();
  const { Warehouses } = data;

  // Loop through all warehouse's items

  for (var i = 0; i < Warehouses.length; i++) {
     const dataItems = Warehouses[i].Name;
   }
}
getData();

Now the problem is I don't know how to show every Name element in DOM separately, like in a
 tag. I want to give them a click event listener further, so I can get more json data in DOM.


问:
How to returned image to original position when zoomout - AndroidX
I want to return my image to original position when I zoom out my image and the the image scale is smaller than the first initial image size</p>

```<code>@Override
public boolean onTouch(View v, MotionEvent event)
{
    ImageView view = (ImageView) v;
    view.setScaleType(ImageView.ScaleType.MATRIX);
    float scale = 0;

    dumpEvent(event);
    // Handle touch events here...

    switch (event.getAction() & MotionEvent.ACTION_MASK)
    {
        case MotionEvent.ACTION_DOWN:   // first finger down only
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            Log.d(TAG, "mode=DRAG"); // write to LogCat
            mode = DRAG;
            break;

        /*case MotionEvent.ACTION_UP: // first finger lifted

        case MotionEvent.ACTION_POINTER_UP: // second finger lifted

            mode = NONE;
            Log.d(TAG, "mode=NONE");
            break;*/

        case MotionEvent.ACTION_UP: // first finger lifted
            mode = NONE;
            break;
        case MotionEvent.ACTION_POINTER_UP:// second finger lifted
            /*matrix.set(savedMatrix);*/
            /*view.setScaleType(ImageView.ScaleType.CENTER);*/
            Log.v("/h/", ""+scale);

            mode = ZOOMOUT;

            //When release back to position
            matrix.set(savedMatrix);
            Log.d(TAG, "mode=ZOOMOUT");
            break;

        case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down

            oldDist = spacing(event);
            Log.d(TAG, "oldDist=" + oldDist);
            if (oldDist > 5f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
                Log.d(TAG, "mode=ZOOM");
            }
            break;

        case MotionEvent.ACTION_MOVE:

            if (mode == DRAG)
            {
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix  of points
            }
            else if (mode == ZOOM)
            {
                // pinch zooming
                float newDist = spacing(event);
                Log.d(TAG, "newDist=" + newDist);

                if (newDist > 5f)
                {
                    matrix.set(savedMatrix);
                    scale = newDist / oldDist; // setting the scaling of the
                    // matrix...if scale > 1 means
                    // zoom in...if scale < 1 means
                    // zoom out
                    if(scale>1) {
                        //Zoom In
                    }else if(scale<1) {
                        //Zoom Out
                    }

                    matrix.postScale(scale, scale, mid.x, mid.y);

                    Log.v("/h/", ""+scale+mode);

                }

            }

            break;

    }

    view.setImageMatrix(matrix); // display the transformation on screen

    return true; // indicate event was handled
}

/*
 * --------------------------------------------------------------------------
 * Method: spacing Parameters: MotionEvent Returns: float Description:
 * checks the spacing between the two fingers on touch
 * ----------------------------------------------------
 */

private float spacing(MotionEvent event)
{
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float) Math.sqrt(x * x + y * y);
}

/*
 * --------------------------------------------------------------------------
 * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
 * Description: calculates the midpoint between the two fingers
 * ------------------------------------------------------------
 */

private void midPoint(PointF point, MotionEvent event)
{
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}
</code>```

答:
Set savedMatrix to view.getImageMatrix() on ACTION_DOWN.

Do zoom/drag changes on a separate matrix

On ACTION_UP or ACTION_POINTER_UP set original matrix back to imageview.
view.setImageMatrix(savedMatrix)

Body:
I want to return my image to original position when I zoom out my image and the the image scale is smaller than the first initial image size

@Override
public boolean onTouch(View v, MotionEvent event)
{
    ImageView view = (ImageView) v;
    view.setScaleType(ImageView.ScaleType.MATRIX);
    float scale = 0;

    dumpEvent(event);
    // Handle touch events here...

    switch (event.getAction() & MotionEvent.ACTION_MASK)
    {
        case MotionEvent.ACTION_DOWN:   // first finger down only
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            Log.d(TAG, "mode=DRAG"); // write to LogCat
            mode = DRAG;
            break;

        /*case MotionEvent.ACTION_UP: // first finger lifted

        case MotionEvent.ACTION_POINTER_UP: // second finger lifted

            mode = NONE;
            Log.d(TAG, "mode=NONE");
            break;*/

        case MotionEvent.ACTION_UP: // first finger lifted
            mode = NONE;
            break;
        case MotionEvent.ACTION_POINTER_UP:// second finger lifted
            /*matrix.set(savedMatrix);*/
            /*view.setScaleType(ImageView.ScaleType.CENTER);*/
            Log.v("/h/", ""+scale);

            mode = ZOOMOUT;

            //When release back to position
            matrix.set(savedMatrix);
            Log.d(TAG, "mode=ZOOMOUT");
            break;

        case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down

            oldDist = spacing(event);
            Log.d(TAG, "oldDist=" + oldDist);
            if (oldDist > 5f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
                Log.d(TAG, "mode=ZOOM");
            }
            break;

        case MotionEvent.ACTION_MOVE:

            if (mode == DRAG)
            {
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix  of points
            }
            else if (mode == ZOOM)
            {
                // pinch zooming
                float newDist = spacing(event);
                Log.d(TAG, "newDist=" + newDist);

                if (newDist > 5f)
                {
                    matrix.set(savedMatrix);
                    scale = newDist / oldDist; // setting the scaling of the
                    // matrix...if scale > 1 means
                    // zoom in...if scale < 1 means
                    // zoom out
                    if(scale>1) {
                        //Zoom In
                    }else if(scale<1) {
                        //Zoom Out
                    }

                    matrix.postScale(scale, scale, mid.x, mid.y);

                    Log.v("/h/", ""+scale+mode);

                }

            }

            break;

    }

    view.setImageMatrix(matrix); // display the transformation on screen

    return true; // indicate event was handled
}

/*
 * --------------------------------------------------------------------------
 * Method: spacing Parameters: MotionEvent Returns: float Description:
 * checks the spacing between the two fingers on touch
 * ----------------------------------------------------
 */

private float spacing(MotionEvent event)
{
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float) Math.sqrt(x * x + y * y);
}

/*
 * --------------------------------------------------------------------------
 * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
 * Description: calculates the midpoint between the two fingers
 * ------------------------------------------------------------
 */

private void midPoint(PointF point, MotionEvent event)
{
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}


问:
SELECT, FROM, INNER JOIN, WHERE function
I have two tables "users" and "emp_details". "users" are Branch mangers who have login id for monitoring their own branch's employees. "emp_details" includes employees working for different branches which include branch managers aslo.

when Branch manager ("users") log in it should fetch details from "emp_details" only if this particular "users" branch (code: location) match.

```<code>SELECT emp_details.emp_no, emp_name, designation, emp_details.location
 FROM emp_details
 INNER JOIN users
 WHERE users.location = emp_details.location
</code>```

used above code but showing data for all users created not as per the login-ed users location. Please help

答:
From your query it will give the output of all the data which have matching locations.
If you want to get the data which belong to the location of the specific user, you have to filter that user from the query. Otherwise query will output all the matching data.

```<code>    DECLARE @UserName AS Varchar(50)

    SELECT ed.emp_no, ed.emp_name, ed.designation,ed.location
    FROM emp_details ed
    INNER JOIN users u ON u= ed.location
    WHERE u.User_Name = @UserName
</code>```

Please note that above parameter can be user name or user ID or any relevant thing, but you have to pass that to the sql query.

Body:
I have two tables "users" and "emp_details". "users" are Branch mangers who have login id for monitoring their own branch's employees. "emp_details" includes employees working for different branches which include branch managers aslo.

when Branch manager ("users") log in it should fetch details from "emp_details" only if this particular "users" branch (code: location) match.

SELECT emp_details.emp_no, emp_name, designation, emp_details.location
 FROM emp_details
 INNER JOIN users
 WHERE users.location = emp_details.location

used above code but showing data for all users created not as per the login-ed users location. Please help

Body:
From your query it will give the output of all the data which have matching locations.
If you want to get the data which belong to the location of the specific user, you have to filter that user from the query. Otherwise query will output all the matching data.

    DECLARE @UserName AS Varchar(50)

    SELECT ed.emp_no, ed.emp_name, ed.designation,ed.location
    FROM emp_details ed
    INNER JOIN users u ON u= ed.location
    WHERE u.User_Name = @UserName

Please note that above parameter can be user name or user ID or any relevant thing, but you have to pass that to the sql query.


问:
Why does ToString format a number with the incorrect decimal separator
In my locale settings->numbers/currency, the decimal symbol is set to a period. Yet when I use the following in a Razor view:

```<code><td class="number-col">@Model.TendersReceived[i].Wq.ToString("N")</td>
</code>```

It renders the number with a comma as a decimal separator. The issue isn't with a different machine for the web server, because I use my dev PC's IIS. Or does IIS follow some other local settings?

答:
try this

@Model.TendersReceived[i].Wq.ToString("N2")

or

```<code><td class="number-col">string.Format("{0:0.00}", @Model.TendersReceived[i].Wq)</td>
</code>```

Body:
In my locale settings->numbers/currency, the decimal symbol is set to a period. Yet when I use the following in a Razor view:

@Model.TendersReceived[i].Wq.ToString("N")

It renders the number with a comma as a decimal separator. The issue isn't with a different machine for the web server, because I use my dev PC's IIS. Or does IIS follow some other local settings?

Body:
try this

@Model.TendersReceived[i].Wq.ToString("N2")

or

<td class="number-col">string.Format("{0:0.00}", @Model.TendersReceived[i].Wq)</td>


问:
Can you pre render an iframe in React so it is loaded when it is needed in the app?
In my case, I need to display a credit card form, and use an iframe to load the credit card field from CardConnect (a secure external site). The problem is that once I display that form in a modal, it takes about a half second to load that iframe. I would like to pre render/load the iframe so once it is ready to display, it looks like it loaded immediately.

I tried techniques from this link with no luck: https://hackernoon.com/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d

I also tried memoizing the iframe, rendering it in a hidden div earlier in the app and calling on it again, but also no luck, it's loaded twice.

答:
I'm not too familiar with CardConnect however, you should be able to preload an iframe by appending the following link element to the head of your document:

```<code><link rel="preload" href="https://cardconnect.com/iframe.html" as="document">
</code>```

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

Body:
I'm not too familiar with CardConnect however, you should be able to preload an iframe by appending the following link element to the head of your document:

<link rel="preload" href="https://cardconnect.com/iframe.html" as="document">

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content


问:
I have a problem with my Gradle. Cannot Resolve some Issues
Failed to resolve: com.android.support:appcompat-v7:25.1.0.

Failed to resolve: com.android.support:design:25.1.0.

Failed to resolve: com.android.support.test.espresso:espresso-core:2.2.2.

its and old app that im learning from it all over again

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.kaldeta.moviemania"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
I suggest to check repositories clause in your root build.gradle, there must be google reposity, like

```<code>repositories {
    google()
    jcenter()
    mavenCentral()
}
</code>```

Also check, if gradle is in offline mode Android Studio->Preferences->Gradle-Offline work checkbox

Body:
Failed to resolve: com.android.support:appcompat-v7:25.1.0.

Failed to resolve: com.android.support:design:25.1.0.

Failed to resolve: com.android.support.test.espresso:espresso-core:2.2.2.

its and old app that im learning from it all over again

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.kaldeta.moviemania"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    testCompile 'junit:junit:4.12'
}

Body:
I suggest to check repositories clause in your root build.gradle, there must be google reposity, like

repositories {
    google()
    jcenter()
    mavenCentral()
}

Also check, if gradle is in offline mode Android Studio->Preferences->Gradle-Offline work checkbox


问:
How to transform multiple view to same location(CGPoint)
I've got multiple UIImageViews, spread across in a view.

```<code>@IBOutlet var leftIVs: [UIImageView]!
@IBOutlet var topIVs: [UIImageView]!
@IBOutlet var rightIVs: [UIImageView]!
</code>```

I'm trying to create a function using UIView.animate... functions and 'transform' property which brings all of these UIImageViews at the center of the superview. I'm using the following code:

```<code>let performInitialTransformation: ((UIImageView)->()) = { (card) in
    let cardCenter = CGPoint(x: card.frame.midX, y: card.frame.midY)
    let viewCenter = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    let deltaPoint = cardCenter - viewCenter //also tried (viewCenter - cardCenter)
    UIView.animate(withDuration: 0.5, animations: {
        card.transform = CGAffineTransform.init(translationX: deltaPoint.x, y: deltaPoint.y)
    }) { (done) in
    }
}

for card in topIVs {
    performInitialTransformation(card)
}

for card in leftIVs {
    performInitialTransformation(card)
}

for card in rightIVs {
    performInitialTransformation(card)
}
</code>```

I'm using this static function:

```<code>extension CGPoint {
    static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        return CGPoint(x: rhs.x - lhs.x, y: rhs.y - lhs.y)
    }
}
</code>```

NOTE: Also, I will be bringing those images back to there original position afterward for which I will use CGAffineTransform.identity

The images are not being shown in the center. How can I achieve this? Thanks in advance!

答:
I think your problem was that you didn't reduce the size of the image view so that they stack at the exact centre of the screen.

```<code>let deltaX = (self.view.center.x - card.frame.minX) - card.frame.width/2
let deltaY = (self.view.center.y - card.frame.minY) - card.frame.height/2
UIView.animate(withDuration: 1) {
    card.transform = .init(translationX: deltaX, y: deltaY)
}
</code>```

Body:
I've got multiple UIImageViews, spread across in a view.

@IBOutlet var leftIVs: [UIImageView]!
@IBOutlet var topIVs: [UIImageView]!
@IBOutlet var rightIVs: [UIImageView]!

I'm trying to create a function using UIView.animate... functions and 'transform' property which brings all of these UIImageViews at the center of the superview. I'm using the following code:

let performInitialTransformation: ((UIImageView)->()) = { (card) in
    let cardCenter = CGPoint(x: card.frame.midX, y: card.frame.midY)
    let viewCenter = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    let deltaPoint = cardCenter - viewCenter //also tried (viewCenter - cardCenter)
    UIView.animate(withDuration: 0.5, animations: {
        card.transform = CGAffineTransform.init(translationX: deltaPoint.x, y: deltaPoint.y)
    }) { (done) in
    }
}

for card in topIVs {
    performInitialTransformation(card)
}

for card in leftIVs {
    performInitialTransformation(card)
}

for card in rightIVs {
    performInitialTransformation(card)
}

I'm using this static function:

extension CGPoint {
    static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        return CGPoint(x: rhs.x - lhs.x, y: rhs.y - lhs.y)
    }
}

NOTE: Also, I will be bringing those images back to there original position afterward for which I will use CGAffineTransform.identity

The images are not being shown in the center. How can I achieve this? Thanks in advance!

Body:
I think your problem was that you didn't reduce the size of the image view so that they stack at the exact centre of the screen.

let deltaX = (self.view.center.x - card.frame.minX) - card.frame.width/2
let deltaY = (self.view.center.y - card.frame.minY) - card.frame.height/2
UIView.animate(withDuration: 1) {
    card.transform = .init(translationX: deltaX, y: deltaY)
}


问:
'property' object cannot be intepreted as an integer
I discovered Python properties recently and I have been using it as a way to get 'read only' members, but now troubles arrive...

I have some 'read-only' numbers stored into properties inside a config class and I want to re-use those number in numpy/tensorflow, something a bit like:

class MyConfig:
    def __init__(self, val):
        self._val = val

    @property
    def val(self):
        return self._val

conf = MyConfig(10)
np.ones(conf.val)
```

<p>Error:</p>

```TypeError: expected sequence object with len >= 0 or a single integer
```

In my real code, the error is triggered by a np.reshape and the error message is a little different (TypeError: 'property' object cannot be interpreted as integer). I assume the cause for the error is the same as in this little example and only the error helper message differs.

Am I doing something wrong?
Can't properties be used in other functions for the values they embed?

答:
I agree with petronella. Code executes as expected on my iPhone in Pythonista </p>

```<code>>>> conf = MyConfig(10)
>>> type(conf.val)
<class 'int'>
>>> conf.val
10
>>> np.ones(conf.val)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
</code>```

Body:
I discovered Python properties recently and I have been using it as a way to get 'read only' members, but now troubles arrive...

I have some 'read-only' numbers stored into properties inside a config class and I want to re-use those number in numpy/tensorflow, something a bit like:

class MyConfig:
    def __init__(self, val):
        self._val = val

    @property
    def val(self):
        return self._val

conf = MyConfig(10)
np.ones(conf.val)

Error:

TypeError: expected sequence object with len >= 0 or a single integer

In my real code, the error is triggered by a np.reshape and the error message is a little different (TypeError: 'property' object cannot be interpreted as integer). I assume the cause for the error is the same as in this little example and only the error helper message differs.

Am I doing something wrong?
Can't properties be used in other functions for the values they embed?

Body:
I agree with petronella. Code executes as expected on my iPhone in Pythonista

>>> conf = MyConfig(10)
>>> type(conf.val)
<class 'int'>
>>> conf.val
10
>>> np.ones(conf.val)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])


问:
Flutter: SingleChildScrollView shrink-wrap its children along the vertical axis error
In Scaffold I have a container to set background . in container's child I have SingleChildScrollView and in its child, I have Column. In children of this widget I have 2 Expanded widget :

```<code>Scaffold
    |
     Container
        |
         SingleChildScrollView
            |
             * Expanded
             * Expanded
</code>```

This is code:

```<code> Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      resizeToAvoidBottomPadding: true,
      body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("images/main_background.png"),
              fit: BoxFit.cover,
            ),
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(..)
                Expanded(..)
</code>```

My problem is when on this page runs all the page has pink color means I got this error :

```<code>I/flutter ( 8893): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 8893): The following assertion was thrown during performLayout():
I/flutter ( 8893): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 8893): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 8893): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 8893): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 8893): space in the vertical direction.
I/flutter ( 8893): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 8893): cannot simultaneously expand to fit its parent.
I/flutter ( 8893): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 8893): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 8893): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 8893): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 8893): constraints provided by the parent.
I/flutter ( 8893): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 8893):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 8893):   http://api.flutter.dev/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 8893): The affected RenderFlex is:
I/flutter ( 8893):   RenderFlex#4b35c relayoutBoundary=up13 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE(creator: Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#fcff2] ← Semantics ← _PointerListener ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#e245d] ← _PointerListener ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#471e6] ← ⋯, parentData: <none> (can use size), constraints: BoxConstraints(0.0<=w<=320.0, 0.0<=h<=Infinity), size: MISSING, direction: vertical, mainAxisAlignment: start, mainAxisSize: max, crossAxisAlignment: center, verticalDirection: down)
I/flutter ( 8893): The creator information is set to:
I/flutter ( 8893):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#fcff2] ← Semantics ← .....
</code>```

What is the problem?

答:
The problem is that the two Expanded are expanding the Column and the SingleChildScrollView infinitely in the vertical axis. You have to constraint the height somewhere within the body.

It's not clear what you are trying to achieve here, but the most straightforward solutions would be to either remove the two Expanded or the SingleChildScrollView.

You might also want to use a ListView instead of SingleChildScrollView + Column.

Body:
In Scaffold I have a container to set background . in container's child I have SingleChildScrollView and in its child, I have Column. In children of this widget I have 2 Expanded widget :

Scaffold
    |
     Container
        |
         SingleChildScrollView
            |
             * Expanded
             * Expanded

This is code:

 Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      resizeToAvoidBottomPadding: true,
      body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("images/main_background.png"),
              fit: BoxFit.cover,
            ),
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(..)
                Expanded(..)

My problem is when on this page runs all the page has pink color means I got this error :

I/flutter ( 8893): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 8893): The following assertion was thrown during performLayout():
I/flutter ( 8893): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 8893): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 8893): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 8893): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 8893): space in the vertical direction.
I/flutter ( 8893): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 8893): cannot simultaneously expand to fit its parent.
I/flutter ( 8893): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 8893): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 8893): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 8893): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 8893): constraints provided by the parent.
I/flutter ( 8893): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 8893):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 8893):   http://api.flutter.dev/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 8893): The affected RenderFlex is:
I/flutter ( 8893):   RenderFlex#4b35c relayoutBoundary=up13 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE(creator: Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#fcff2] ← Semantics ← _PointerListener ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#e245d] ← _PointerListener ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#471e6] ← ⋯, parentData: <none> (can use size), constraints: BoxConstraints(0.0<=w<=320.0, 0.0<=h<=Infinity), size: MISSING, direction: vertical, mainAxisAlignment: start, mainAxisSize: max, crossAxisAlignment: center, verticalDirection: down)
I/flutter ( 8893): The creator information is set to:
I/flutter ( 8893):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#fcff2] ← Semantics ← .....

What is the problem?


问:
Minimize cost in R
I'd like to minimize the following function

```<code>cost=function(x){
  events=sum(x==1)
  rev = sum(df$rev[which(x==0)])*0.8

  costcomp1=tail(comp1$cost[which(comp1$Nevents<events)],1)

  costcomp2=tail(comp2$percentuale[which(comp2$k<=rev)],1)*rev+50000

  cost=costcomp1+costcomp2

  return(cost)
}
</code>```

x should be a binary vector, because for every item I want to choose the supplier to buy from

```<code>head(comp2)
        k percentuale
1  800000      0.0500
2 1800000      0.0325
3 88888888888888      0.0200

head(comp1)
       Nevents  cost
1         1500 13000
2         1750 17000
3         2000 21000
4         2500 22500
5         3000 26000
6         3500 29000
</code>```

I tried optimize(cost,x),x=sample(c(0,1),nrow(df),replace = T) but it doesn't work. It gives me the error invalid function value in 'optimize'

答:
I think what you need might be fminsearch

```<code>pracma::fminsearch
</code>```

and you can try

```<code>pracma::fminsearch(cost,rep(0,nrow(df)))$fmin
</code>```

Title: Minimize cost in R

Body:
I'd like to minimize the following function

cost=function(x){
  events=sum(x==1)
  rev = sum(df$rev[which(x==0)])*0.8

  costcomp1=tail(comp1$cost[which(comp1$Nevents<events)],1)

  costcomp2=tail(comp2$percentuale[which(comp2$k<=rev)],1)*rev+50000

  cost=costcomp1+costcomp2

  return(cost)
}

x should be a binary vector, because for every item I want to choose the supplier to buy from

head(comp2)
        k percentuale
1  800000      0.0500
2 1800000      0.0325
3 88888888888888      0.0200

head(comp1)
       Nevents  cost
1         1500 13000
2         1750 17000
3         2000 21000
4         2500 22500
5         3000 26000
6         3500 29000

I tried optimize(cost,x),x=sample(c(0,1),nrow(df),replace = T) but it doesn't work. It gives me the error invalid function value in 'optimize'

Body:
I think what you need might be fminsearch

pracma::fminsearch

and you can try

pracma::fminsearch(cost,rep(0,nrow(df)))$fmin


问:
Divide 2 columns into 4 based on odd and even
I want to divide 2 columns into 4 based on odd and even. I have a table

```<code>INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')
</code>```

I tried the following query:-

```<code>SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A
</code>```

Results I am getting from the query is:-

But I want the result in following format:-

```<code>DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1
</code>```

答:
you can also try this:</p>

```<code>create table #tab(id int,test varchar(40),des varchar(40))

INSERT INTO #tab
VALUES (1,'test', 'desc'), (2,'test1', 'desc1'), (3,'test2', 'desc2'),
   (4,'test3', 'desc3'), (5,'test4', 'desc4')
select * from #tab

with cte as
(select ROW_NUMBER()OVER(ORDER BY a.TestODD) row_num,*
    from (select(case when id in (1,3,5)  then '0' else test end) TestODD from #tab) a
    where a.TestODD!='0'),
cte2 as (
select ROW_NUMBER() OVER(ORDER BY b.TestEven)row_num,*
   from (select(case when id in(2,4)then '0' else test end)TestEven from #tab)b
   where b.TestEven!='0'
 ),
 cte3 as (
 select ROW_NUMBER()OVER(ORDER BY  c.desODD) row_num,*
   from (select (case when id in (1,3,5)then '0' else des end) desODD from #tab)c
   where c.desODD!='0'
 ),
 cte4 as (
 select ROW_NUMBER()OVER(ORDER BY d.destEven)row_num,*
   from (select(case when id in (2,4)then '0' else des end)destEven from #tab) d
   where d.destEven!='0'
 )
  select TestEven,TestODD,destEven,desODD from cte2
       left join cte on cte.row_num=cte2.row_num
      left join cte3 on cte2.row_num=cte3.row_num
      left join cte4 on cte2.row_num=cte4.row_num
</code>```

Body:
I want to divide 2 columns into 4 based on odd and even. I have a table

INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')

I tried the following query:-

SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A

Results I am getting from the query is:-

But I want the result in following format:-

DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1

Body:
you can also try this:

create table #tab(id int,test varchar(40),des varchar(40))

INSERT INTO #tab
VALUES (1,'test', 'desc'), (2,'test1', 'desc1'), (3,'test2', 'desc2'),
   (4,'test3', 'desc3'), (5,'test4', 'desc4')
select * from #tab

with cte as
(select ROW_NUMBER()OVER(ORDER BY a.TestODD) row_num,*
    from (select(case when id in (1,3,5)  then '0' else test end) TestODD from #tab) a
    where a.TestODD!='0'),
cte2 as (
select ROW_NUMBER() OVER(ORDER BY b.TestEven)row_num,*
   from (select(case when id in(2,4)then '0' else test end)TestEven from #tab)b
   where b.TestEven!='0'
 ),
 cte3 as (
 select ROW_NUMBER()OVER(ORDER BY  c.desODD) row_num,*
   from (select (case when id in (1,3,5)then '0' else des end) desODD from #tab)c
   where c.desODD!='0'
 ),
 cte4 as (
 select ROW_NUMBER()OVER(ORDER BY d.destEven)row_num,*
   from (select(case when id in (2,4)then '0' else des end)destEven from #tab) d
   where d.destEven!='0'
 )
  select TestEven,TestODD,destEven,desODD from cte2
       left join cte on cte.row_num=cte2.row_num
      left join cte3 on cte2.row_num=cte3.row_num
      left join cte4 on cte2.row_num=cte4.row_num


问:
Delete duplicate rows with an order by
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

```<code>;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1
</code>```

and this is the output:

how to delete duplicate rows and show the output like this:

答:
You missed ID in the partition Order by. This produces what you want as you are always deleting the 2nd , 3rd .. duplicate. Anchor your query on the first instance as below.

```<code>SELECT
ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY ID, STATUSIN) AS RowNumber,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH
</code>```

I would also mention that you should probably strengthen how you are partitioning. What happens if you get multiple customer records with the exact same time stamp? EG is NIP + Name unique? Added name to the below example.

```<code>SELECT
ROW_NUMBER()OVER(PARTITION BY Name,STATUSIN ORDER BY Name, STATUSIN) AS RowNumber,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH
</code>```

Solution for your query

```<code>;WITH CTE AS
(
  SELECT
ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY ID, STATUSIN) AS RowNumber
,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

    SELECT * FROM #DAILYDATAWH
</code>```

Title: Delete duplicate rows with an order by

Body:
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

and this is the output:

how to delete duplicate rows and show the output like this:

Body:
You missed ID in the partition Order by. This produces what you want as you are always deleting the 2nd , 3rd .. duplicate. Anchor your query on the first instance as below.

SELECT
ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY ID, STATUSIN) AS RowNumber,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH

I would also mention that you should probably strengthen how you are partitioning. What happens if you get multiple customer records with the exact same time stamp? EG is NIP + Name unique? Added name to the below example.

SELECT
ROW_NUMBER()OVER(PARTITION BY Name,STATUSIN ORDER BY Name, STATUSIN) AS RowNumber,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH

Solution for your query

;WITH CTE AS
(
  SELECT
ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY ID, STATUSIN) AS RowNumber
,
ID, NIP, Name,DEPARTMENT,STATUSIN,STATUSOUT FROM #DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

    SELECT * FROM #DAILYDATAWH


问:
Problem with Fatal error: Call to Undefined function filter_var()
I have an error: "Fatal error: Call to undefined function filter_var() in /home/example/public_html/register.php on line 17"

My script is like this. And I would like to seek advice as to what the problem is? My PHP version on cPanel is currently set to 5.5.

```<code><?php

session_start();
include('config.php');

function validate($post)
{
    if ($post->email == "") return "Email field is required.";
    if ($post->name == "") return "Name field is required.";
    if ($post->password == "") return "Password field is required.";

    if ($_SESSION['captcha'] != $post->captcha) return "Captcha incorrect, please try again.";//this is Line 16
    if (!filter_var($post->email, FILTER_VALIDATE_EMAIL)) return "That email address is invalid.";//this is Line 17

    return false;
}

?>
</code>```

答:
replace filter_var with \filter_var

```<code>if (!\filter_var($post->email, FILTER_VALIDATE_EMAIL)) return "That email address is invalid.";
</code>```

Body:
I have an error: "Fatal error: Call to undefined function filter_var() in /home/example/public_html/register.php on line 17"

My script is like this. And I would like to seek advice as to what the problem is? My PHP version on cPanel is currently set to 5.5.

<?php

session_start();
include('config.php');

function validate($post)
{
    if ($post->email == "") return "Email field is required.";
    if ($post->name == "") return "Name field is required.";
    if ($post->password == "") return "Password field is required.";

    if ($_SESSION['captcha'] != $post->captcha) return "Captcha incorrect, please try again.";//this is Line 16
    if (!filter_var($post->email, FILTER_VALIDATE_EMAIL)) return "That email address is invalid.";//this is Line 17

    return false;
}

?>

Body:
replace filter_var with \filter_var

if (!\filter_var($post->email, FILTER_VALIDATE_EMAIL)) return "That email address is invalid.";


问:
Construct AWS cost APi for getting total monthly costs or total daily usage for my account
i want to create/consume API for getting AWS cost daily and monthly details.
want to know how i can create api and check in the postman for getting cost details for my account.</p>

答: You will need to enable  cost explorer on your AWS account. Once you're done you can use AWS SDK to fetch cost results.</p>


问:
CSS: Make image fit the proper area with the absolutely positioned label on the picture
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
  <span class="label">Label</span>
</div></code>```

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

答:
You should try to use background-image instead of a single image

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-size: contain;
  background-repeat: no-repeat;
  position: absolute;
  top: 10%;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="img" style="background-image:url(https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80)" alt="">
  <span class="label">Label</span>
  </div>
</div></code>```

Body:
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

  Label

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

Body:
You should try to use background-image instead of a single image

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-size: contain;
  background-repeat: no-repeat;
  position: absolute;
  top: 10%;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

<div class="wrapper">
  <div class="img" style="background-image:url(https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80)" alt="">
  <span class="label">Label</span>
  </div>
</div>


问:
Big Query Data Expiration
I have been collecting data in BigQuery for analysis purposes. However, the size of the data is growing and I only need 2 weeks of recent data. I wanted to erase data that is not used. I did some research and I found out that there is an expiration option for partitioned data.

Current setup:

My table is a partitioned table
I use a Lambda Function with a code similar to this in order to put data into the table (I have tried adding timePartitioning option, but it didn't work so that's why I am asking on stackoverflow if anyone knows)

```<code>wait bq
      .dataset("dataset name")
      .table('tablename' + '$' + partitionTime)
      .load( filename, {
        sourceFormat: 'CSV',
        schema,
        skipLeadingRows: 1,
        timePartitioning: {
           expirationMs: "300000"
        }
      });
</code>```

Where partitionTime is in the format YYYYMMDD (this places the data inserted into that partition)

Thank you for all your comments and taking time to read my trouble :)
Have a nice day.

答:
As you can see here, the function load accepts three parameters:

source (needed)

metadata (optional)

callback (optional)

The options that you need can be set in the metadata parameter. In the link provided above you can also notice that the BigQuery SDK uses API calls to perform the given operations.
In this link and in the printscreen bellow, you can see how to build a correct API call for BigQuery

In the field timePartitioning you can add DAY as your tipe of partitioning and your expiration time in miliseconds.

In the end, your code would have a small change:

```<code> wait bq
      .dataset("dataset name")
      .table('tablename')
      .load( filename, {
        sourceFormat: 'CSV',
        schema,
        skipLeadingRows: 1,
        timePartitioning: {
           type: "DAY",
           expirationMs: "300000"
        }
      });
</code>```

I hope it helps

Title: Big Query Data Expiration

Body:
I have been collecting data in BigQuery for analysis purposes. However, the size of the data is growing and I only need 2 weeks of recent data. I wanted to erase data that is not used. I did some research and I found out that there is an expiration option for partitioned data.

Current setup:

My table is a partitioned table
I use a Lambda Function with a code similar to this in order to put data into the table (I have tried adding timePartitioning option, but it didn't work so that's why I am asking on stackoverflow if anyone knows)

wait bq
      .dataset("dataset name")
      .table('tablename' + '$' + partitionTime)
      .load( filename, {
        sourceFormat: 'CSV',
        schema,
        skipLeadingRows: 1,
        timePartitioning: {
           expirationMs: "300000"
        }
      });

Where partitionTime is in the format YYYYMMDD (this places the data inserted into that partition)

Thank you for all your comments and taking time to read my trouble :)
Have a nice day.

Body:
As you can see here, the function load accepts three parameters:

source (needed)

metadata (optional)

callback (optional)

The options that you need can be set in the metadata parameter. In the link provided above you can also notice that the BigQuery SDK uses API calls to perform the given operations.
In this link and in the printscreen bellow, you can see how to build a correct API call for BigQuery

In the field timePartitioning you can add DAY as your tipe of partitioning and your expiration time in miliseconds.

In the end, your code would have a small change:

 wait bq
      .dataset("dataset name")
      .table('tablename')
      .load( filename, {
        sourceFormat: 'CSV',
        schema,
        skipLeadingRows: 1,
        timePartitioning: {
           type: "DAY",
           expirationMs: "300000"
        }
      });

I hope it helps


问:
Override footer/header section
I was trying to modify footer section with outlets by defining:

```<code><ng-container *ngIf="templateName$ | async">
        <ng-template *ngIf="true" cxOutletRef="footer">
        </ng-template>
</ng-container>
</code>```

and footer section is not replaced. Is it possible to replace footer/header for specific templates?
As a result of this code, templateName is properly resolved from PageLayoutService, but it replacing does not work.
Also tried

```<code><ng-container *ngIf="(templateName$ | async) === expectedTemplateName">
        <ng-template cxOutletRef="footer">
        </ng-template>
</ng-container>
</code>```

but still no luck.
Any hints? It would be great to modify/change header as well, Thanks!

答:
There are various ways to customise the header/footer of a page:

Implement the customisation in the CMS, where you can setup different page templates for different pages, including an alternative header/footer. This approach would align best with how Spartacus is build, as the pages are data driven and component mapping is done in a generic way. You don't need to touch the spartacus code to get different headers and footers.

Use outlets as you tried already. The issue you're facing is that at the time that the page template is resolved, the footer is already rendered and the registered outlet will not make a difference. I can imagine this is a bit confusing in how outlets work. I've created a quick example on Stackblitz for a conditional footer using outlets.

Implement a custom root component (replacing cx-storefront) and implement the footer in a custom way. You can leverage the page-layout and page-slot component to render CMS content.

Hope that gives you and idea or two.

Here's a bit more info on page template driven classes for page specific styling. Given that the header/footer do not benefit from the page template based class (as it's only available inside the router outlet), you could implement this in your app, I've updated the Stackblitz example for you with an example.

Title: Override footer/header section

Body:
I was trying to modify footer section with outlets by defining:

<ng-container *ngIf="templateName$ | async">
        <ng-template *ngIf="true" cxOutletRef="footer">
        </ng-template>
</ng-container>

and footer section is not replaced. Is it possible to replace footer/header for specific templates?
As a result of this code, templateName is properly resolved from PageLayoutService, but it replacing does not work.
Also tried

<ng-container *ngIf="(templateName$ | async) === expectedTemplateName">
        <ng-template cxOutletRef="footer">
        </ng-template>
</ng-container>

but still no luck.
Any hints? It would be great to modify/change header as well, Thanks!


问:
Standard deviation MPG

I am getting an error column 'mpg' unknown? I am trying to calculate the stdev of the mpg, a computed column

```<code>SELECT Date, Vehicle, Quantity as [Ltrs],
    LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage,
    OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles],
    (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG],
    case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10
        then 1 else 0 end as [Anomaly],
    stdev(MPG)
FROM [Fleet].[DwhTriscanChargeouts]
where vehicle='DE63VAM'
order by 2, 1
</code>```

答:
The reason that you're getting this error is that you're trying to calculate STD (MPG)  before the actual value is calculated (possibly).

I suggest you use an inner query calculating the column, then calculating the STD. Inner queries are calculated before upper select clause, which is calculated last in the query.

Don't forget using GROUP BY clause since STD is an aggregation function.

Title: Standard deviation MPG

Body:
I am getting an error column 'mpg' unknown? I am trying to calculate the stdev of the mpg, a computed column

SELECT Date, Vehicle, Quantity as [Ltrs],
    LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage,
    OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles],
    (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG],
    case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10
        then 1 else 0 end as [Anomaly],
    stdev(MPG)
FROM [Fleet].[DwhTriscanChargeouts]
where vehicle='DE63VAM'
order by 2, 1


问:
How to disable "Save To Files" in iOS 11?
I have an iOS app which creates a PDF and is shared using the UIActivityViewController using the default share functionality. I had to block a few sharing facilities like Vimeo, Facebook, Twillio, etc. and also the file should not be stored on the device.

With the new iOS 11 version, Apple has provided SaveToFiles option with the default share functionality. I tried using excludedActivityTypes, and with blocking the "com.apple.CloudDocsUI.AddToiCloudDrive" option, but no success.

Can anyone help me to disable the SaveToFile option though Swift? I am using Xcode 9.3 and Swift 4.

答:
Currently, we probably cannot disable Save to Files or Add to Shared Album by add excludedActivityTypes in activityViewController. But we can prevent when user did press two activity types will do not perform action instead we'll showing alert.

First we create custom UIActivityItemProvider

class ActivityItemProvider: UIActivityItemProvider {
  override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
    // in here we'll check activityType = "com.apple.CloudDocsUI.AddToiCloudDrive" (Save to Files),
    // activityType = "com.apple.mobileslideshow.StreamShareService" (Shared Album)
    if(activityType.rawValue.contains("com.apple.CloudDocsUI.AddToiCloudDrive") || (activityType.rawValue.contains("com.apple.mobileslideshow.StreamShareService") {
      // dismiss activityViewController first
      activityViewController.dismiss(animated: true, completion: nil)
      // show alert controller, we can using UIApplication.shared.keyWindow?.rootViewController to present alert
      return nil
    }
    return self.placeholderItem
}

```

<p>In where we call <code>UIActivityController</code>, let's using</p>

<pre class="lang-swift prettyprint-override"><code>let item = ActivityItemProvider.init(placeholderItem: {your item})
let activityViewController = UIActivityViewController.init(activityItems: item, applicationActivities: nil)
</code>```

ObjectiveC version

```<code>#import "BRActivityItemProvider.h"
#import "UIViewController+Additions.h"
@implementation BRActivityItemProvider

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(UIActivityType)activityType {
  [super activityViewController:activityViewController itemForActivityType:activityType];
  NSLog(@"itemForActivityType %@", activityType);
  if([activityType containsString:@"com.apple.CloudDocsUI.AddToiCloudDrive"] || [activityType containsString:@"com.apple.mobileslideshow.StreamShareService"]) {
    [activityViewController dismissViewControllerAnimated:true completion:^{
      UIViewController *rootController = [UIApplication sharedApplication].keyWindow.rootViewController;
      if(rootController != nil) {
        NSString *str = [activityType containsString:@"com.apple.CloudDocsUI.AddToiCloudDrive"]
        ? @"Cannot save file to iCloud Driver"
        : @"Cannot save file to Shared Album";
        dispatch_async(dispatch_get_main_queue(), ^{
// this's my custom show alert controller, you can change your own
          [rootController showAlertController:str action:^(UIAlertAction * _Nonnull action) {
          }];
        });
      }
    }];
    return nil;
  }
  return self.placeholderItem;
}

</code>```

In where call UIActivityViewController

```<code>BRActivityItemProvider *itemProvider = [[BRActivityItemProvider alloc]initWithPlaceholderItem:item];
    UIActivityViewController *activityController = [[UIActivityViewController alloc]initWithActivityItems:itemProvider applicationActivities:nil];
    activityController.popoverPresentationController.sourceView = controller.view;
// your logic code
// ....
</code>```

Body:
Currently, we probably cannot disable Save to Files or Add to Shared Album by add excludedActivityTypes in activityViewController. But we can prevent when user did press two activity types will do not perform action instead we'll showing alert.

First we create custom UIActivityItemProvider

class ActivityItemProvider: UIActivityItemProvider {
  override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
    // in here we'll check activityType = "com.apple.CloudDocsUI.AddToiCloudDrive" (Save to Files),
    // activityType = "com.apple.mobileslideshow.StreamShareService" (Shared Album)
    if(activityType.rawValue.contains("com.apple.CloudDocsUI.AddToiCloudDrive") || (activityType.rawValue.contains("com.apple.mobileslideshow.StreamShareService") {
      // dismiss activityViewController first
      activityViewController.dismiss(animated: true, completion: nil)
      // show alert controller, we can using UIApplication.shared.keyWindow?.rootViewController to present alert
      return nil
    }
    return self.placeholderItem
}

In where we call UIActivityController, let's using

let item = ActivityItemProvider.init(placeholderItem: {your item})
let activityViewController = UIActivityViewController.init(activityItems: item, applicationActivities: nil)

ObjectiveC version

#import "BRActivityItemProvider.h"
#import "UIViewController+Additions.h"
@implementation BRActivityItemProvider

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(UIActivityType)activityType {
  [super activityViewController:activityViewController itemForActivityType:activityType];
  NSLog(@"itemForActivityType %@", activityType);
  if([activityType containsString:@"com.apple.CloudDocsUI.AddToiCloudDrive"] || [activityType containsString:@"com.apple.mobileslideshow.StreamShareService"]) {
    [activityViewController dismissViewControllerAnimated:true completion:^{
      UIViewController *rootController = [UIApplication sharedApplication].keyWindow.rootViewController;
      if(rootController != nil) {
        NSString *str = [activityType containsString:@"com.apple.CloudDocsUI.AddToiCloudDrive"]
        ? @"Cannot save file to iCloud Driver"
        : @"Cannot save file to Shared Album";
        dispatch_async(dispatch_get_main_queue(), ^{
// this's my custom show alert controller, you can change your own
          [rootController showAlertController:str action:^(UIAlertAction * _Nonnull action) {
          }];
        });
      }
    }];
    return nil;
  }
  return self.placeholderItem;
}

In where call UIActivityViewController

BRActivityItemProvider *itemProvider = [[BRActivityItemProvider alloc]initWithPlaceholderItem:item];
    UIActivityViewController *activityController = [[UIActivityViewController alloc]initWithActivityItems:itemProvider applicationActivities:nil];
    activityController.popoverPresentationController.sourceView = controller.view;
// your logic code
// ....


问:
Stop people uploading malicious PHP files via forms
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

```<code>function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}
</code>```

Thanks, Ben.

答:
If you set php to only parse files ending with .php, then you can just rename a file from somename.php to somename.php.jpeg and you are safe.

If you really want to delete the files, there is a zip library available to php. You could use it to check the names and extensions of all the files inside the zip archive uploaded, and if it contains a php file, give the user an error message.

OwnerDisplayName: Ben McRae

Body:
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}

Thanks, Ben.

LastEditorDisplayName: gs

OwnerDisplayName: Marius

ContentLicense: CC BY-SA 2.5


问:
Why is there no decent sql parser?
I'm currently doing some oracle sql analysis and often encounter valid sql statement that can not be properly parsed by various sql parsers. Either they fail parsing it, or their abstract syntax tree generated is somehow messed up. It seems that the only parser that can really handle oracle sql is their own one that is not publicly available and cannot be obtained as a stand-alone parser.

I'm aware that there are different sql grammars and complying to all may not be possible.
But even parsers that claim to be Oracle SQL parsers do not succeed in all cases.

What do you think are the main reasons that make it hard to implement sql parsers in general or oracle sql parsers in particular?

Best,
Will

答:
Metadata.

```<code>SELECT identifier_1.identifier_2 FROM table
</code>```

could mean identifier_1 is a schema or a package, and identifier_2 might be a function or synonym to a function.

There's a whole bunch of reasons why a statement might be correct but can't be understood without the metadata about the database objects. Given those limitations, there's a limit to how far a parser can go.

If a parser can work out 80% of your code, and 15% can't be worked out without the metadata, there's diminishing returns in stretching the parser to cope with the missing "5%".

Title: Why is there no decent sql parser?

Body:
Metadata.

SELECT identifier_1.identifier_2 FROM table

could mean identifier_1 is a schema or a package, and identifier_2 might be a function or synonym to a function.

There's a whole bunch of reasons why a statement might be correct but can't be understood without the metadata about the database objects. Given those limitations, there's a limit to how far a parser can go.

If a parser can work out 80% of your code, and 15% can't be worked out without the metadata, there's diminishing returns in stretching the parser to cope with the missing "5%".


问:
Run first request multiple times and other request single time in a single thread
I Have 5 HTTP request in single thread, I want to run first request multiple times and then other request only single time

I can't use multiple thread as all request are depends on each other.

答:
Depending on what you're trying to achieve:

Put the request which needs to be run only once under Once Only Controller, this way the Sampler will be executed only during first iteration of the Thread Group

If you want more complex/flexible criteria - put the request which needs to be executed only once under the If Controller, this way you will be able to specify whatever criteria you want. For example if you want to run a Sampler only during 5th iteration use the following condition:

```<code>${__jexl3("${__jm__Thread Group__idx}" == "5",)}
</code>```

this way the sampler(s) which is (are) under the If Controller will be executed only if the condition is met:

Body:
Depending on what you're trying to achieve:

Put the request which needs to be run only once under Once Only Controller, this way the Sampler will be executed only during first iteration of the Thread Group

If you want more complex/flexible criteria - put the request which needs to be executed only once under the If Controller, this way you will be able to specify whatever criteria you want. For example if you want to run a Sampler only during 5th iteration use the following condition:

${__jexl3("${__jm__Thread Group__idx}" == "5",)}

this way the sampler(s) which is (are) under the If Controller will be executed only if the condition is met:


问:
Python - How do I do conditional counting of rows based on various columns?
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

```<code>A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4
</code>```

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

答:
I was able to get the required output based on the logic provided by @Umesh Sharma.

From the original dataframe, df, I created a dataframe without any of the F rows.

```<code>df_no_F = df[df['Type'] != "F"]
</code>```

I then use groupby and count to determine the number of rows for each
Sample and Date combination.

```<code>df_count = df_no_F.groupby(['Sample' , 'Date'], as_index=False).count()
</code>```

Body:
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

Body:
I was able to get the required output based on the logic provided by @Umesh Sharma.

From the original dataframe, df, I created a dataframe without any of the F rows.

df_no_F = df[df['Type'] != "F"]

I then use groupby and count to determine the number of rows for each
Sample and Date combination.

df_count = df_no_F.groupby(['Sample' , 'Date'], as_index=False).count()