问:
Error getting salesOrder in Netsuite while getting a record
Unable to get single NetSuite salesOrder, Generating below error

```<code>Getting Sales Order record
Error
[
  {
    '$attributes': { type: 'ERROR' },
    code: 'INVALID_TRANS_TYP',
    message: 'Transaction type specified is incorrect.'
  }
]
{
  "readResponse": {
    "status": {
      "$attributes": {
        "isSuccess": "false"
      },
      "statusDetail": [
        {
          "$attributes": {
            "type": "ERROR"
          },
          "code": "INVALID_TRANS_TYP",
          "message": "Transaction type specified is incorrect."
        }
      ]
    }
  }
}
Last Request:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:tns="urn:platform_2014_2.webservices.netsuite.com" xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns:platformFaults="urn:faults_2014_2.platform.webservices.netsuite.com" xmlns:platformCore="urn:core_2014_2.platform.webservices.netsuite.com" xmlns:platformCommon="urn:common_2014_2.platform.webservices.netsuite.com" xmlns:listRel="urn:relationships_2014_2sales.transactions.webservices.netsuite.com" xmlns:tranSales="urn:sales_2014_2.transactions.webservices.netsuite.com" xmlns:actSched="urn:scheduling_2014_2.activities.webservices.netsuite.com" xmlns:setupCustom="urn:customization_2014_2.setup.webservices.netsuite.com" xmlns:listAcct="urn:accounting_2014_2.lists.webservices.netsuite.com" xmlns:tranBank="urn:bank_2014_2.transactions.webservices.netsuite.com" xmlns:tranCust="urn:customers_2014_2.transactions.webservices.netsuite.com" xmlns:tranInvt="urn:inventory_2014_2.transactions.webservices.netsuite.com" xmlns:listSupport="urn:support_2014_2.lists.webservices.netsuite.com" xmlns:tranGeneral="urn:general_2014_2.transactions.webservices.netsuite.com" xmlns:listMkt="urn:marketing_2014_2.lists.webservices.netsuite.com" xmlns:listWebsite="urn:website_2014_2.lists.webservices.netsuite.com" xmlns:fileCabinet="urn:filecabinet_2014_2.documents.webservices.netsuite.com" xmlns:listEmp="urn:employees_2014_2.lists.webservices.netsuite.com"><soap:Header><platformMsgs:passport><platformCore:email>darshan.sanandiya@techholding.co</platformCore:email><platformCore:password>techh@123#</platformCore:password><platformCore:account>5022995_SB1</platformCore:account><platformCore:role internalId="3"></platformCore:role></platformMsgs:passport></soap:Header><soap:Body><platformMsgs:get xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns="urn:messages_2014_2.platform.webservices.netsuite.com"><platformMsgs:baseRef type="salesOrder" xsi:type="platformCore:RecordRef" internalId="106095" externalId="106095"></platformMsgs:baseRef></platformMsgs:get></soap:Body></soap:Envelope>
</code>```

All I want to fetch single order with internalId, But in return, it throws INVALID transction type error;
I am using npm soap; and netsuite sdk with nodejs

```<code>'use strict';

var denodeify = require('denodeify');
var NetSuite = require('../');

var credentials = require('../example/credentials.json');
var config = new NetSuite.Configuration(credentials);
var service = new NetSuite.Service(config);

console.log('Creating NetSuite connection');
console.log(service,"Service<<<")
service
  .init()
  .then(function( /*client*/ ) {
    console.log('WSDL processed. Service description:');
    console.log(service.config.client.describe());

    var recordRef = new NetSuite.Records.RecordRef();
    recordRef.internalId = "106095";
    recordRef.type = 'salesOrder';

    console.log('Getting Sales Order record');
    return service.get(recordRef);
  })
  .then(function(result, raw, soapHeader) {
    if (result.readResponse.status.$attributes.isSuccess !== 'true') {
      console.error('Error');
      console.error(result.readResponse.status.statusDetail);
    }
    console.log(JSON.stringify(result, null, 2));
    console.log('Last Request:');
    console.log(service.config.client.lastRequest);
  })
  .catch(function(err) {
    console.error(err);
    console.error('Last Request:');
    console.error(service.config.client.lastRequest);
  });
</code>```

Above is the code I am executing to get salesOrder;

答:
Believe the Record Type you want is SalesOrder, not salesOrder.

Reference: https://system.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2019_2/schema/record/salesorder.html

Body:
Unable to get single NetSuite salesOrder, Generating below error

Getting Sales Order record
Error
[
  {
    '$attributes': { type: 'ERROR' },
    code: 'INVALID_TRANS_TYP',
    message: 'Transaction type specified is incorrect.'
  }
]
{
  "readResponse": {
    "status": {
      "$attributes": {
        "isSuccess": "false"
      },
      "statusDetail": [
        {
          "$attributes": {
            "type": "ERROR"
          },
          "code": "INVALID_TRANS_TYP",
          "message": "Transaction type specified is incorrect."
        }
      ]
    }
  }
}
Last Request:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:tns="urn:platform_2014_2.webservices.netsuite.com" xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns:platformFaults="urn:faults_2014_2.platform.webservices.netsuite.com" xmlns:platformCore="urn:core_2014_2.platform.webservices.netsuite.com" xmlns:platformCommon="urn:common_2014_2.platform.webservices.netsuite.com" xmlns:listRel="urn:relationships_2014_2sales.transactions.webservices.netsuite.com" xmlns:tranSales="urn:sales_2014_2.transactions.webservices.netsuite.com" xmlns:actSched="urn:scheduling_2014_2.activities.webservices.netsuite.com" xmlns:setupCustom="urn:customization_2014_2.setup.webservices.netsuite.com" xmlns:listAcct="urn:accounting_2014_2.lists.webservices.netsuite.com" xmlns:tranBank="urn:bank_2014_2.transactions.webservices.netsuite.com" xmlns:tranCust="urn:customers_2014_2.transactions.webservices.netsuite.com" xmlns:tranInvt="urn:inventory_2014_2.transactions.webservices.netsuite.com" xmlns:listSupport="urn:support_2014_2.lists.webservices.netsuite.com" xmlns:tranGeneral="urn:general_2014_2.transactions.webservices.netsuite.com" xmlns:listMkt="urn:marketing_2014_2.lists.webservices.netsuite.com" xmlns:listWebsite="urn:website_2014_2.lists.webservices.netsuite.com" xmlns:fileCabinet="urn:filecabinet_2014_2.documents.webservices.netsuite.com" xmlns:listEmp="urn:employees_2014_2.lists.webservices.netsuite.com"><soap:Header><platformMsgs:passport><platformCore:email>darshan.sanandiya@techholding.co</platformCore:email><platformCore:password>techh@123#</platformCore:password><platformCore:account>5022995_SB1</platformCore:account><platformCore:role internalId="3"></platformCore:role></platformMsgs:passport></soap:Header><soap:Body><platformMsgs:get xmlns:platformMsgs="urn:messages_2014_2.platform.webservices.netsuite.com" xmlns="urn:messages_2014_2.platform.webservices.netsuite.com"><platformMsgs:baseRef type="salesOrder" xsi:type="platformCore:RecordRef" internalId="106095" externalId="106095"></platformMsgs:baseRef></platformMsgs:get></soap:Body></soap:Envelope>

All I want to fetch single order with internalId, But in return, it throws INVALID transction type error;
I am using npm soap; and netsuite sdk with nodejs

'use strict';

var denodeify = require('denodeify');
var NetSuite = require('../');

var credentials = require('../example/credentials.json');
var config = new NetSuite.Configuration(credentials);
var service = new NetSuite.Service(config);

console.log('Creating NetSuite connection');
console.log(service,"Service<<<")
service
  .init()
  .then(function( /*client*/ ) {
    console.log('WSDL processed. Service description:');
    console.log(service.config.client.describe());

    var recordRef = new NetSuite.Records.RecordRef();
    recordRef.internalId = "106095";
    recordRef.type = 'salesOrder';

    console.log('Getting Sales Order record');
    return service.get(recordRef);
  })
  .then(function(result, raw, soapHeader) {
    if (result.readResponse.status.$attributes.isSuccess !== 'true') {
      console.error('Error');
      console.error(result.readResponse.status.statusDetail);
    }
    console.log(JSON.stringify(result, null, 2));
    console.log('Last Request:');
    console.log(service.config.client.lastRequest);
  })
  .catch(function(err) {
    console.error(err);
    console.error('Last Request:');
    console.error(service.config.client.lastRequest);
  });

Above is the code I am executing to get salesOrder;


来源: stackexchange

问:
CRTP Singleton Incomplete type or Non-literal type
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

```<code>template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}
</code>```

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

```<code> . . .
 private:
   static constexpr Impl impl{};
 };
</code>```

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

答:
Try implementing your getInstance function in this way:

template <class Impl>
inline const Impl& Base<Impl>::getInstance() {
    static const Impl impl{};
    return impl;
}
```

<p>and then in <code>foo</code> function</p>

<pre class="lang-cpp prettyprint-override"><code>template <class Impl>
inline int Base<Impl>::foo(int x) {
    return getInstance().foo_impl(x);
}
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

 . . .
 private:
   static constexpr Impl impl{};
 };

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

Body:
Try implementing your getInstance function in this way:

template <class Impl>
inline const Impl& Base<Impl>::getInstance() {
    static const Impl impl{};
    return impl;
}

and then in foo function

template <class Impl>
inline int Base<Impl>::foo(int x) {
    return getInstance().foo_impl(x);
}

<a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJNJb0AGTy1MAOWMAjTMTO8ADqgWF1tPYYmgl4%2BanQ2do5GLm6SAAyKypiqfgwEzMQEAcam5koqYbRpGQQRDs6u7orpmdlBnNUlZVExZnEAlIqoBsTIHADkUgDMtsiGWADU4kM66goExJjMRtPY4nEAgusbY8wKChMAIq54AG6Y6JzTspvbBJhGHsL30zq7%2BxMAko%2Bsq9vvB2ke0w23EAHYbhsPAYnKw8MgQNsJhN5sw1MgJmhaPMvj8pAA2CbATAET7Y9K0PoQdrXJEo9Loia2AgTGioCDMiYADxpQ0hHmIZzRHDpAHpRajGVicd8nky8RDwYdabcwcq%2BXcHk9ha8AbinqsmbQ4XZ/nQZXjJISgUpXrLfkNsCAQMTSeSRFSaarIcjkZL4ZjzSz7fKDYq1SqNr6JosCD1aKGHZClZqfjqZnr7YbbCaQZtOTaQTMs47nWyOfRuV6torNsjY/GiSSyajKZhqQA6NkAfTwPwgPMjKdumz1x0F50uExAE2hsIDhde47OFyujtBtahMLhCLpnJ7faeFZZPMD5KHEY1%2Bcry8nnDLqFQvf7nNP0oIG59MZJja5UxkExDBeyojhsnJGMwtjHhMGTAMgpCYggGQAFTITBxDAKc1bgl%2B75HCcd4EhM6BTEMhz4ROq7Oq6LYUp6kZ%2BgQ6DOmgBgsq8rwUSulwPuyQztKROicfMzEgJYSZ0g2xAJnEwH9J0rAgP0ACs/SkKY/RxGpqBKUJMhyCi3S9Jg/5DJwakEEpWntJ0ADWIDcAAnB2AAcylOdw%2BJDEMcQ8JInD4kISncGpGlaaQOn9GpCggAklmafJpBwLAMCICgqCPHg7BkBQEBoJl2Uuo55hUFl9zEDFEBOFZalOLYGQAJ5KeZpD5UYWgEAA8saTUJaQWAQaI7A1f1eCLCk5wxX1mBcskbEDOFzLKCNcJOMQjV6FgzUWYKRjbZ0ND0EwbAcDw/BmEIIhiHIchCHgTgxZAnSoB4hRTQAtCJ0yHBI%2BkyJwLX5MkhSaNodSmA0ljNBUbgNCEvh0ODwTeAjtDQ9ElQNEDKR0MUtT6DkgjY4UeOlLY5QY7DjT44EEPU2TkQw1wnQKEZfTM0FKmhSNkVci5%2BLvfi3BEsgGLOZIEwQLghAkKZDQTHoBWuKZkgCXpsgyBZNU2aQ9nKXEHY8PrylDPi%2BKOW5YIudwymcyFpB7fr6k80p0WxaQ8XWUlqUQEg3QENCBDkJQ%2BUeFllTmBcMtU4djAsMNZ0AO7rR4%2B2c6pzt9ZFwwS4nhAINy/OC8LcFix2khawlOsIEsWBuNSdtqY7CRhdpruKO7nvyXZID64bNtxCbZsW8pVs25zQzc1n7ddzrin9BXmfhZFlfWZ05wVX4DlAA%3D%3D%3D" rel="nofollow noreferrer">Demo


问:
How to make Google Maps marker bounce again in JavaScript
I want my Google Maps marker to keep bouncing. When it is dragged, I want it to stop bouncing. When it has stopped being dragged, I want it to start bouncing again.

Here is the code:

```<code>    var marker = new google.maps.Marker({
        position: { lat: 0, lng: 0 },
        map: map,
        draggable: true,
        animation: google.maps.Animation.BOUNCE
    });

    marker.addListener('dragend', function () {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    });

    marker.addListener('dragstart', function () {
        marker.setAnimation(null);
    });
</code>```

The problem is that when I stop dragging the marker, it does the bounce animation once (for like a second) and then the marker doesn't keep on bouncing up and down like it did before being dragged.

I have the same problem in another function when I click on a marker and then click on it again (it bounces once after the second click and doesn't keep on bouncing).

It only does one bounce and stops, but I want it to keep on bouncing up and down on dragend (like it does before being dragged), rather than having one bounce and it stopping.

Any ideas why it's not continuing the animation and how to fix it?

答:
Seems like a bug in the API.  Might be worth opening an issue in the issue tracker pointing to this question.

You can work around it by using a setTimeout to restart the animation again:

```<code>marker.addListener('dragend', function() {
  marker.setAnimation(google.maps.Animation.BOUNCE);
  setTimeout(function() {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }, 1000);
});
</code>```

There seems to be some period of time when the previous animation is active, but ending, where it will only bounce once.

The animation_changed event doesn't seem to help either (doesn't seem to fire when the previous animation stops).

proof of concept fiddle

code snippet:

// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.

var marker;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {
      lat: 59.325,
      lng: 18.070
    }
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.BOUNCE,
    position: {
      lat: 59.327,
      lng: 18.067
    }
  });
  marker.addListener('dragend', function() {
    marker.setAnimation(google.maps.Animation.BOUNCE);
    setTimeout(function() {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }, 1000);
  });

  marker.addListener('dragstart', function() {
    marker.setAnimation(null);
  });

  marker.addListener('animation_changed', function() {
    console.log(marker.getAnimation());
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

Body:
I want my Google Maps marker to keep bouncing. When it is dragged, I want it to stop bouncing. When it has stopped being dragged, I want it to start bouncing again.

Here is the code:

    var marker = new google.maps.Marker({
        position: { lat: 0, lng: 0 },
        map: map,
        draggable: true,
        animation: google.maps.Animation.BOUNCE
    });

    marker.addListener('dragend', function () {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    });

    marker.addListener('dragstart', function () {
        marker.setAnimation(null);
    });

The problem is that when I stop dragging the marker, it does the bounce animation once (for like a second) and then the marker doesn't keep on bouncing up and down like it did before being dragged.

I have the same problem in another function when I click on a marker and then click on it again (it bounces once after the second click and doesn't keep on bouncing).

It only does one bounce and stops, but I want it to keep on bouncing up and down on dragend (like it does before being dragged), rather than having one bounce and it stopping.

Any ideas why it's not continuing the animation and how to fix it?

Body:
Seems like a bug in the API.  Might be worth opening an issue in the issue tracker pointing to this question.

You can work around it by using a setTimeout to restart the animation again:

marker.addListener('dragend', function() {
  marker.setAnimation(google.maps.Animation.BOUNCE);
  setTimeout(function() {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }, 1000);
});

There seems to be some period of time when the previous animation is active, but ending, where it will only bounce once.

The animation_changed event doesn't seem to help either (doesn't seem to fire when the previous animation stops).

proof of concept fiddle

code snippet:

// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.

var marker;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {
      lat: 59.325,
      lng: 18.070
    }
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.BOUNCE,
    position: {
      lat: 59.327,
      lng: 18.067
    }
  });
  marker.addListener('dragend', function() {
    marker.setAnimation(google.maps.Animation.BOUNCE);
    setTimeout(function() {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }, 1000);
  });

  marker.addListener('dragstart', function() {
    marker.setAnimation(null);
  });

  marker.addListener('animation_changed', function() {
    console.log(marker.getAnimation());
  })
}

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>


问:
Dynamic collection of classes
It works, but I don't know how:
I want to create a dynamic number of classes, so I use a dictionary for that.
But I can't add a key to each class of the dictionary.
It works when I add each entry of the 1st dictionary to a second dictionary as a couple item/key.

```<code>sub test()
Dim dict As New Dictionary
Dim dict2 As New Dictionary

For i = 1 To 2
    Set dict(i) = New Cfgadress
    dict(i).Col1 = i
    dict2.Add "d" & i, dict(i)
Next i

Debug.Print dict2("d1").Col1
Debug.Print dict2("d2").Col1
End Sub
</code>```

That was a guess and I'm not sure I understand how it works : is the entry of the first dictionary a class object, while the entry of the second dictionary is a dictionary object (couple item/key) ?

答:
No need for the second dictionary. What's the error you're getting with using just one?

Here is my working code:

Add Module: Module1

```<code>Sub test()

    Dim col1 As Dictionary

    Dim classInstance As Class1

    Dim counter As Long

    ' Init the collection
    Set col1 = New Dictionary

    For counter = 1 To 2

        ' Set new instance of class
        Set classInstance = New Class1

        ' Set properties in new class instance
        classInstance.testfield = "Test value" & counter

        ' Add it to the collection
        col1.Add "test" & counter, classInstance

    Next counter

    Debug.Print col1.Item("test1").testfield
    Debug.Print col1.Item("test2").testfield

End Sub
</code>```

Class: Class1

```<code>Public testfield As String
</code>```

Title: Dynamic collection of classes

Body:
It works, but I don't know how:
I want to create a dynamic number of classes, so I use a dictionary for that.
But I can't add a key to each class of the dictionary.
It works when I add each entry of the 1st dictionary to a second dictionary as a couple item/key.

sub test()
Dim dict As New Dictionary
Dim dict2 As New Dictionary

For i = 1 To 2
    Set dict(i) = New Cfgadress
    dict(i).Col1 = i
    dict2.Add "d" & i, dict(i)
Next i

Debug.Print dict2("d1").Col1
Debug.Print dict2("d2").Col1
End Sub

That was a guess and I'm not sure I understand how it works : is the entry of the first dictionary a class object, while the entry of the second dictionary is a dictionary object (couple item/key) ?

Body:
No need for the second dictionary. What's the error you're getting with using just one?

Here is my working code:

Add Module: Module1

Sub test()

    Dim col1 As Dictionary

    Dim classInstance As Class1

    Dim counter As Long

    ' Init the collection
    Set col1 = New Dictionary

    For counter = 1 To 2

        ' Set new instance of class
        Set classInstance = New Class1

        ' Set properties in new class instance
        classInstance.testfield = "Test value" & counter

        ' Add it to the collection
        col1.Add "test" & counter, classInstance

    Next counter

    Debug.Print col1.Item("test1").testfield
    Debug.Print col1.Item("test2").testfield

End Sub

Class: Class1

Public testfield As String


问:
RecyclerView is always above other views
It seems to me that I have read all the topics on stackoverflow and have not found a solution.

The problem is that ImageView is always under RecyclerView, whatever I do, but I need to display ImageView on top of RecyclerView.

Question: Why is this happening and how can I fix it?

Example of right and wrong:

My XML:

```<code><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:clickable="true"
 android:focusable="true"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:background="@drawable/bottom_style"
 android:overScrollMode="never"
 app:behavior_hideable="false"
 app:behavior_peekHeight="150dp"
 app:layout_behavior="....BottomSheetController.MyBottomSheetBehavior">

 <androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="6dp"
    android:layout_marginBottom="6dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        <....BottomSheetController.MyRecyclerView
            android:id="@+id/recycler_view"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:overScrollMode="never" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_button_close" />
    </RelativeLayout>
 </androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答:
Try below code</p>

```<code><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:clickable="true"
        android:focusable="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/colorAccent"
        android:overScrollMode="never"
        app:behavior_hideable="false"
        app:behavior_peekHeight="150dp"
        app:layout_behavior="....BottomSheetController.MyBottomSheetBehavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginTop="6dp"
            android:layout_marginBottom="6dp">

            <androidx.coordinatorlayout.widget.CoordinatorLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp">

 <....BottomSheetController.MyRecyclerView
                       android:id="@+id/recycler_view"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:overScrollMode="never" />

            </androidx.coordinatorlayout.widget.CoordinatorLayout>
            <ImageView
                android:id="@+id/close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:src="@drawable/ic_button_close" />
        </RelativeLayout>

    </androidx.core.widget.NestedScrollView>
</code>```

Body:
It seems to me that I have read all the topics on stackoverflow and have not found a solution.

The problem is that ImageView is always under RecyclerView, whatever I do, but I need to display ImageView on top of RecyclerView.

Question: Why is this happening and how can I fix it?

Example of right and wrong:

My XML:

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:clickable="true"
 android:focusable="true"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:background="@drawable/bottom_style"
 android:overScrollMode="never"
 app:behavior_hideable="false"
 app:behavior_peekHeight="150dp"
 app:layout_behavior="....BottomSheetController.MyBottomSheetBehavior">

 <androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="6dp"
    android:layout_marginBottom="6dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        <....BottomSheetController.MyRecyclerView
            android:id="@+id/recycler_view"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:overScrollMode="never" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_button_close" />
    </RelativeLayout>
 </androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.core.widget.NestedScrollView>

Body:
Try below code

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:clickable="true"
        android:focusable="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/colorAccent"
        android:overScrollMode="never"
        app:behavior_hideable="false"
        app:behavior_peekHeight="150dp"
        app:layout_behavior="....BottomSheetController.MyBottomSheetBehavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginTop="6dp"
            android:layout_marginBottom="6dp">

            <androidx.coordinatorlayout.widget.CoordinatorLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp">

 <....BottomSheetController.MyRecyclerView
                       android:id="@+id/recycler_view"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:overScrollMode="never" />

            </androidx.coordinatorlayout.widget.CoordinatorLayout>
            <ImageView
                android:id="@+id/close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:src="@drawable/ic_button_close" />
        </RelativeLayout>

    </androidx.core.widget.NestedScrollView>


问:
How can I evenly balance a string over the minimum amount of lines using only JavaScript?
I'm trying to evenly balance text over multiple lines using only JavaScript and without caring about the complexity of font sizes.

Given an input string and the maximum1 amount of characters in each line, how can I evenly balance2 the text over the minimum amount of lines?

I'm using an up-to-date version of Google Chrome and legacy browser support isn't important to my question.

Below is my attempt without trying to balance the text (which I want but I don't know how to go about doing it).

It might be possible to remove one or both of the replace() methods by changing the RegExp's string in the match() method.

const stringInputsAndExpectedArrayOutputs = [
  ['', ['']],
  [' ', ['']],
  ['  ', ['']],
  ['.', ['.']],
  ['The ', ['The']],
  ['The quick\nbrown fox', ['The quick brown', 'fox']],
  ['Thequickbrownfox jumpsoverthelazydog.', ['Thequickbrownfox', 'jumpsoverthelazydog.']],
  ['   The   quick   brown   fox   jumps   over   the   lazy   dog.   ', ['The quick brown', 'fox jumps over', 'the lazy dog.']],
  ['The quick brown fox jumps over the lazy dog.', ['The quick brown', 'fox jumps over', 'the lazy dog.']]
];
const maximumCharactersPerLine = 15;

const distributeTextOverLines = ((stringInput, maximumCharactersPerLine) => {
  let arrayOutput = stringInput.replace(/[\r\n ]+$/g, '').replace(/[\r\n ]{2,}|[\r\n]/g, ' ');
  arrayOutput = arrayOutput.match(new RegExp(`(?! )(?:.{1,${maximumCharactersPerLine}}|[^ ]+)(?= |$)`, 'g')) || [''];
  return arrayOutput;
});

for (const [stringInput, expectedArrayOutput] of stringInputsAndExpectedArrayOutputs) {
  const arrayOutput = distributeTextOverLines(stringInput, maximumCharactersPerLine);
  const arrayOutputDifferentThanExpected = !(arrayOutput.length === expectedArrayOutput.length && arrayOutput.every((value, index) => value === expectedArrayOutput[index]));
  if (arrayOutputDifferentThanExpected) {
    console.log('array output:');
    console.log(arrayOutput);
    console.log('expected array output:');
    console.log(expectedArrayOutput);
    continue;
  }
  const stringOutput = arrayOutput.join('\n');
  console.log('string output:');
  console.log(stringOutput);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}</code>```

1 If a word is longer than the maximum limit then the line must contain the whole word overflowing it.

2 Distribute the text in a way so that each line has as similar amount of characters as the other ones have as possible which makes the width of all the lines together as small as possible.

答:
For the even distribution, I would suggest a binary search algorithm:

Do a greedy distribution, like you already did. This fixes the number of lines that the solution must have.

Calculate a theoretical minimum width, based on the total number of characters, the maximum width and the number of lines you have at your disposition.

Perform a binary search in the range between these two width extremes to find the smallest width for which the (greedy) distribution can still fit in that number of lines.

Here is an interactive snippet that allows you to provide text and the maximum width. The output is generated with every change you make.

Just for convenience, the output starts with an extra line of hyphens, filling up the given maximum width. That way you can better visualise how much the result below it deviates from the input width.

function breakLines(text, maxWidth) {
    function greedy(wordSizes, maxWidth) {
        let width = 0;
        let lineWidth = maxWidth;
        let firstWordPerLine = [];
        wordSizes.forEach((wordSize, i) => {
            if (lineWidth + wordSize >= maxWidth) {
                firstWordPerLine.push(i);
                lineWidth = wordSize;
            } else {
                lineWidth += 1 + wordSize;
            }
            if (lineWidth > width) width = lineWidth;
        });

        return { firstWordPerLine, width }
    }

    let words = text.match(/\S+/g);
    if (!words) return "";
    let wordSizes = words.map(word => word.length);
    let letterCount = wordSizes.reduce((a, b) => a+b);

    // Perform a greedy distribution
    let { firstWordPerLine, width } = greedy(wordSizes, maxWidth);
    let bestLines = firstWordPerLine;
    if (width <= maxWidth) { // There is not a word that causes overflow:
        let minWidth = Math.ceil((letterCount + words.length) / bestLines.length) - 1;
        // Perform binary search for optimal width
        while (minWidth < maxWidth) {
            let mid = (minWidth + maxWidth) >> 1;
            let { firstWordPerLine, width } = greedy(wordSizes, mid);
            if (firstWordPerLine.length > bestLines.length) {
                minWidth = mid + 1;
            } else if (width > mid) {
                bestLines = firstWordPerLine;
                break;
            } else {
                maxWidth = width;
                bestLines = firstWordPerLine;
            }
        }
    }
    // Convert bestLines & words to output
    let output = [];
    while (bestLines.length) {
        output.push(words.splice(bestLines.pop(), Infinity).join(" "))
    }
    return output.reverse().join("\n");

}

// I/O handling
let widthInput = document.querySelector("#maxwidth");
let inputText = document.querySelector("#text");
let outputText = document.querySelector("#aligned");

document.addEventListener("input", refresh);

function refresh() {
    let text = inputText.value;
    let maxWidth = Math.min(text.length, Math.max(0, +widthInput.value || 0));
    text = breakLines(text, maxWidth);
    outputText.textContent = "-".repeat(maxWidth) + "\n" + text;
}
refresh();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#maxwidth { width: 5em; }
#text { width: 100%; height: 5em }
#aligned { border: 0.5px solid; width:min-content }</code>```

max width: <input type="number" id="maxwidth" value="50" min="0">

Input:

<textarea id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>

Output:

```</code>```

(Open the snippet in full page mode for a better experience)

Body:
I'm trying to evenly balance text over multiple lines using only JavaScript and without caring about the complexity of font sizes.

Given an input string and the maximum1 amount of characters in each line, how can I evenly balance2 the text over the minimum amount of lines?

I'm using an up-to-date version of Google Chrome and legacy browser support isn't important to my question.

Below is my attempt without trying to balance the text (which I want but I don't know how to go about doing it).

It might be possible to remove one or both of the replace() methods by changing the RegExp's string in the match() method.

const stringInputsAndExpectedArrayOutputs = [
  ['', ['']],
  [' ', ['']],
  ['  ', ['']],
  ['.', ['.']],
  ['The ', ['The']],
  ['The quick\nbrown fox', ['The quick brown', 'fox']],
  ['Thequickbrownfox jumpsoverthelazydog.', ['Thequickbrownfox', 'jumpsoverthelazydog.']],
  ['   The   quick   brown   fox   jumps   over   the   lazy   dog.   ', ['The quick brown', 'fox jumps over', 'the lazy dog.']],
  ['The quick brown fox jumps over the lazy dog.', ['The quick brown', 'fox jumps over', 'the lazy dog.']]
];
const maximumCharactersPerLine = 15;

const distributeTextOverLines = ((stringInput, maximumCharactersPerLine) => {
  let arrayOutput = stringInput.replace(/[\r\n ]+$/g, '').replace(/[\r\n ]{2,}|[\r\n]/g, ' ');
  arrayOutput = arrayOutput.match(new RegExp(`(?! )(?:.{1,${maximumCharactersPerLine}}|[^ ]+)(?= |$)`, 'g')) || [''];
  return arrayOutput;
});

for (const [stringInput, expectedArrayOutput] of stringInputsAndExpectedArrayOutputs) {
  const arrayOutput = distributeTextOverLines(stringInput, maximumCharactersPerLine);
  const arrayOutputDifferentThanExpected = !(arrayOutput.length === expectedArrayOutput.length && arrayOutput.every((value, index) => value === expectedArrayOutput[index]));
  if (arrayOutputDifferentThanExpected) {
    console.log('array output:');
    console.log(arrayOutput);
    console.log('expected array output:');
    console.log(expectedArrayOutput);
    continue;
  }
  const stringOutput = arrayOutput.join('\n');
  console.log('string output:');
  console.log(stringOutput);
}

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

1 If a word is longer than the maximum limit then the line must contain the whole word overflowing it.

2 Distribute the text in a way so that each line has as similar amount of characters as the other ones have as possible which makes the width of all the lines together as small as possible.

Body:
For the even distribution, I would suggest a binary search algorithm:

Do a greedy distribution, like you already did. This fixes the number of lines that the solution must have.

Calculate a theoretical minimum width, based on the total number of characters, the maximum width and the number of lines you have at your disposition.

Perform a binary search in the range between these two width extremes to find the smallest width for which the (greedy) distribution can still fit in that number of lines.

Here is an interactive snippet that allows you to provide text and the maximum width. The output is generated with every change you make.

Just for convenience, the output starts with an extra line of hyphens, filling up the given maximum width. That way you can better visualise how much the result below it deviates from the input width.

function breakLines(text, maxWidth) {
    function greedy(wordSizes, maxWidth) {
        let width = 0;
        let lineWidth = maxWidth;
        let firstWordPerLine = [];
        wordSizes.forEach((wordSize, i) => {
            if (lineWidth + wordSize >= maxWidth) {
                firstWordPerLine.push(i);
                lineWidth = wordSize;
            } else {
                lineWidth += 1 + wordSize;
            }
            if (lineWidth > width) width = lineWidth;
        });

        return { firstWordPerLine, width }
    }

    let words = text.match(/\S+/g);
    if (!words) return "";
    let wordSizes = words.map(word => word.length);
    let letterCount = wordSizes.reduce((a, b) => a+b);

    // Perform a greedy distribution
    let { firstWordPerLine, width } = greedy(wordSizes, maxWidth);
    let bestLines = firstWordPerLine;
    if (width <= maxWidth) { // There is not a word that causes overflow:
        let minWidth = Math.ceil((letterCount + words.length) / bestLines.length) - 1;
        // Perform binary search for optimal width
        while (minWidth < maxWidth) {
            let mid = (minWidth + maxWidth) >> 1;
            let { firstWordPerLine, width } = greedy(wordSizes, mid);
            if (firstWordPerLine.length > bestLines.length) {
                minWidth = mid + 1;
            } else if (width > mid) {
                bestLines = firstWordPerLine;
                break;
            } else {
                maxWidth = width;
                bestLines = firstWordPerLine;
            }
        }
    }
    // Convert bestLines & words to output
    let output = [];
    while (bestLines.length) {
        output.push(words.splice(bestLines.pop(), Infinity).join(" "))
    }
    return output.reverse().join("\n");

}

// I/O handling
let widthInput = document.querySelector("#maxwidth");
let inputText = document.querySelector("#text");
let outputText = document.querySelector("#aligned");

document.addEventListener("input", refresh);

function refresh() {
    let text = inputText.value;
    let maxWidth = Math.min(text.length, Math.max(0, +widthInput.value || 0));
    text = breakLines(text, maxWidth);
    outputText.textContent = "-".repeat(maxWidth) + "\n" + text;
}
refresh();

#maxwidth { width: 5em; }
#text { width: 100%; height: 5em }
#aligned { border: 0.5px solid; width:min-content }

max width: <input type="number" id="maxwidth" value="50" min="0"><br>
Input: <br>
<textarea id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea><br>

Output:
<pre id="aligned"></pre>

(Open the snippet in full page mode for a better experience)


问:
getInstalledPackages issues in Android simulator / device 2.2
The code above does not give quite every installed package (for instance, it does not give the package this code is running from). The code runs from the main thread, never tried other device / emulator versions besides device / emulator 2.2. Any idea what is wrong ?

Thanks

```<code>public Map<String, String> getInstalledPackages()
{
    Map<String, String> apps = new HashMap<String, String>();
    List<PackageInfo> appsInfo = pm.getInstalledPackages(0);

    for (PackageInfo appInfo: appsInfo)
    {
        try
        {
            apps.put(appInfo.packageName, appInfo.versionName);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return apps;
}
</code>```

PS: if I try it with pm.getInstalledPackages(PackageManager.GET_ACTIVITIES) it returns an empty Map - tried on device ony

答:
If I replace

```<code>List<PackageInfo> appsInfo = pm.getInstalledPackages(0);
</code>```

with

```<code>List<PackageInfo> appsInfo = getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);
</code>```

I get the package of my application.

ContentLicense: CC BY-SA 3.0

Body:
The code above does not give quite every installed package (for instance, it does not give the package this code is running from). The code runs from the main thread, never tried other device / emulator versions besides device / emulator 2.2. Any idea what is wrong ?

Thanks

public Map<String, String> getInstalledPackages()
{
    Map<String, String> apps = new HashMap<String, String>();
    List<PackageInfo> appsInfo = pm.getInstalledPackages(0);

    for (PackageInfo appInfo: appsInfo)
    {
        try
        {
            apps.put(appInfo.packageName, appInfo.versionName);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return apps;
}

PS: if I try it with pm.getInstalledPackages(PackageManager.GET_ACTIVITIES) it returns an empty Map - tried on device ony

Body:
If I replace

List<PackageInfo> appsInfo = pm.getInstalledPackages(0);

with

List<PackageInfo> appsInfo = getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);

I get the package of my application.


问:
How can we convert a Python script in to Matlab code?
I want to convert the code written in Python into Matlab code. May I know is it possible to do that. l am wonder, how can we use the python libraries in Matlab. Share the procedure to do the conversion

Here is the Data I used:

https://drive.google.com/open?id=1GLm87-5E_6YhUIPZ_CtQLV9F9wcGaTj2

Here is my code in Python:

```<code># imports libraries
import numpy as np
import pandas as pd
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import random
from scipy import signal
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
from tensorflow import set_random_seed
from tensorflow.keras.initializers import glorot_uniform
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from importlib import reload

# useful pandas display settings
pd.options.display.float_format = '{:.3f}'.format

# useful functions
def plot_history(history, metrics_to_plot):
    """
    Function plots history of selected metrics for fitted neural net.

    """

    # plot
    for metric in metrics_to_plot:
        plt.plot(history.history[metric])

    # name X axis informatively
    plt.xlabel('epoch')

    # name Y axis informatively
    plt.ylabel('metric')

    # add informative legend
    plt.legend(metrics_to_plot)

    # plot
    plt.show()

def plot_fit(y_true, y_pred, title='title'):
    """
    Function plots true values and predicted values, sorted in increase order by true values.

    """

    # create one dataframe with true values and predicted values
    results = y_true.reset_index(drop=True).merge(pd.DataFrame(y_pred), left_index=True, right_index=True)

    # rename columns informartively
    results.columns = ['true', 'prediction']

    # sort for clarity of visualization
    results = results.sort_values(by=['true']).reset_index(drop=True)

    # plot true values vs predicted values
    results.plot()

    # adding scatter on line plots
    plt.scatter(results.index, results.true, s=5)
    plt.scatter(results.index, results.prediction, s=5)

    # name X axis informatively
    plt.xlabel('obs sorted in ascending order with respect to true values')

    # add customizable title
    plt.title(title)

    # plot
    plt.show();

def reset_all_randomness():
    """
    Function assures reproducibility of NN estimation results.

    """

    # reloads
    reload(tf)
    reload(np)
    reload(random)

    # seeds - for reproducibility
    os.environ['PYTHONHASHSEED']=str(984797)
    random.seed(984797)
    set_random_seed(984797)
    np.random.seed(984797)
    my_init = glorot_uniform(seed=984797)

    return my_init
def give_me_mse(true, prediction):
    """
    This function returns mse for 2 vectors: true and predicted values.

    """

    return np.mean((true-prediction)**2)
# Importing the dataset
X = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1").values
y = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet2").values

# Importing the experiment data
Data = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1")
v = pd.DataFrame(Data, columns= ['v']).values
c = pd.DataFrame(Data, columns= ['c']).values
ird = pd.DataFrame(Data, columns= ['ird']).values
tmp = pd.DataFrame(Data, columns= ['tmp']).values

#Data Prepration
ird = ird.ravel()
tmp = tmp.ravel()
ir = np.nanmax(ird)
tp = np.nanmax(tmp)
p = v*c
p = p.ravel()
peaks, _ = signal.find_peaks(p)
nop = len(peaks)
pv = p.max()

#Experimental Data for testing
E_data = np.array([[ir,tp,pv,nop]])

#importing some more libraries
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils

# encode class values as integers
encoder = LabelEncoder()
encoder.fit(np.ravel(y))
y_encoded = encoder.transform(np.ravel(y))
# convert integers to dummy variables (i.e. one hot encoded)
y_dummy = np_utils.to_categorical(y_encoded)

# reset_all_randomness - for reproducibility
my_init = reset_all_randomness()

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test, y_train_dummy, y_test_dummy = train_test_split(X, y, y_dummy, test_size = 0.3, random_state = 20)

# Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
E_data = sc.transform(E_data)

# Initialising the ANN
model0 = Sequential()

# Adding 1 hidden layer: the input layer and the first hidden layer
model0.add(Dense(units = 160, activation = 'tanh', input_dim = 4, kernel_initializer=my_init))

# Adding 2 hidden layer
model0.add(Dense(units = 49, activation = 'tanh', kernel_initializer=my_init))

# Adding 3 hidden layer
model0.add(Dense(units = 24, activation = 'tanh', kernel_initializer=my_init))

# Adding 4 hidden layer
model0.add(Dense(units = 15, activation = 'tanh', kernel_initializer=my_init))

# Adding output layer
model0.add(Dense(units = 6, activation = 'softmax', kernel_initializer=my_init))

# Set up Optimizer
Optimizer = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.99)

# Compiling the ANN
model0.compile(optimizer = Optimizer, loss = 'categorical_crossentropy', metrics=['accuracy','categorical_crossentropy','mse'])

# Fitting the ANN to the Train set, at the same time observing quality on Valid set
history = model0.fit(X_train, y_train_dummy, validation_data=(X_test, y_test_dummy), batch_size = 100, epochs = 1500)

# Generate prediction for all Train, Valid set and Experimental set
y_train_pred_model0 = model0.predict(X_train)
y_test_pred_model0 = model0.predict(X_test)
y_exp_pred_model0 = model0.predict(E_data)

# find final prediction by taking class with highest probability
y_train_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_train_pred_model0])
y_test_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_test_pred_model0])
y_exp_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_exp_pred_model0])

# check what metrics are in fact available in history
history.history.keys()

# Inverse scaling
X_train_inverse = sc.inverse_transform(X_train)
X_test_inverse = sc.inverse_transform(X_test)
E_data_inverse = sc.inverse_transform(E_data)

#Plots
print('#######################################################################')

# look at model fitting history
plot_history(history, ['mean_squared_error', 'val_mean_squared_error'])
plot_history(history, ['categorical_crossentropy', 'val_categorical_crossentropy'])
plot_history(history, ['acc', 'val_acc'])

# look at model fit quality
plot_fit(pd.DataFrame(y_train), y_train_pred_model0, 'Fit on train data')
plot_fit(pd.DataFrame(y_test), y_test_pred_model0, 'Fit on test data')

#Results
print('#######################################################################')

print('=============Mean Squared Error============')

print('MSE on train data is: {}'.format(give_me_mse(y_train, y_train_pred_model0)))
print('MSE on test data is: {}'.format(give_me_mse(y_test, y_test_pred_model0)))

print('#######################################################################')

print('================Accuracy===================')

print('Accuracy of ANN is: {} Percentage'.format((accuracy_score(y_test, y_test_pred_model0))*100))

print('#######################################################################')

print('========Result of Test Data set is=========')

for i in range(len(y_test)):
    print('%s => %d (expected %s)' % (X_test_inverse[i].tolist(), y_test_pred_model0[i], y_test[i].tolist()))

print('#######################################################################')

print('====Result of Experimental Data set is=====')

print('%s => %d' % (E_data_inverse, y_exp_pred_model0))
</code>```

答:
There is  no "direct" way to convert Python code to MATLAB code.

What you can do is directly translate the approach (the algorithm) and write the code from scratch.

or what I think would be more preferable to you is to directly call python script in MATLAB using their API

here is the link for further reading: https://in.mathworks.com/help/matlab/call-python-libraries.html

for example:

```<code>>> py.math.sqrt(4)
ans =
    1
</code>```

To run your own function, you can create a file in your current MATLAB working directory. here is the file ‘hello.py’ that contained these two lines:

```<code>def world():
    return 'hello world'
</code>```

Then in MATLAB:

```<code>>> py.hello.world();
Hello world!
</code>```

if you run into errors make sure you're using the supported version of Python and add

pyversion <path_to_executable>

to the start of your MATLAB file.

Although I'm not sure how well it will work considering all the Python libraries you're importing  (Scipy, Tensorflow etc)

Body:
I want to convert the code written in Python into Matlab code. May I know is it possible to do that. l am wonder, how can we use the python libraries in Matlab. Share the procedure to do the conversion

Here is the Data I used:

https://drive.google.com/open?id=1GLm87-5E_6YhUIPZ_CtQLV9F9wcGaTj2

Here is my code in Python:

# imports libraries
import numpy as np
import pandas as pd
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import random
from scipy import signal
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
from tensorflow import set_random_seed
from tensorflow.keras.initializers import glorot_uniform
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from importlib import reload

# useful pandas display settings
pd.options.display.float_format = '{:.3f}'.format

# useful functions
def plot_history(history, metrics_to_plot):
    """
    Function plots history of selected metrics for fitted neural net.

    """

    # plot
    for metric in metrics_to_plot:
        plt.plot(history.history[metric])

    # name X axis informatively
    plt.xlabel('epoch')

    # name Y axis informatively
    plt.ylabel('metric')

    # add informative legend
    plt.legend(metrics_to_plot)

    # plot
    plt.show()

def plot_fit(y_true, y_pred, title='title'):
    """
    Function plots true values and predicted values, sorted in increase order by true values.

    """

    # create one dataframe with true values and predicted values
    results = y_true.reset_index(drop=True).merge(pd.DataFrame(y_pred), left_index=True, right_index=True)

    # rename columns informartively
    results.columns = ['true', 'prediction']

    # sort for clarity of visualization
    results = results.sort_values(by=['true']).reset_index(drop=True)

    # plot true values vs predicted values
    results.plot()

    # adding scatter on line plots
    plt.scatter(results.index, results.true, s=5)
    plt.scatter(results.index, results.prediction, s=5)

    # name X axis informatively
    plt.xlabel('obs sorted in ascending order with respect to true values')

    # add customizable title
    plt.title(title)

    # plot
    plt.show();

def reset_all_randomness():
    """
    Function assures reproducibility of NN estimation results.

    """

    # reloads
    reload(tf)
    reload(np)
    reload(random)

    # seeds - for reproducibility
    os.environ['PYTHONHASHSEED']=str(984797)
    random.seed(984797)
    set_random_seed(984797)
    np.random.seed(984797)
    my_init = glorot_uniform(seed=984797)

    return my_init
def give_me_mse(true, prediction):
    """
    This function returns mse for 2 vectors: true and predicted values.

    """

    return np.mean((true-prediction)**2)
# Importing the dataset
X = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1").values
y = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet2").values

# Importing the experiment data
Data = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1")
v = pd.DataFrame(Data, columns= ['v']).values
c = pd.DataFrame(Data, columns= ['c']).values
ird = pd.DataFrame(Data, columns= ['ird']).values
tmp = pd.DataFrame(Data, columns= ['tmp']).values

#Data Prepration
ird = ird.ravel()
tmp = tmp.ravel()
ir = np.nanmax(ird)
tp = np.nanmax(tmp)
p = v*c
p = p.ravel()
peaks, _ = signal.find_peaks(p)
nop = len(peaks)
pv = p.max()

#Experimental Data for testing
E_data = np.array([[ir,tp,pv,nop]])

#importing some more libraries
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils

# encode class values as integers
encoder = LabelEncoder()
encoder.fit(np.ravel(y))
y_encoded = encoder.transform(np.ravel(y))
# convert integers to dummy variables (i.e. one hot encoded)
y_dummy = np_utils.to_categorical(y_encoded)

# reset_all_randomness - for reproducibility
my_init = reset_all_randomness()

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test, y_train_dummy, y_test_dummy = train_test_split(X, y, y_dummy, test_size = 0.3, random_state = 20)

# Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
E_data = sc.transform(E_data)

# Initialising the ANN
model0 = Sequential()

# Adding 1 hidden layer: the input layer and the first hidden layer
model0.add(Dense(units = 160, activation = 'tanh', input_dim = 4, kernel_initializer=my_init))

# Adding 2 hidden layer
model0.add(Dense(units = 49, activation = 'tanh', kernel_initializer=my_init))

# Adding 3 hidden layer
model0.add(Dense(units = 24, activation = 'tanh', kernel_initializer=my_init))

# Adding 4 hidden layer
model0.add(Dense(units = 15, activation = 'tanh', kernel_initializer=my_init))

# Adding output layer
model0.add(Dense(units = 6, activation = 'softmax', kernel_initializer=my_init))

# Set up Optimizer
Optimizer = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.99)

# Compiling the ANN
model0.compile(optimizer = Optimizer, loss = 'categorical_crossentropy', metrics=['accuracy','categorical_crossentropy','mse'])

# Fitting the ANN to the Train set, at the same time observing quality on Valid set
history = model0.fit(X_train, y_train_dummy, validation_data=(X_test, y_test_dummy), batch_size = 100, epochs = 1500)

# Generate prediction for all Train, Valid set and Experimental set
y_train_pred_model0 = model0.predict(X_train)
y_test_pred_model0 = model0.predict(X_test)
y_exp_pred_model0 = model0.predict(E_data)

# find final prediction by taking class with highest probability
y_train_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_train_pred_model0])
y_test_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_test_pred_model0])
y_exp_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_exp_pred_model0])

# check what metrics are in fact available in history
history.history.keys()

# Inverse scaling
X_train_inverse = sc.inverse_transform(X_train)
X_test_inverse = sc.inverse_transform(X_test)
E_data_inverse = sc.inverse_transform(E_data)

#Plots
print('#######################################################################')

# look at model fitting history
plot_history(history, ['mean_squared_error', 'val_mean_squared_error'])
plot_history(history, ['categorical_crossentropy', 'val_categorical_crossentropy'])
plot_history(history, ['acc', 'val_acc'])

# look at model fit quality
plot_fit(pd.DataFrame(y_train), y_train_pred_model0, 'Fit on train data')
plot_fit(pd.DataFrame(y_test), y_test_pred_model0, 'Fit on test data')

#Results
print('#######################################################################')

print('=============Mean Squared Error============')

print('MSE on train data is: {}'.format(give_me_mse(y_train, y_train_pred_model0)))
print('MSE on test data is: {}'.format(give_me_mse(y_test, y_test_pred_model0)))

print('#######################################################################')

print('================Accuracy===================')

print('Accuracy of ANN is: {} Percentage'.format((accuracy_score(y_test, y_test_pred_model0))*100))

print('#######################################################################')

print('========Result of Test Data set is=========')

for i in range(len(y_test)):
    print('%s => %d (expected %s)' % (X_test_inverse[i].tolist(), y_test_pred_model0[i], y_test[i].tolist()))

print('#######################################################################')

print('====Result of Experimental Data set is=====')

print('%s => %d' % (E_data_inverse, y_exp_pred_model0))

Body:
There is  no "direct" way to convert Python code to MATLAB code.

What you can do is directly translate the approach (the algorithm) and write the code from scratch.

or what I think would be more preferable to you is to directly call python script in MATLAB using their API

here is the link for further reading: https://in.mathworks.com/help/matlab/call-python-libraries.html

for example:

>> py.math.sqrt(4)
ans =
    1

To run your own function, you can create a file in your current MATLAB working directory. here is the file ‘hello.py’ that contained these two lines:

def world():
    return 'hello world'

Then in MATLAB:

>> py.hello.world();
Hello world!

if you run into errors make sure you're using the supported version of Python and add

pyversion <path_to_executable>

to the start of your MATLAB file.

Although I'm not sure how well it will work considering all the Python libraries you're importing  (Scipy, Tensorflow etc)


问:
terraform aws_cloudwatch_metric_alarm dynamic dimension key error
Wondering if it's possible to use a dynamic evaluated list element in a terraform aws_cloudwatch_metric_alarm dimension name.

using a locals list like this with the idea to create x amount of cloudwatch alarms.

```<code>locals {
 alarm_list = ['service1-status', 'service2-status2', service3-status3']
}
</code>```

in my resouce block for aws_cloudwatch_metric_alarm

```<code>dimensions = {
     "${element(split("-", local.alarms_list[count.index]), 0)}" =
     "${element(split("-", local.alarms_list[count.index]), 1)}"
</code>```

}

this is the output im getting with tf plan.

```<code>  + aws_cloudwatch_metric_alarm.alarm[0]
      id:                                                                   <computed>
      actions_enabled:                                                      "true"
      alarm_description:                                                    "response codes from nginx status"
      alarm_name:                                                           "nginx-status-alarm"
      arn:                                                                  <computed>
      comparison_operator:                                                  "GreaterThanThreshold"
      dimensions.${element(split("-", local.alarms_list[count.index]), 0)}: ""
</code>```

答:
This is pretty simple in terraform 0.12 using map for-expressions, e.g.</p>

```<code>  dimensions = {
    for value in local.alarm_list :
      element(split("-", value), 0) => element(split("-", value), 1)
  }
</code>```

Body:
Wondering if it's possible to use a dynamic evaluated list element in a terraform aws_cloudwatch_metric_alarm dimension name.

using a locals list like this with the idea to create x amount of cloudwatch alarms.

locals {
 alarm_list = ['service1-status', 'service2-status2', service3-status3']
}

in my resouce block for aws_cloudwatch_metric_alarm

dimensions = {
     "${element(split("-", local.alarms_list[count.index]), 0)}" =
     "${element(split("-", local.alarms_list[count.index]), 1)}"

}

this is the output im getting with tf plan.

  + aws_cloudwatch_metric_alarm.alarm[0]
      id:                                                                   <computed>
      actions_enabled:                                                      "true"
      alarm_description:                                                    "response codes from nginx status"
      alarm_name:                                                           "nginx-status-alarm"
      arn:                                                                  <computed>
      comparison_operator:                                                  "GreaterThanThreshold"
      dimensions.${element(split("-", local.alarms_list[count.index]), 0)}: ""

Body:
This is pretty simple in terraform 0.12 using map for-expressions, e.g.

  dimensions = {
    for value in local.alarm_list :
      element(split("-", value), 0) => element(split("-", value), 1)
  }


问:
Is there any good chipmunk/cocos2d sample source out there?
I'm looking for sample to help me understand the how chipmunk physics works ... So I'm asking : is there any source code available out there ?</p>

答:
Check these out:

Bouncy Ball

Collision & Particle System

Moving Shapes With Touches

Also, best place to get support is here.


问:
GAS - Basic Script
I'm trying to do a simple script to transfer the entire line to "Sheet2" every time that the word "Correct" is typed on the 5th Column of the Sheet1.

What is wrong with the code below? Its doesnt works. And, sometimes, the following error message appears:

```<code>ReferenceError: "value" is undefined. (line 2, file "Resize")
</code>```

```<code>function onEdit(e){
  if(e.value != "Correct" || e.range.columnStart != 5) return;
  dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
e.range.offset(0,-5,1,e.source.getActiveSheet().getLastColumn()).moveTo(dest.getRange(dest.getLastRow()+1,1,1,e.source.getActiveSheet().getLastColumn())); }
</code>```

If this could help, I have the same function on VBA:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
 If Target.Column <> 5 Then Exit Sub
 If Target.Value <> "Correct" Then Exit Sub
 Dim LR As Long
  With Sheets("Sheets2")
   LR = .Cells(Rows.Count, 1).End(xlUp).Row
   .Cells(LR + 1, 1).Resize(, 4).Value = Cells(Target.Row, 1).Resize(, 4).Value
  End With
Rows(Target.Row).Delete
End Sub
</code>```

答:
The problem is your offset

If e.range.columnStart is 5, then e.range.offset(0,-5) would be column 0, which is obviously not possible.

Title: GAS - Basic Script

Body:
I'm trying to do a simple script to transfer the entire line to "Sheet2" every time that the word "Correct" is typed on the 5th Column of the Sheet1.

What is wrong with the code below? Its doesnt works. And, sometimes, the following error message appears:

ReferenceError: "value" is undefined. (line 2, file "Resize")

function onEdit(e){
  if(e.value != "Correct" || e.range.columnStart != 5) return;
  dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
e.range.offset(0,-5,1,e.source.getActiveSheet().getLastColumn()).moveTo(dest.getRange(dest.getLastRow()+1,1,1,e.source.getActiveSheet().getLastColumn())); }

If this could help, I have the same function on VBA:

Private Sub Worksheet_Change(ByVal Target As Range)
 If Target.Column <> 5 Then Exit Sub
 If Target.Value <> "Correct" Then Exit Sub
 Dim LR As Long
  With Sheets("Sheets2")
   LR = .Cells(Rows.Count, 1).End(xlUp).Row
   .Cells(LR + 1, 1).Resize(, 4).Value = Cells(Target.Row, 1).Resize(, 4).Value
  End With
Rows(Target.Row).Delete
End Sub


问:
How to use a string variable into re.findall?
I used Python to find a word started and ended with specified letters through a text file. But, I have some problem with using a string variable inside re.findall command. Could you please give me any suggestion?

```<code>import re
import sys

f = open(sys.argv[1]+'.txt', "r")
data = f.read()
re.findall(r'\b'+str(sys.argv[2])'\w+', data)
</code>```

Could you please expanding this code to find a word started and ended with defined letters?

答:
```<code>import re
import sys

thefile = open(sys.argv[1]+".txt", "r")

for line in thefile:
    if re.match(sys.argv[2]+"(.*)"+sys.argv[3]+"(.*)(.*)", line):
        print line
</code>```

argv[1]  is a file name

argv[2] is a starting letter of word,

argv[3] is a ending letter of word,

you can search a word using starting and ending letter of words

Body:
I used Python to find a word started and ended with specified letters through a text file. But, I have some problem with using a string variable inside re.findall command. Could you please give me any suggestion?

import re
import sys

f = open(sys.argv[1]+'.txt', "r")
data = f.read()
re.findall(r'\b'+str(sys.argv[2])'\w+', data)

Could you please expanding this code to find a word started and ended with defined letters?

Body:
import re
import sys

thefile = open(sys.argv[1]+".txt", "r")

for line in thefile:
    if re.match(sys.argv[2]+"(.*)"+sys.argv[3]+"(.*)(.*)", line):
        print line

argv[1]  is a file name

argv[2] is a starting letter of word,

argv[3] is a ending letter of word,

you can search a word using starting and ending letter of words


问:
How to remove compatibility level on subject level
I added compatibility level FULL on a subject and now I want it removed, so the schema-registry compatibility level (global compatibility level) is used. How can it be done?
According to the documentation updating compatibility level for the specified subject is done by 'PUT /config/(string: subject)' + {"compatibility": "FULL"}.

When I try:

```<code>{
  "compatibility": ""
}
</code>```

as body it returns :

```<code>{
    "error_code": 42203,
    "message": "Invalid compatibility level. Valid values are none, backward, forward and full"
}
</code>```

and if I try empty body:

```<code>{
    "error_code": 422,
    "message": "updateSubjectLevelConfig.arg3 may not be null (was null)"
}
</code>```

Can someone help?

答: I checked out schema registry code and in ConfigResource compatibility level received from the request and is parsed against a CompatibilityLevel enum. So, it is either a valid config (none, full...) or exception is thrown (when null). Also, I couldn't find any other rest end point in rest resources that can allow the deletion of this configuration.</p>

Body:
I added compatibility level FULL on a subject and now I want it removed, so the schema-registry compatibility level (global compatibility level) is used. How can it be done?
According to the documentation updating compatibility level for the specified subject is done by 'PUT /config/(string: subject)' + {"compatibility": "FULL"}.

When I try:

{
  "compatibility": ""
}

as body it returns :

{
    "error_code": 42203,
    "message": "Invalid compatibility level. Valid values are none, backward, forward and full"
}

and if I try empty body:

{
    "error_code": 422,
    "message": "updateSubjectLevelConfig.arg3 may not be null (was null)"
}

Can someone help?


问:
How to automate the renaming of a txt file using python
I am trying to find a way to automate the renaming of a file using python.

So the text files need to be renamed everyday to include yesterday's date (T-1).

For example: FileName_20200121.txt needs to be renamed to FileName_20200120.txt.

How do I go about this?

Thanks for the help in advance.

答:
This script will search for a date in format "%Y%m%d" in your file name (for example "FileName_20200121_foobar.txt" will work) and replace the date found in file by date - 1day

```<code>import os
from datetime import datetime, timedelta

old_filename = "FileName_20200121.txt"

strTime = datetime.now().strftime("%Y%m%d")
split_str = old_filename.split(".")[0].split("_")
format_str = "%Y%m%d"

for s in split_str:
    try:
        old_date_str = s # 20200121
        old_date = datetime.strptime(s, format_str).date() # 2020-01-21
        new_date = old_date - timedelta(days=1) # 2020-01-20
        new_date_str = new_date.strftime(format_str) # 20200120
    except:
        pass

new_filename = old_filename.replace(old_date_str, new_date_str)
print("new_filename", new_filename)
# FileName_20200120.txt

os.rename(old_filename, new_filename)

</code>```

Body:
This script will search for a date in format "%Y%m%d" in your file name (for example "FileName_20200121_foobar.txt" will work) and replace the date found in file by date - 1day

import os
from datetime import datetime, timedelta

old_filename = "FileName_20200121.txt"

strTime = datetime.now().strftime("%Y%m%d")
split_str = old_filename.split(".")[0].split("_")
format_str = "%Y%m%d"

for s in split_str:
    try:
        old_date_str = s # 20200121
        old_date = datetime.strptime(s, format_str).date() # 2020-01-21
        new_date = old_date - timedelta(days=1) # 2020-01-20
        new_date_str = new_date.strftime(format_str) # 20200120
    except:
        pass

new_filename = old_filename.replace(old_date_str, new_date_str)
print("new_filename", new_filename)
# FileName_20200120.txt

os.rename(old_filename, new_filename)


问:
How to avoid generated duplicade html code in javascript
Maybe this is a common question in javascript world, but i can't find any usefull keyword for a profitable search. Long story short:

I have html code generated server side, suppose something like this

```<code><div id="container">
    <div class="element">
        <!-- yadayada -->
    </div>

    <div class="element">
        <!-- yadayada -->
    </div>
</div>
</code>```

and a client script to add new elements without reloading the page

```<code><script>
    // do asynchronous server stuff, then add new div from json server output
    var string = "<div class=\"element\">\n" +
                 "    <!-- yadayada -->\n" +
                 "</div>";
    $("#container").prepend($(string));
</script>
</code>```

Well, if the  internal layout is changed in the server scripts, the javascript code must also be changed.

How can I avoid this ? how can I have only one maintainable source for the yadayada layout ?

答:
As mentioned in the comments, you can 'clone' an item served up by the server.

elem.cloneNode(true)

On a page that I did, I named one element 'master' and then used that to create all new elements as needed (I hid the master with CSS display: none).

As mentioned in other posts you can use .clone() with jquery.

If you do not want to use jQuery, you can use regular javascript:

Excerpt from the W3 Schools site:

```<code>// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;
// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);
</code>```

The above is an example of cloning in regular javascript from W3 Schools site: https://www.w3schools.com/jsref/met_node_clonenode.asp

Body:
Maybe this is a common question in javascript world, but i can't find any usefull keyword for a profitable search. Long story short:

I have html code generated server side, suppose something like this

and a client script to add new elements without reloading the page

Well, if the  internal layout is changed in the server scripts, the javascript code must also be changed.

How can I avoid this ? how can I have only one maintainable source for the yadayada layout ?

Body:
As mentioned in the comments, you can 'clone' an item served up by the server.

elem.cloneNode(true)

On a page that I did, I named one element 'master' and then used that to create all new elements as needed (I hid the master with CSS display: none).

As mentioned in other posts you can use .clone() with jquery.

If you do not want to use jQuery, you can use regular javascript:

Excerpt from the W3 Schools site:

// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;
// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);

The above is an example of cloning in regular javascript from W3 Schools site: https://www.w3schools.com/jsref/met_node_clonenode.asp


问:
What does the fdim acronym stand for?
All C math functions seems to have an understandable name, but I can't find what the fdim acronym stands for.
(fdim computes the positive difference of it two floating-point inputs).</p>

答:
My guess is, that it is a composition from difference and max, because this is what the function does.

Pseudo-code

```<code>double fdim(x, y) {
    float    tmp = x - y;        // 1st step: "di"fference
    float result = fmax(tmp, 0); // 2nd step: "m"aximum
    return result;
}
</code>```

Same nomenclature for example with fma(a, b, c), which means "multiply" and "add" (a*b+c)

Edit:

The function indeed occurred even earlier in Fortran, where the function
DIM(number, number) is defined as

A function that returns the value of the first argument minus the minimum (MIN) of the two arguments.

so the function name is derived from difference and minimum here. See the F77 DIM manual

Title: What does the fdim acronym stand for?

Body:
My guess is, that it is a composition from difference and max, because this is what the function does.

Pseudo-code

double fdim(x, y) {
    float    tmp = x - y;        // 1st step: "di"fference
    float result = fmax(tmp, 0); // 2nd step: "m"aximum
    return result;
}

Same nomenclature for example with fma(a, b, c), which means "multiply" and "add" (a*b+c)

Edit:

The function indeed occurred even earlier in Fortran, where the function
DIM(number, number) is defined as

A function that returns the value of the first argument minus the minimum (MIN) of the two arguments.

so the function name is derived from difference and minimum here. See the F77 DIM manual


问:
Creating image histograms from all pictures in a folder
I'm trying to create a histogram for each image in a folder, and save the plots of them into a CSV file. The user would enter the folder the images are saved, and then the files would get created and named accordingly

```<code>files = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] #loop to get all files from folder
for x in files:
    image = "x + 1"
    img2 = cv2.imread('similarImages/' + directory + '/' + image + '.png', cv2.IMREAD_COLOR)
    histSim = cv2.calcHist([img2], [1], None, [256], [0, 256])  # create histo of each image
    np.savetxt('Test/similarImage' + x + '.csv', histSim, delimiter=',')  # save save plots to csv
</code>```

From my previous knowledge of python, I've theory crafted the above code, but in classic fashion, it doesnt work (shocker)

Am I going along the right lines? If not could I get a nudge in the right direction, and if so, why doesnt it work?

It's been a while since I took on something like this, and such I am a little rusty, many thanks, Ben

答:
You can use pandas for this task. If you want to store all the histograms in a single csv file you can use a list and append all the histogram values to it using this

```<code>df = []
df.append(cv2.calcHist(img, [1], None, [256], [0, 256])[:, 0]) # check if you want like this or transpose.
</code>```

Then convert it to a dataframe using pd.DataFrame and store it as a csv file using df.to_csv

If you want to save each histogram to its independent csv file then you can:

```<code>histSim = pd.DataFrame(cv2.calcHist(img, [1], None, [256], [0, 256]))
histSim.to_csv('histogram.csv', index=False)
</code>```

Body:
I'm trying to create a histogram for each image in a folder, and save the plots of them into a CSV file. The user would enter the folder the images are saved, and then the files would get created and named accordingly

files = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] #loop to get all files from folder
for x in files:
    image = "x + 1"
    img2 = cv2.imread('similarImages/' + directory + '/' + image + '.png', cv2.IMREAD_COLOR)
    histSim = cv2.calcHist([img2], [1], None, [256], [0, 256])  # create histo of each image
    np.savetxt('Test/similarImage' + x + '.csv', histSim, delimiter=',')  # save save plots to csv

From my previous knowledge of python, I've theory crafted the above code, but in classic fashion, it doesnt work (shocker)

Am I going along the right lines? If not could I get a nudge in the right direction, and if so, why doesnt it work?

It's been a while since I took on something like this, and such I am a little rusty, many thanks, Ben

Body:
You can use pandas for this task. If you want to store all the histograms in a single csv file you can use a list and append all the histogram values to it using this

df = []
df.append(cv2.calcHist(img, [1], None, [256], [0, 256])[:, 0]) # check if you want like this or transpose.

Then convert it to a dataframe using pd.DataFrame and store it as a csv file using df.to_csv

If you want to save each histogram to its independent csv file then you can:

histSim = pd.DataFrame(cv2.calcHist(img, [1], None, [256], [0, 256]))
histSim.to_csv('histogram.csv', index=False)


问:
neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified."
Can anyone help me, I'm working on .NET Framework version 4.5.
I'm trying to add the data connection of PostgreSQL but this message came out.

"Could not load file or assembly
  'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified."

I tried different version but it didn't work.

答: This is a known issue that is already reported on github. Upvote the issue and look for fixes.</p>


问:
How to make git status show only staged files
I would like to get a list of only the staged filenames. I can't find the equivalent flag for --name-only for the git status command. What is a good alternative?

The file list will be piped to php -l (PHP lint syntax checker).

Solution: the complete command

```<code>git diff --name-only --cached | xargs -l php -l
</code>```

答:
to view staged files with code changes

```<code>git diff --staged
</code>```

or using --cached which is  synonym for --staged

```<code>git diff --cached
</code>```

or to view only file names  without code changes

```<code>git diff --staged --name-only
</code>```

git-diff manual

Body:
I would like to get a list of only the staged filenames. I can't find the equivalent flag for --name-only for the git status command. What is a good alternative?

The file list will be piped to php -l (PHP lint syntax checker).

Solution: the complete command

git diff --name-only --cached | xargs -l php -l

Body:
to view staged files with code changes

git diff --staged

or using --cached which is  synonym for --staged

git diff --cached

or to view only file names  without code changes

git diff --staged --name-only

git-diff manual


问:
Apply theme to material UI menu component
I have next code, for applying custom theme:

```<code>import Menu from '@material-ui/core/Menu';
import { createStyles, withStyles, Theme } from '@material-ui/core/styles';

const myMenu = withStyles( ( theme: Theme ) =>
    createStyles( {
        root: {
            backgroundColor: theme.palette.primary.main,
        },
    } ),
)( Menu );
</code>```

But I am getting next error:

```<code>Argument of type 'ComponentType<MenuProps>' is not assignable to parameter of type 'ComponentType<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>>'.
  Type 'ComponentClass<MenuProps, any>' is not assignable to type 'ComponentType<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>>'.
    Type 'ComponentClass<MenuProps, any>' is not assignable to type 'ComponentClass<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>, any>'.
      Types of property 'propTypes' are incompatible.
        Type 'WeakValidationMap<MenuProps> | undefined' is not assignable to type
</code>```

答:
You have to move (theme: Theme) => inside the createStyles function. Like this:

import Menu from '@material-ui/core/Menu';
import { createStyles, withStyles, Theme } from '@material-ui/core/styles';

const myMenu = withStyles(createStyles((theme: Theme) => {
        root: {
            backgroundColor: theme.palette.primary.main,
        },
    }),
)( Menu );
```

Body:
I have next code, for applying custom theme:

import Menu from '@material-ui/core/Menu';
import { createStyles, withStyles, Theme } from '@material-ui/core/styles';

const myMenu = withStyles( ( theme: Theme ) =>
    createStyles( {
        root: {
            backgroundColor: theme.palette.primary.main,
        },
    } ),
)( Menu );

But I am getting next error:

Argument of type 'ComponentType<MenuProps>' is not assignable to parameter of type 'ComponentType<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>>'.
  Type 'ComponentClass<MenuProps, any>' is not assignable to type 'ComponentType<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>>'.
    Type 'ComponentClass<MenuProps, any>' is not assignable to type 'ComponentClass<ConsistentWith<MenuProps, { classes: Record<"root", string>; }> | ConsistentWith<PropsWithChildren<MenuProps>, { ...; }>, any>'.
      Types of property 'propTypes' are incompatible.
        Type 'WeakValidationMap<MenuProps> | undefined' is not assignable to type


问:
Compilation issue with typescript file
I'm new to typescript and was trying to work on it where in I came across this issue, where I saved a file using .ts extension and instead of recognizing the file as a typescript file,the system is recognizing it as a Transport Stream file. I have already installed all the typescript files using node. Whenever I try to compile the code the error displayed is as follows:

PS D:\WorkSpace\typescript> tsc basics.ts tsc : File
  C:\Users\mn\AppData\Roaming\npm\tsc.ps1 cannot be loaded because
  running scripts is disabled on this system. For more information, see
  about_Execution_Policies at
  https:/go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

tsc basics.ts

```<code>+ CategoryInfo          : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
</code>```

This is how the file appears in the folder:

Folder image

答:
For now, I suggest removing all .ps1 files from your npm bin folder.

Sometimes changing the execution policy is not a good practice. A more restricted Execution policy (RemoteSigned) helps users from unintentionally running malicious code.

The issue is still open in the npm/cli repository, labeled as 'Needs Discussion' Necessity of Powershell Script Support for Global Packages.

Title: Compilation issue with typescript file

Body:
I'm new to typescript and was trying to work on it where in I came across this issue, where I saved a file using .ts extension and instead of recognizing the file as a typescript file,the system is recognizing it as a Transport Stream file. I have already installed all the typescript files using node. Whenever I try to compile the code the error displayed is as follows:

PS D:\WorkSpace\typescript> tsc basics.ts tsc : File
  C:\Users\mn\AppData\Roaming\npm\tsc.ps1 cannot be loaded because
  running scripts is disabled on this system. For more information, see
  about_Execution_Policies at
  https:/go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

tsc basics.ts

+ CategoryInfo          : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

This is how the file appears in the folder:

Folder image


问:
Operating on every element of a list without for loop
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

```<code>def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed
</code>```

Is there any other way of accessing list elements in a manner that a for loop would do?

答:
You can iterate over the list using while loop:</p>

```<code>i = 0
sizeofList = len(wordList)
while i < sizeofList :
    print(wordList[i])
    i += 1
</code>```

Body:
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed

Is there any other way of accessing list elements in a manner that a for loop would do?

Body:
You can iterate over the list using while loop:

i = 0
sizeofList = len(wordList)
while i < sizeofList :
    print(wordList[i])
    i += 1


问:
Django rest_api and React
I am creating an am using Django and React. I have created custom user model api in Django using rest-framework, but i am confused about the whole login and signup system. Do we create login and signup modules in Django or React.
Can anyone please guide me through it, or suggest any tutorial. </p>

答: You create the templates (login, signup, etc. pages) in React and connect them to DRF. There are multiple ways to perform authentication. Take a look to Authentication docs on DRF. https://django-rest-framework.org/api-guide/authentication</p>

Title: Django rest_api and React


问:
Excel - Find the correct value out of multiple
I'm currently trying to extract a set of values corresponding to some other but can't succeed.

On my sheet, I have 2 columns (Country (C) / online(D))

Wrong

There are multiple values.
In columns F and G, I display the results.

I'm using a formula with INDEX/MATCH to do this but the problem it only takes into account the first value found (so for country BEL, first value is "yes", it will show "yes" in column G). My formula is

```<code>=INDEX(D2:D8,MATCH(F2:F4,C2:C8,0))
</code>```

What I'd like is if for BEL there are "yes" and "no" values, the result will show me "no". so "yes" is a default value and if there are "yes" and "no", since there is a different value for BEL, it will show this other value and give this

Right

any idea how to do this ?

Hope it's clear.

Thanks a lot for your help.

答:
You can use COUNTIFS to get the number of matches where ONLINE = "no" for each country, then use that as an input to an IF statement that will output "no" if the count of "no" in the table is > 0

here is a formula to get started:

```<code>=IF(COUNTIFS(B:B,"=no",A:A,E4)>0,"no","yes")
</code>```

COL A has the Countries, B the Online state, and E is the summary section

Body:
I'm currently trying to extract a set of values corresponding to some other but can't succeed.

On my sheet, I have 2 columns (Country (C) / online(D))

Wrong

There are multiple values.
In columns F and G, I display the results.

I'm using a formula with INDEX/MATCH to do this but the problem it only takes into account the first value found (so for country BEL, first value is "yes", it will show "yes" in column G). My formula is

=INDEX(D2:D8,MATCH(F2:F4,C2:C8,0))

What I'd like is if for BEL there are "yes" and "no" values, the result will show me "no". so "yes" is a default value and if there are "yes" and "no", since there is a different value for BEL, it will show this other value and give this

Right

any idea how to do this ?

Hope it's clear.

Thanks a lot for your help.

Body:
You can use COUNTIFS to get the number of matches where ONLINE = "no" for each country, then use that as an input to an IF statement that will output "no" if the count of "no" in the table is > 0

here is a formula to get started:

=IF(COUNTIFS(B:B,"=no",A:A,E4)>0,"no","yes")

COL A has the Countries, B the Online state, and E is the summary section


问:
Can exif-parser extract XMP (Extensible Metadata Platform) tags?
I'm looking for a Javascript package to extract an extended image tag Projection Type
to detect between image with projection (e.g. sphere image) and image without projection.

I found another Javascript library (exifreader) that extracts XMP (Extensible Metadata Platform) tags including the Projection Type tag.

Since I'm looking to use well-maintained, and optimized code I compared between the 2 Javascript exif-parser, and exifreader.

In terms of popularity and size, exif-parser is clearly a winner (see the table below).

But I don't find any reference to extended metadata or XMP flags in the exif-parser code.

 the Javascript package exif-parser extract XMP tags?

Thanks,

Avi

答:
I'd like to chime in with my own library exifr. I've written it because the others out there either aren't maintained, isomorphic, don't support HEIC photos, can't parse segments other than TIFF/EXIF (in your case you look for XMP), aren't efficient, read the whole file, or all of the above.

I've written exifr to be the fastest and also most efficient. And yes it does read XMP. I'd be happy if you would try it out. There's a playground for experimenting with images, or check out the repository and docs.

There's one catch though. To keep the exifr's size down, it does not parse the XML. It only exports the XML string for you. There's plenty of XML parsers out there and many ways to parse XML (since the tag can have both attributes and children).

PS: Right now I'm just a days off from publishing version 3.0.0, which is a complete rewrite. It's already in repo's master branch, but it's not yet published on npm.