问:
ORA-04091: table CISTU018.TIMESHEET is mutating, trigger/function may not see it
I have created a trigger:(my before trigger worked well, but my instructor wanted me to do an after trigger, but it didn't work when I tried to fire the trigger)

```<code>/*AFTER TRIGGER*/
SET SERVEROUTPUT ON;
SET VERIFY OFF
CREATE OR REPLACE TRIGGER HOUR_TIMESHEET
AFTER INSERT ON TIMESHEET
FOR EACH ROW

DECLARE
T_REGHOURS TIMESHEET.REGHOURS%TYPE := :NEW.REGHOURS;
T_OTIMEHOURS TIMESHEET.OTIMEHOURS%TYPE := :NEW.REGHOURS - 40;
T_EMPID TIMESHEET.EMPID%TYPE := :NEW.EMPID;
T_PAYWEEKENDDATE TIMESHEET.PAYWEEKENDDATE%TYPE := :NEW.PAYWEEKENDDATE;
BEGIN
  IF(T_REGHOURS > 40)
  THEN
  DBMS_OUTPUT.PUT_LINE('Employee ID:'|| T_EMPID);
  UPDATE TIMESHEET
    SET REGHOURS = 40, OTIMEHOURS = (T_OTIMEHOURS) WHERE EMPID = :OLD.EMPID AND PAYWEEKENDDATE = :OLD.PAYWEEKENDDATE;
  END IF;
END;

/*end of trigger*/
</code>```

Script output:  the trigger compiled: Trigger HOUR_TIMESHEET compiled

Then I tried to do an insert in order to fire the trigger:
INSERT INTO TIMESHEET VALUES(72690,'30-MAY-03',42,0);

Then it gave me an error message:

```<code>Error starting at line : 142 in command -
INSERT INTO TIMESHEET VALUES(72690,'30-MAY-03',42,0)
Error report -
SQL Error: ORA-04091: table CISTU018.TIMESHEET is mutating, trigger/function may not see it
ORA-06512: at "CISTU018.HOUR_TIMESHEET", line 10
ORA-04088: error during execution of trigger 'CISTU018.HOUR_TIMESHEET'
04091. 00000 -  "table %s.%s is mutating, trigger/function may not see it"
*Cause:    A trigger (or a user defined plsql function that is referenced in
           this statement) attempted to look at (or modify) a table that was
           in the middle of being modified by the statement which fired it.
*Action:   Rewrite the trigger (or function) so it does not read that table.
Employee ID:72690
</code>```

答:
The update statement in the body of the row-level TRIGGER is forbidden, as it reads from the TABLE to which the trigger is attached.  Any SELECT or manipulation of the attached table is prohibited in oracle row-level triggers.

If your goal is to convert surplus (>40) regular-hours in new TIMESHEET records to overtime-hours, you don't need to make an update in the statement at all and can use a BEFORE TRIGGER to directly mutate incoming data, but as you mentioned your instructor asked for an AFTER TRIGGER, I'll include an AFTER example.    I'm not sure if this is a suggestion or a requirement, so I'll include a little discussion about BEFORE triggers as well, as these may be preferable, depending on the situation.

Here's a simple example using an AFTER trigger, presuming there aren't other triggers involved.  In this example, the TRIGGER timing is changed to statement rather than ROW.  This removes the restriction you observed in your original error, and pulls any surplus hours away from regular-hours and adds them to overtime-hours.

First, create the table:

```<code>CREATE TABLE  TIMESHEET(
EMPID NUMBER(10,0) NOT NULL,
REGHOURS NUMBER(3,0) NOT NULL,
OTIMEHOURS NUMBER(3,0) NOT NULL,
PAYWEEKENDDATE DATE NOT NULL);
</code>```

Then create the statement-level AFTER TRIGGER:

```<code>CREATE OR REPLACE TRIGGER HOUR_TIMESHEET
AFTER INSERT ON TIMESHEET
BEGIN
UPDATE TIMESHEET
SET REGHOURS = 40,
OTIMEHOURS = (OTIMEHOURS + REGHOURS - 40)
WHERE REGHOURS > 40;
END;
/
</code>```

Then test it by inserting some data:

```<code>--reghours <= 40 and no overtime present. No change expected
INSERT INTO TIMESHEET VALUES (1,40, 0, TO_DATE('20170401','YYYYMMDD'));
-- reghours < 40 and overtime already counted.  No change expected
INSERT INTO TIMESHEET VALUES (2,20, 15, TO_DATE('20170401','YYYYMMDD'));
-- reghours (50) > 40, plus 10 additional overtime hours.  Expecting adjustment to 40 + 20
INSERT INTO TIMESHEET VALUES (1,50, 10, TO_DATE('20170415','YYYYMMDD'));
-- reghours (55) > 40, plus no overtime.  Expecting adjustment to 40 + 15
INSERT INTO TIMESHEET VALUES (2,55, 0, TO_DATE('20170415','YYYYMMDD'));
COMMIT;
</code>```

Then check what the TRIGGER did:

```<code>SELECT * FROM TIMESHEET ORDER BY 4 ASC, 1 ASC;
EMPID  REGHOURS  OTIMEHOURS  PAYWEEKENDDATE
1      40        0           01-APR-17
2      20        15          01-APR-17
1      40        20          15-APR-17
2      40        15          15-APR-17
</code>```

The trigger swept through AFTER the INSERT completed, and updated surplus REGHOURS to OTIMEHOURS, but left other REGHOURS and OTIMEHOURS alone.  Hopefully this aligns with your goals.

There are pros and cons to the use of row-level and statement-level triggers, and deciding what to use can depend on the data model involved as well as other triggers in play, etc.

Another alternative is to just use a BEFORE trigger to directly mutate the values of incoming :NEW fields, as you mentioned in your question.  Please keep in mind that this may be lower-cost and preferable, depending on the data involved and whether other TRIGGERs are in-play. Weighing pros and cons of statement vs row can be beneficial.

Keeping triggers as simple as possible is recommended.  However, if you really need to take action that would make use of selecting against the attached-table and require row-level evaluations, or need to tune or nuance statement-level triggers,  I'd recommend looking into Compound-Triggers

Body:
I have created a trigger:(my before trigger worked well, but my instructor wanted me to do an after trigger, but it didn't work when I tried to fire the trigger)

/*AFTER TRIGGER*/
SET SERVEROUTPUT ON;
SET VERIFY OFF
CREATE OR REPLACE TRIGGER HOUR_TIMESHEET
AFTER INSERT ON TIMESHEET
FOR EACH ROW

DECLARE
T_REGHOURS TIMESHEET.REGHOURS%TYPE := :NEW.REGHOURS;
T_OTIMEHOURS TIMESHEET.OTIMEHOURS%TYPE := :NEW.REGHOURS - 40;
T_EMPID TIMESHEET.EMPID%TYPE := :NEW.EMPID;
T_PAYWEEKENDDATE TIMESHEET.PAYWEEKENDDATE%TYPE := :NEW.PAYWEEKENDDATE;
BEGIN
  IF(T_REGHOURS > 40)
  THEN
  DBMS_OUTPUT.PUT_LINE('Employee ID:'|| T_EMPID);
  UPDATE TIMESHEET
    SET REGHOURS = 40, OTIMEHOURS = (T_OTIMEHOURS) WHERE EMPID = :OLD.EMPID AND PAYWEEKENDDATE = :OLD.PAYWEEKENDDATE;
  END IF;
END;

/*end of trigger*/

Script output:  the trigger compiled: Trigger HOUR_TIMESHEET compiled

Then I tried to do an insert in order to fire the trigger:
INSERT INTO TIMESHEET VALUES(72690,'30-MAY-03',42,0);

Then it gave me an error message:

Error starting at line : 142 in command -
INSERT INTO TIMESHEET VALUES(72690,'30-MAY-03',42,0)
Error report -
SQL Error: ORA-04091: table CISTU018.TIMESHEET is mutating, trigger/function may not see it
ORA-06512: at "CISTU018.HOUR_TIMESHEET", line 10
ORA-04088: error during execution of trigger 'CISTU018.HOUR_TIMESHEET'
04091. 00000 -  "table %s.%s is mutating, trigger/function may not see it"
*Cause:    A trigger (or a user defined plsql function that is referenced in
           this statement) attempted to look at (or modify) a table that was
           in the middle of being modified by the statement which fired it.
*Action:   Rewrite the trigger (or function) so it does not read that table.
Employee ID:72690

Body:
The update statement in the body of the row-level TRIGGER is forbidden, as it reads from the TABLE to which the trigger is attached.  Any SELECT or manipulation of the attached table is prohibited in oracle row-level triggers.

If your goal is to convert surplus (>40) regular-hours in new TIMESHEET records to overtime-hours, you don't need to make an update in the statement at all and can use a BEFORE TRIGGER to directly mutate incoming data, but as you mentioned your instructor asked for an AFTER TRIGGER, I'll include an AFTER example.    I'm not sure if this is a suggestion or a requirement, so I'll include a little discussion about BEFORE triggers as well, as these may be preferable, depending on the situation.

Here's a simple example using an AFTER trigger, presuming there aren't other triggers involved.  In this example, the TRIGGER timing is changed to statement rather than ROW.  This removes the restriction you observed in your original error, and pulls any surplus hours away from regular-hours and adds them to overtime-hours.

First, create the table:

CREATE TABLE  TIMESHEET(
EMPID NUMBER(10,0) NOT NULL,
REGHOURS NUMBER(3,0) NOT NULL,
OTIMEHOURS NUMBER(3,0) NOT NULL,
PAYWEEKENDDATE DATE NOT NULL);

Then create the statement-level AFTER TRIGGER:

CREATE OR REPLACE TRIGGER HOUR_TIMESHEET
AFTER INSERT ON TIMESHEET
BEGIN
UPDATE TIMESHEET
SET REGHOURS = 40,
OTIMEHOURS = (OTIMEHOURS + REGHOURS - 40)
WHERE REGHOURS > 40;
END;
/

Then test it by inserting some data:

--reghours <= 40 and no overtime present. No change expected
INSERT INTO TIMESHEET VALUES (1,40, 0, TO_DATE('20170401','YYYYMMDD'));
-- reghours < 40 and overtime already counted.  No change expected
INSERT INTO TIMESHEET VALUES (2,20, 15, TO_DATE('20170401','YYYYMMDD'));
-- reghours (50) > 40, plus 10 additional overtime hours.  Expecting adjustment to 40 + 20
INSERT INTO TIMESHEET VALUES (1,50, 10, TO_DATE('20170415','YYYYMMDD'));
-- reghours (55) > 40, plus no overtime.  Expecting adjustment to 40 + 15
INSERT INTO TIMESHEET VALUES (2,55, 0, TO_DATE('20170415','YYYYMMDD'));
COMMIT;

Then check what the TRIGGER did:

SELECT * FROM TIMESHEET ORDER BY 4 ASC, 1 ASC;
EMPID  REGHOURS  OTIMEHOURS  PAYWEEKENDDATE
1      40        0           01-APR-17
2      20        15          01-APR-17
1      40        20          15-APR-17
2      40        15          15-APR-17

The trigger swept through AFTER the INSERT completed, and updated surplus REGHOURS to OTIMEHOURS, but left other REGHOURS and OTIMEHOURS alone.  Hopefully this aligns with your goals.

There are pros and cons to the use of row-level and statement-level triggers, and deciding what to use can depend on the data model involved as well as other triggers in play, etc.

Another alternative is to just use a BEFORE trigger to directly mutate the values of incoming :NEW fields, as you mentioned in your question.  Please keep in mind that this may be lower-cost and preferable, depending on the data involved and whether other TRIGGERs are in-play. Weighing pros and cons of statement vs row can be beneficial.

Keeping triggers as simple as possible is recommended.  However, if you really need to take action that would make use of selecting against the attached-table and require row-level evaluations, or need to tune or nuance statement-level triggers,  I'd recommend looking into Compound-Triggers


来源: stackexchange

问:
Checked static cast on a reference
Long ago I have created a following template so that I get an assert whenever I perform a static_cast but the type is not what I assume it to be:

```<code>/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}
</code>```

Today I wanted to create a variant which would work not only with pointers, but with references as well:

```<code>/// overload for reference
template <class Type, class SourceType>
Type &static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<Type *>(&item));
  return static_cast<Type>(item);
}
</code>```

However, the compiler does not seem to use this overload when I am casting a reference to another reference. I am afraid I do not understand template resolution rules enough to understand why, or to be able to create a variant which works.

Note: I cannot catch the bad_cast exception instead of checking dynamic_cast<Type *> for NULL, as exceptions are disabled for this project.

答:
```<code>#include <boost/type_traits/add_pointer.hpp>

template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
  assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

template <typename Type,  class SourceType>
Type static_cast_checked(SourceType &item)
{
   typedef typename boost::add_pointer<Type>::type TypePtr;
   assert(dynamic_cast< TypePtr >(&item));
   return static_cast<Type>(item);
}
</code>```

This implementation works like static_cast or dynamic_cast from the std-lib:``

```<code>    Base &b    = static_cast_checked<Base&>( a);
    Base* bPtr = static_cast_checked<Base*>(&a);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Checked static cast on a reference

Body:
Long ago I have created a following template so that I get an assert whenever I perform a static_cast but the type is not what I assume it to be:

/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
  Assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

Today I wanted to create a variant which would work not only with pointers, but with references as well:

/// overload for reference
template <class Type, class SourceType>
Type &static_cast_checked(SourceType &item)
{
  Assert(dynamic_cast<Type *>(&item));
  return static_cast<Type>(item);
}

However, the compiler does not seem to use this overload when I am casting a reference to another reference. I am afraid I do not understand template resolution rules enough to understand why, or to be able to create a variant which works.

Note: I cannot catch the bad_cast exception instead of checking dynamic_cast<Type *> for NULL, as exceptions are disabled for this project.

Body:
#include <boost/type_traits/add_pointer.hpp>

template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
  assert(!item || dynamic_cast<Type>(item));
  return static_cast<Type>(item);
}

template <typename Type,  class SourceType>
Type static_cast_checked(SourceType &item)
{
   typedef typename boost::add_pointer<Type>::type TypePtr;
   assert(dynamic_cast< TypePtr >(&item));
   return static_cast<Type>(item);
}

This implementation works like static_cast or dynamic_cast from the std-lib:``

    Base &b    = static_cast_checked<Base&>( a);
    Base* bPtr = static_cast_checked<Base*>(&a);


问:
Replace 2 parts in a single string with other string using JAVA
I have a string like:

```<code>{abc} say hello to {def};
</code>```

or

```<code>You say hello to {abc};
</code>```

Now I want to replace this sentence like this:

```<code>Peter say hello to Sally;
</code>```

or

```<code>You say hello to Peter
</code>```

which {abc} and {def} are user's ID, so I need to get the string inside { }. Then replace these words. How can I get the words inside { }

I tried to use .indexOf and .substring to make it work. But I think it is not a good idea as it need a lot of codes to handle two kinds.
My method:

```<code>String sentence = {abc} say hello to {def};
int firstOpen = sentence.indexOf("{");
int firstClose = sentence.indexOf("}");
int secondOpen = sentence.lastIndexOf("{");
int secondClose = sentence.lastIndexOf("}");
String firstName = sentence.subSting(firstOpen + 1, firstClose);
String secondName = sentence.subSting(secondOpen + 1, secondClose);
...
sentence = "Peter" + sentence.substring(firstClose, secondOpen) .....
</code>```

答:
Just use String.replace</p>

```<code>String output = "{abc} say hello to {def}".replace ("{abc}", "Peter")
                                          .replace ("{def}", "Sally");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a string like:

{abc} say hello to {def};

or

You say hello to {abc};

Now I want to replace this sentence like this:

Peter say hello to Sally;

or

You say hello to Peter

which {abc} and {def} are user's ID, so I need to get the string inside { }. Then replace these words. How can I get the words inside { }

I tried to use .indexOf and .substring to make it work. But I think it is not a good idea as it need a lot of codes to handle two kinds.
My method:

String sentence = {abc} say hello to {def};
int firstOpen = sentence.indexOf("{");
int firstClose = sentence.indexOf("}");
int secondOpen = sentence.lastIndexOf("{");
int secondClose = sentence.lastIndexOf("}");
String firstName = sentence.subSting(firstOpen + 1, firstClose);
String secondName = sentence.subSting(secondOpen + 1, secondClose);
...
sentence = "Peter" + sentence.substring(firstClose, secondOpen) .....

Body:
Just use String.replace

String output = "{abc} say hello to {def}".replace ("{abc}", "Peter")
                                          .replace ("{def}", "Sally");


问:
How can I batch reindex several elastic indexes?
For example, I have quite large numbers of indexes named like:

```<code>logstash-oidmsgcn_2016.12.01
logstash-oidmsgcn_2016.12.02
logstash-oidmsgcn_2016.12.03
...
logstash-oidmsgcn_2017.02.21
</code>```

need to be indexed to names:

```<code>bk-logstash-oidmsgcn_2016.12.01
bk-logstash-oidmsgcn_2016.12.02
bk-logstash-oidmsgcn_2016.12.03
...
bk-logstash-oidmsgcn_2017.02.21
</code>```

so, I only need to give their names a prefix in a batch way.
what can I do to get this job done?
I have referenced to reindex api and bulk api, but I still cannot get the hang of its way.

答:
You can only do this be reindexing all your indices. If you are open to do this, you can do it with the reindex API like this:

```<code>POST _reindex
{
  "source": {
    "index": "logstash-oidmsgcn_*"
  },
  "dest": {
    "index": "bk-logstash-oidmsgcn"
  },
  "script": {
    "inline": "ctx._index = 'bk-logstash-oidmsgcn_' + (ctx._index.substring('logstash-oidmsgcn_'.length(), ctx._index.length()))"
  }
}
</code>```

Note that you need to enable dynamic scripting in order for this to work.

Body:
For example, I have quite large numbers of indexes named like:

logstash-oidmsgcn_2016.12.01
logstash-oidmsgcn_2016.12.02
logstash-oidmsgcn_2016.12.03
...
logstash-oidmsgcn_2017.02.21

need to be indexed to names:

bk-logstash-oidmsgcn_2016.12.01
bk-logstash-oidmsgcn_2016.12.02
bk-logstash-oidmsgcn_2016.12.03
...
bk-logstash-oidmsgcn_2017.02.21

so, I only need to give their names a prefix in a batch way.
what can I do to get this job done?
I have referenced to reindex api and bulk api, but I still cannot get the hang of its way.

Body:
You can only do this be reindexing all your indices. If you are open to do this, you can do it with the reindex API like this:

POST _reindex
{
  "source": {
    "index": "logstash-oidmsgcn_*"
  },
  "dest": {
    "index": "bk-logstash-oidmsgcn"
  },
  "script": {
    "inline": "ctx._index = 'bk-logstash-oidmsgcn_' + (ctx._index.substring('logstash-oidmsgcn_'.length(), ctx._index.length()))"
  }
}

Note that you need to enable dynamic scripting in order for this to work.


问:
How can I determine bandwidth on Windows 7, 8.1 and 10?
So far I have struggled to get MbnInterfaceManager working (see hresult from IMbnInterfaceManager::GetInterfaces when no MBN device exists), so instead I built and debugged an application with no problems from within Visual Studio 2015 that executed this WMI query in C# (see also the Win32_PerfFormattedData_Tcpip_NetworkInterface documentation):

string query = "SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();
```

<p>But then when I deployed the application to Windows 8.1, I receive this error every time the query is executed:</p>

```System.Management.ManagementException: Invalid query
   at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
```

Does anyone have any suggestions on how to resolve this issue?  How can I deploy an application so that it is able to use queries like this?

UPDATE:

Please note that I can build and run the above code (as part of a larger WPF application) from within Visual Studio 2015 on either Windows 7 or Windows 8.1, and I can deploy the same application using ClickOnce onto Windows 7 where it runs successfully.  For some reason when I deploy this application using ClickOnce  onto Windows 8.1, I get that Invalid query message.

答:
I think what I have to do is make sure that the System.Management reference is set to "Copy Local" but I'm not able to test that right now.  If anyone has any better ideas please feel free to let me know.

UPDATE:

It is not possible to use System.Management.dll on Windows 8.1 in the same way it is used on Windows 7 or Windows 10.

I've found that to perform operations similar to the ones I mentioned in my question on Windows 8.1 and Windows 8 phone you need to either get a Windows 8.1 developer license or on Windows 10 set your computer to "Developer Mode" so you can use the Windows.Networking.Connectivity namespace:

```<code>            string connectionProfileInfo = string.Empty;
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

            if (InternetConnectionProfile == null)
            {
                rootPage.NotifyUser("Not connected to Internet\n", NotifyType.StatusMessage);
            }
            else
            {
                connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
                OutputText.Text = connectionProfileInfo;
                rootPage.NotifyUser("Success", NotifyType.StatusMessage);
            }

            // Which calls this function, that allows you to determine how strong the signal is and the associated bandwidth
            string GetConnectionProfile(ConnectionProfile connectionProfile)
            {
                // ...
                    if (connectionProfile.GetSignalBars().HasValue)
                    {
                        connectionProfileInfo += "====================\n";
                        connectionProfileInfo += "Signal Bars: " + connectionProfile.GetSignalBars() + "\n";
                    }
                // ...
            }
</code>```

Please note that you have to make sure your project is either a Window 8.1 PCL or a Windows 8.1 app to be able to reference the namespace.

For details please see https://code.msdn.microsoft.com/windowsapps/network-information-sample-63aaa201

UPDATE 2:

To be able to get bandwidth on Windows 7, 8.1 and 10, I ended up using this code:

```<code>    private int GetMaxBandwidth()
    {
        int maxBandwidth = 0;
        NetworkInterface[] networkIntrInterfaces  = NetworkInterface.GetAllNetworkInterfaces();

        foreach (var networkInterface in networkIntrInterfaces)
        {
            IPv4InterfaceStatistics interfaceStats = networkInterface.GetIPv4Statistics();
            int bytesSentSpeed = (int)(interfaceStats.BytesSent);
            int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived);

            if (bytesSentSpeed + bytesReceivedSpeed > maxBandwidth)
            {
                maxBandwidth = bytesSentSpeed + bytesReceivedSpeed;
            }
        }
    }
</code>```

Body:
So far I have struggled to get MbnInterfaceManager working (see hresult from IMbnInterfaceManager::GetInterfaces when no MBN device exists), so instead I built and debugged an application with no problems from within Visual Studio 2015 that executed this WMI query in C# (see also the Win32_PerfFormattedData_Tcpip_NetworkInterface documentation):

string query = "SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();

But then when I deployed the application to Windows 8.1, I receive this error every time the query is executed:

System.Management.ManagementException: Invalid query
   at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
   at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()

Does anyone have any suggestions on how to resolve this issue?  How can I deploy an application so that it is able to use queries like this?

UPDATE:

Please note that I can build and run the above code (as part of a larger WPF application) from within Visual Studio 2015 on either Windows 7 or Windows 8.1, and I can deploy the same application using ClickOnce onto Windows 7 where it runs successfully.  For some reason when I deploy this application using ClickOnce  onto Windows 8.1, I get that Invalid query message.

Body:
I think what I have to do is make sure that the System.Management reference is set to "Copy Local" but I'm not able to test that right now.  If anyone has any better ideas please feel free to let me know.

UPDATE:

It is not possible to use System.Management.dll on Windows 8.1 in the same way it is used on Windows 7 or Windows 10.

I've found that to perform operations similar to the ones I mentioned in my question on Windows 8.1 and Windows 8 phone you need to either get a Windows 8.1 developer license or on Windows 10 set your computer to "Developer Mode" so you can use the Windows.Networking.Connectivity namespace:

            string connectionProfileInfo = string.Empty;
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

            if (InternetConnectionProfile == null)
            {
                rootPage.NotifyUser("Not connected to Internet\n", NotifyType.StatusMessage);
            }
            else
            {
                connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
                OutputText.Text = connectionProfileInfo;
                rootPage.NotifyUser("Success", NotifyType.StatusMessage);
            }

            // Which calls this function, that allows you to determine how strong the signal is and the associated bandwidth
            string GetConnectionProfile(ConnectionProfile connectionProfile)
            {
                // ...
                    if (connectionProfile.GetSignalBars().HasValue)
                    {
                        connectionProfileInfo += "====================\n";
                        connectionProfileInfo += "Signal Bars: " + connectionProfile.GetSignalBars() + "\n";
                    }
                // ...
            }

Please note that you have to make sure your project is either a Window 8.1 PCL or a Windows 8.1 app to be able to reference the namespace.

For details please see https://code.msdn.microsoft.com/windowsapps/network-information-sample-63aaa201

UPDATE 2:

To be able to get bandwidth on Windows 7, 8.1 and 10, I ended up using this code:

    private int GetMaxBandwidth()
    {
        int maxBandwidth = 0;
        NetworkInterface[] networkIntrInterfaces  = NetworkInterface.GetAllNetworkInterfaces();

        foreach (var networkInterface in networkIntrInterfaces)
        {
            IPv4InterfaceStatistics interfaceStats = networkInterface.GetIPv4Statistics();
            int bytesSentSpeed = (int)(interfaceStats.BytesSent);
            int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived);

            if (bytesSentSpeed + bytesReceivedSpeed > maxBandwidth)
            {
                maxBandwidth = bytesSentSpeed + bytesReceivedSpeed;
            }
        }
    }


答:
You can use the String.replaceFirst method</p>

```<code>String sentence = "{abc} say hello to {def}";
String firstChange = sentence.replaceFirst("\\{abc\\}","you");
String secondChange = firstChagne.replaceFirst("\\{def\\}","Peter");
</code>```

Title: Replace 2 parts in a single string with other string using JAVA

Body:
You can use the String.replaceFirst method

String sentence = "{abc} say hello to {def}";
String firstChange = sentence.replaceFirst("\\{abc\\}","you");
String secondChange = firstChagne.replaceFirst("\\{def\\}","Peter");


问:
Where can I permanently set java heap size on Windows pc?
I recently downloaded the latest Java 1.6 JDK. I'm using VisualVM which came with the SDK to test/monitor my webapp (using Tomcat server) on my local pc. I'm running Windows XP.

Where are the parameters located for setting the min. and max. java heap size? VisualVM indicates that the max. heap is at about 256mb. I looked in the server.xml file for Tomcat, but didn't find any settings in there.

Thank you

答:
You can use the JAVA_OPTS environment variable for dealing with java heap size.
This variable can be added as a environment variable as well as you can define a configuration line in the startup.bat file.

Add the following line in the startup.bat file.

```<code>set JAVA_OPTS=-Xms512m -Xmx512m
</code>```

You can add this as environment variable as said.

Body:
You can use the JAVA_OPTS environment variable for dealing with java heap size.
This variable can be added as a environment variable as well as you can define a configuration line in the startup.bat file.

Add the following line in the startup.bat file.

set JAVA_OPTS=-Xms512m -Xmx512m

You can add this as environment variable as said.


问:
pandas comparing series with numpy float gives TypeError
In pandas, you can do this:

```<code>>>> x = pd.DataFrame([[1,2,3,4], [3,4,5,6]], columns=list('abcd'))
>>> x
   a  b  c  d
0  1  2  3  4
1  3  4  5  6
>>> 2 < x.a
0    False
1     True
Name: a, dtype: bool
</code>```

However, when I try it with it with a numpy float:

```<code>>>> np.float64(2) < x.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/simon/Documents/workspace/rent-my-rez/venv/lib/python2.7/site-packages/pandas/core/ops.py", line 741, in wrapper
    if len(self) != len(other):
TypeError: len() of unsized object
</code>```

Is there some way around this (which doesn't involve casting the numpy float to a regular float), or some way I can monkey patch the Series class from pandas to implement reverse comparison? I've looked around in the source code for where comparison is implemented, but I couldn't find it, so a reference to the location in the code would be very helpful

(I am aware that it is easily fixed by changing the order of comparison, but I am asking this more out of interest, as I would like to understand the source code more)

答: Perhaps you should update your pandas version to the newest, for there is an update for your bugs. I just update it 0.19.2 by pip in Python 2.7.3. Now the bug is fixed.</p>

Body:
In pandas, you can do this:

>>> x = pd.DataFrame([[1,2,3,4], [3,4,5,6]], columns=list('abcd'))
>>> x
   a  b  c  d
0  1  2  3  4
1  3  4  5  6
>>> 2 < x.a
0    False
1     True
Name: a, dtype: bool

However, when I try it with it with a numpy float:

>>> np.float64(2) < x.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/simon/Documents/workspace/rent-my-rez/venv/lib/python2.7/site-packages/pandas/core/ops.py", line 741, in wrapper
    if len(self) != len(other):
TypeError: len() of unsized object

Is there some way around this (which doesn't involve casting the numpy float to a regular float), or some way I can monkey patch the Series class from pandas to implement reverse comparison? I've looked around in the source code for where comparison is implemented, but I couldn't find it, so a reference to the location in the code would be very helpful

(I am aware that it is easily fixed by changing the order of comparison, but I am asking this more out of interest, as I would like to understand the source code more)


问:
How to put plural parameters into url with laravel
I want to build a website with a plural levels in the url. When it gets deeper,I find it difficult to get the parameters in the url.For example, www.example.com/level1/level2, I can get plural parameters level2(plural pages) because I know level1,but as it keeps going like level1/level2/level3,since parameter level2 is unknown value,how should I get level3? Because based on what I'm thinking, there are level4 and level5, at last, should the route file look like Route::get('/{parameter1}/{parameter2}/{parameter3}/{parameter4}','Controller@func')?
Any reply will be appreciated!</p>

答:
Is this what you are looking for?

```<code>{{ url('func', ['level1' => 'val1', 'level2' => 'val2', 'level3' => 'val3']) }} // your link

Route::get('/func', 'YourController@func');
</code>```

your action method

```<code>public function func(Request $request){
  $level3 = $request->get('level3');
}
</code>```

Body:
Is this what you are looking for?

{{ url('func', ['level1' => 'val1', 'level2' => 'val2', 'level3' => 'val3']) }} // your link

Route::get('/func', 'YourController@func');

your action method

public function func(Request $request){
  $level3 = $request->get('level3');
}


问:
Javascript: How to convert exif date time data to timestamp?
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.

The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.

How to solve this problem?

Thanks in advance.

答:
You can do simple string manipulation and create date if the format is always the same, as:</p>

```<code>var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);
</code>```

Body:
You can do simple string manipulation and create date if the format is always the same, as:

var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);


问:
unhashable type: 'numpy.ndarray' error in tensorflow
```<code>data = pd.read_excel("/Users/madhavthaker/Downloads/Reduced_Car_Data.xlsx")

train = np.random.rand(len(data)) < 0.8

data_train = data[train]
data_test = data[~train]

x_train = data_train.ix[:,0:3].values
y_train = data_train.ix[:,-1].values
x_test = data_test.ix[:,0:3].values
y_test = data_test.ix[:,-1].values

y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')
W = tf.Variable(tf.random_normal([3,1]), name='weights')
b = tf.Variable(tf.random_normal([1]), name='bias')
y = tf.matmul(x,W)  + b

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    summary_op = tf.summary.merge_all()
    #Fit all training data
    for epoch in range(1000):
        sess.run(train, feed_dict={x: x_train, y_label: y_train})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(loss, feed_dict={x: x_train, y_label:y_train})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(loss, feed_dict={x: x_train, y_label: y_train})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
</code>```

Here is the error:

```<code>x---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-50102cbac823> in <module>()
      6     #Fit all training data
      7     for epoch in range(1000):
----> 8         sess.run(train, feed_dict={x: x_train, y_label: y_train})
      9
     10         # Display logs per epoch step

TypeError: unhashable type: 'numpy.ndarray'
</code>```

Here are the shapes of both of the numpy arrays that I am inputting:

```<code>y_train.shape = (78,)
x_train.shape = (78, 3)
</code>```

I have no idea what is causing this. All of my shapes match up and I shouldn't have any issues. Let me know if you need any more information.

Edit: From my comment on one of the answers below, it seems as though I had to specify a specific size for my placeholders. None was not satisfactory. When I changed that and re-ran my code, everything worked fine. Still not quite sure why that is.

答:
I think problem is in defining the dictionary.  A dictionary key has to be a 'hashable type', e.g. a number, a string or a tuple are common.  A list or an array don't work:

```<code>In [256]: {'x':np.array([1,2,3])}
Out[256]: {'x': array([1, 2, 3])}
In [257]: x=np.array([1,2,3])
In [258]: {x:np.array([1,2,3])}
...
TypeError: unhashable type: 'numpy.ndarray'
</code>```

I don't know enough of tensorflow to know what these are:

```<code>y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')
</code>```

The error indicates that they are are numpy arrays, not strings.  Does x have a name attribute?

Or maybe the dictionary should be specified as:

```<code>{'x': x_train, 'y_label': y_train}
</code>```

Body:
data = pd.read_excel("/Users/madhavthaker/Downloads/Reduced_Car_Data.xlsx")

train = np.random.rand(len(data)) < 0.8

data_train = data[train]
data_test = data[~train]

x_train = data_train.ix[:,0:3].values
y_train = data_train.ix[:,-1].values
x_test = data_test.ix[:,0:3].values
y_test = data_test.ix[:,-1].values

y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')
W = tf.Variable(tf.random_normal([3,1]), name='weights')
b = tf.Variable(tf.random_normal([1]), name='bias')
y = tf.matmul(x,W)  + b

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    summary_op = tf.summary.merge_all()
    #Fit all training data
    for epoch in range(1000):
        sess.run(train, feed_dict={x: x_train, y_label: y_train})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(loss, feed_dict={x: x_train, y_label:y_train})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(loss, feed_dict={x: x_train, y_label: y_train})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

Here is the error:

x---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-50102cbac823> in <module>()
      6     #Fit all training data
      7     for epoch in range(1000):
----> 8         sess.run(train, feed_dict={x: x_train, y_label: y_train})
      9
     10         # Display logs per epoch step

TypeError: unhashable type: 'numpy.ndarray'

Here are the shapes of both of the numpy arrays that I am inputting:

y_train.shape = (78,)
x_train.shape = (78, 3)

I have no idea what is causing this. All of my shapes match up and I shouldn't have any issues. Let me know if you need any more information.

Edit: From my comment on one of the answers below, it seems as though I had to specify a specific size for my placeholders. None was not satisfactory. When I changed that and re-ran my code, everything worked fine. Still not quite sure why that is.

Body:
I think problem is in defining the dictionary.  A dictionary key has to be a 'hashable type', e.g. a number, a string or a tuple are common.  A list or an array don't work:

In [256]: {'x':np.array([1,2,3])}
Out[256]: {'x': array([1, 2, 3])}
In [257]: x=np.array([1,2,3])
In [258]: {x:np.array([1,2,3])}
...
TypeError: unhashable type: 'numpy.ndarray'

I don't know enough of tensorflow to know what these are:

y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')

The error indicates that they are are numpy arrays, not strings.  Does x have a name attribute?

Or maybe the dictionary should be specified as:

{'x': x_train, 'y_label': y_train}


问:
Reverse radial axes of Matplotlib polar plot
I'm trying to create an astronomical polar plot with a radial axis that starts from -45° on outer line and increases to 90° in the center of the plot. But I didn't find any way to reverse radial axis of the PolarAxes instance. invert_yaxis() method doesn't work at all. Also, there are some hidden methods such as ax.set_rlim() that doesn't have any docs.

Here is my current code:

```<code>fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True)
# ax.invert_yaxis()
ax.set_theta_zero_location('N')
ax.set_ylim(-45, 90)
ax.set_yticks(np.arange(-45, 90, 15))
ax.plot(ras, decs, linestyle='', marker='.')
</code>```

and my plot

答:
It's a little bit "hacky", but if you know the bounds (which it seems like you do as it corresponds to declination) you could do something like:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True)
# ax.invert_yaxis()
ax.set_theta_zero_location('N')
ax.set_rlim(90, -45, 1)
# Note: you must set the end of arange to be slightly larger than 90 or it won't include 90
ax.set_yticks(np.arange(-45, 91, 15))
ax.set_yticklabels(ax.get_yticks()[::-1])
ax.plot([0,10,20], 90-np.array([12,13,14]), linestyle='', marker='.')
fig.show()
</code>```

Body:
I'm trying to create an astronomical polar plot with a radial axis that starts from -45° on outer line and increases to 90° in the center of the plot. But I didn't find any way to reverse radial axis of the PolarAxes instance. invert_yaxis() method doesn't work at all. Also, there are some hidden methods such as ax.set_rlim() that doesn't have any docs.

Here is my current code:

fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True)
# ax.invert_yaxis()
ax.set_theta_zero_location('N')
ax.set_ylim(-45, 90)
ax.set_yticks(np.arange(-45, 90, 15))
ax.plot(ras, decs, linestyle='', marker='.')

and my plot

Body:
It's a little bit "hacky", but if you know the bounds (which it seems like you do as it corresponds to declination) you could do something like:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True)
# ax.invert_yaxis()
ax.set_theta_zero_location('N')
ax.set_rlim(90, -45, 1)
# Note: you must set the end of arange to be slightly larger than 90 or it won't include 90
ax.set_yticks(np.arange(-45, 91, 15))
ax.set_yticklabels(ax.get_yticks()[::-1])
ax.plot([0,10,20], 90-np.array([12,13,14]), linestyle='', marker='.')
fig.show()


问:
How can i skip files that does not exist file in the repository using python?
I want to download xml file from issue tracking system one by one.It produces error message when file not exist in the repository. I include the python script to better understand my problem.

My code:

```<code>import urllib.request
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    s=urllib.request.urlopen(url)
    contents = s.read()
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)

file.close()
</code>```

Stack Track:

```<code>Traceback (most recent call last):
  File "/PhP/Learning/xmldownlaod.py", line 10, in <module>
    s=urllib.request.urlopen(url)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
</code>```

答:
Python uses "try except" blocks for error handling</p>

```<code>import urllib.request
from urllib.error import URLError # the docs say this is the base error you need to catch
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    try:
        s=urllib.request.urlopen(url)
        contents = s.read()
    except URLError:
        print('an error occurred while fetching: "{}"'.format(url))
        continue # skip this url and proceed to the next
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to download xml file from issue tracking system one by one.It produces error message when file not exist in the repository. I include the python script to better understand my problem.

My code:

import urllib.request
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    s=urllib.request.urlopen(url)
    contents = s.read()
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)

file.close()

Stack Track:

Traceback (most recent call last):
  File "/PhP/Learning/xmldownlaod.py", line 10, in <module>
    s=urllib.request.urlopen(url)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

Body:
Python uses "try except" blocks for error handling

import urllib.request
from urllib.error import URLError # the docs say this is the base error you need to catch
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    try:
        s=urllib.request.urlopen(url)
        contents = s.read()
    except URLError:
        print('an error occurred while fetching: "{}"'.format(url))
        continue # skip this url and proceed to the next
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)


问:
Format text output of script to html
I have the following shell script:

```<code>#!/bin/bash
f='/tmp/cases.txt'
[ -s "$f" ] || printf '%s   |\t%s   |\t%s                    |\n' '#' 'Case Number' 'Date Opened' > "$f"
n=$(cat /tmp/cases.txt | grep 17* |wc -l)
read -p "Enter your SR number: " SR
printf '%d   |\t%d   |\t%s   |\n' "$n" "$SR" "$(date)" >> "$f"
echo -e "-------------------------------------------------------" >> "$f"
</code>```

This outputs:

```<code>#   |   Case Number   | Date Opened                    |
0   |   17416230803   | Wed Mar 29 02:26:24 IST 2017   |
-------------------------------------------------------
1   |   17416230802   | Wed Mar 29 02:32:28 IST 2017   |
-------------------------------------------------------
2   |   17416230801   | Wed Mar 29 02:32:33 IST 2017   |
-------------------------------------------------------
</code>```

Now, I want to format this output to a html file. The same way how I see in this text output.
And if this could generate a link, which I could paste in my browser that would even more cool. I have barely any idea on html so it would be a lot helpful.

Thanks.

答:
You can use the ansi2html.sh script to generate html file from console output. For example, you can generate the output of ls -l as html by:

```<code>ls -l | ./ansi2html.sh > ls.html
</code>```

Please note you can define the generated file path yourself, which means the "link" is up to you.

p.s. In MacOS, you need to install gawk and gnu-sed before running ansi2html.sh

Title: Format text output of script to html

Body:
I have the following shell script:

#!/bin/bash
f='/tmp/cases.txt'
[ -s "$f" ] || printf '%s   |\t%s   |\t%s                    |\n' '#' 'Case Number' 'Date Opened' > "$f"
n=$(cat /tmp/cases.txt | grep 17* |wc -l)
read -p "Enter your SR number: " SR
printf '%d   |\t%d   |\t%s   |\n' "$n" "$SR" "$(date)" >> "$f"
echo -e "-------------------------------------------------------" >> "$f"

This outputs:

#   |   Case Number   | Date Opened                    |
0   |   17416230803   | Wed Mar 29 02:26:24 IST 2017   |
-------------------------------------------------------
1   |   17416230802   | Wed Mar 29 02:32:28 IST 2017   |
-------------------------------------------------------
2   |   17416230801   | Wed Mar 29 02:32:33 IST 2017   |
-------------------------------------------------------

Now, I want to format this output to a html file. The same way how I see in this text output.
And if this could generate a link, which I could paste in my browser that would even more cool. I have barely any idea on html so it would be a lot helpful.

Thanks.

Body:
You can use the ansi2html.sh script to generate html file from console output. For example, you can generate the output of ls -l as html by:

ls -l | ./ansi2html.sh > ls.html

Please note you can define the generated file path yourself, which means the "link" is up to you.

p.s. In MacOS, you need to install gawk and gnu-sed before running ansi2html.sh


问:
Why StreamReader returns string instead of byte array
Two related questions:

Why did they choose to return string from StreamReader.ReadToEnd() instead of byte[]?

I know I can convert it using System.Text.Encoding, but exactly which encoding should I use? UTF8, UTF7, ASCII or Unicode? I'm dealing with binary files.

Note: I was asked for clarification. It is just that the word stream gives an impression of byte-level...well...stream of data (think network stream, file stream, buffer, none of them is supposed to be a char-type concept). As correctly indicated by Joel in his answer, this is more of a naming issue than anything else.

答:
"Why" questions are rarely good fodder for Stack Overflow, since the only ones who can really answer them are those on the design committee for the product.

However, in this case we can at least give you a good indication by pointing you to the StreamReader documentation, where you'll find this:

Implements a TextReader that reads characters from a byte stream in a particular encoding.

So we see, then, that working with text rather than bytes is what StreamReader is all about. Maybe you would ask why it's named "StreamReader" rather than "TextStreamReader", but then I'd have to refer you back to my first sentence.

As for getting a byte array... it depends on what you want to do. .Net uses Unicode for it's strings, but the underlying stream might be something different, and whatever you plan to do with this data might demand a different encoding entirely.

In this case, though, you have binary files, and you want a Byte[]. Rather than messing with streams at all, just look at File.ReadAllBytes(). If you have to deal with streams you might also want a BinaryReader.


问:
Complex Type in Subsonic 3
I am going to use subsonic 3 in  a large enterprise winform application.
what i saw in my personal tests is that subsonic cannot handle complex type references well.
for example if we have an ADDRESS complex type in PERSON object , as far as i saw subsonic just created the PERSON table and is not caring about the Address property of it !

i was wondering how can i solve it ?

Secondly, we have inheritance in our objects, how subsonic can handle it with table-per-subclass strategy?

答:
SubSonic isn't well suited to these scenarios. Regarding complex types you could write a service/repository to handle saving and building these types, but there's no pre-existing way of mapping this to the database.
The same goes for inheritance schemes.
You might want to look at more full-featured O/RM like NHibernate or EF.</p>

Title: Complex Type in Subsonic 3


问:
Resize css image to fit
So im putting list of types and each one has an image. As you can see the list below has the water image cut.  How can I fix this?

I have a class for the water text so it can display the text and im trying to add it to a html list.

this is my class code in css

```<code>.water{
    background: url('../images/water.png');
    object-fit: contain;
    background-repeat: no-repeat;
    max-width:100%;
    height:auto;
    text-indent: -9999px;
}
</code>```

This worked thanks to HolyMoly

"object-fit is used directly on img tags to my understanding, I think you want background-size: contain or background-size: cover since you are not applying the css to an image tag, rather using the image as a background" – HolyMoly

答:
kindly check background-size:contain or background: url('../images/water.png') 50px 50px;
directly mention you size of image</p>

Title: Resize css image to fit

Body:
So im putting list of types and each one has an image. As you can see the list below has the water image cut.  How can I fix this?

I have a class for the water text so it can display the text and im trying to add it to a html list.

this is my class code in css

.water{
    background: url('../images/water.png');
    object-fit: contain;
    background-repeat: no-repeat;
    max-width:100%;
    height:auto;
    text-indent: -9999px;
}

This worked thanks to HolyMoly

"object-fit is used directly on img tags to my understanding, I think you want background-size: contain or background-size: cover since you are not applying the css to an image tag, rather using the image as a background" – HolyMoly


问:
How To Get Chat Id of Users on telegram by there Mobile Number in PHP?
I have gone through many forums and API of telegram also.
But could not get the proper answer.

Well here is my main question.
I have list of users with their mobile numbers in my database and from all those, I want to send them messages on their telegram. So for that I will need their chat ID. How can I retrieve that by their MobileNumber? If I will have chat id, I am able to send message to them by using the following reference.

Telegram php example send message

I have visited the following link to get the chat id by manually from BOT by user itself. But I want automatic from script.

How to obtain Telegram chat_id for a specific user?

Thanks.

答:
By Telegram bot you can send messages only to users that started chat with your bot. you can obtain their chat_id (not phone number) from received query.

So you can not send message to another people even if you have their phone numbers.


问:
notepad++ regex to replace multiple values with different replacement
I have lots of text that have url encoding that needs to be fixed.

As it's rather tedious to keep doing find/replace for every one,

Does anyone have a regex to replace multiple characters at a time?

Example:

Replace...

%20 with a space

%5B with [

%5D with ]

%28 with (

%29 with )

答:
Find by the following regex:

```<code>(%20)|(%5B)|(%5D)|(%28)|(%29)
</code>```

and replace by this:

```<code>(?1 )(?2\[)(?3\[)(?4\()(?5\))
</code>```

Explanation:

```<code>(?1replacementA)(?2replacmentB)(?3replacmentC)....
</code>```

where ?1 indicates to replace first capture group value %20 by

'    replacementA'

where ?2 indicates to replace second capture group %5B by

    'replacementB'

where ?3 indicates to replace third capture group %28 by

    'replacementC'

It is possible since notepad++ 6

Body:
Find by the following regex:

(%20)|(%5B)|(%5D)|(%28)|(%29)

and replace by this:

(?1 )(?2\[)(?3\[)(?4\()(?5\))

Explanation:

(?1replacementA)(?2replacmentB)(?3replacmentC)....

where ?1 indicates to replace first capture group value %20 by

'    replacementA'

where ?2 indicates to replace second capture group %5B by

    'replacementB'

where ?3 indicates to replace third capture group %28 by

    'replacementC'

It is possible since notepad++ 6


问:
How to calculate the optimal Sequence Cache size for a multithreaded application inserting a large amount of data?
I have a multi-threaded application that uses 10 threads, each of which on average result in an insert of 40K rows into a table. These inserts will occur 24/7 around the clock with no pauses.

I ran some performance tests and noted the following:

With CACHE 20 and single threaded, each insert took about 3.5 seconds on average

With CACHE 20 and 10 threads, each insert took 100 seconds on average

After removing the primary key and the sequence, each insert, regardless of the number of threads used, took 3.1 seconds.

With CACHE 400000 and 10 threads, each insert took 5.6 seconds on average. (Incidentally, the average originally was 8, then dropped down to 5.6 over time)

I'm performing an INSERT like this:

```
INSERT INTO foo (id, bar, baz)
SELECT (foo_id_seq.nextval, bar, baz)
FROM (
    SELECT bar, baz
    FROM ...
)
```

Given my constraints of 10 threads processing 40K records each on average, how can I calculate the optimal cache size of a sequence?

I'm tempted to set the cache size = (10 threads * 40K records) == 400,000, but I would be worried about any trade offs that I haven't read about in the docs.

Moreover, the insert with 400K cache size is still 100% worse than the insert with no sequence/pk. Granted this is an acceptable time.

The docs say:

The CACHE clause preallocates a set of sequence numbers and keeps them in memory so that sequence numbers can be accessed faster. When the last of the sequence numbers in the cache has been used, the database reads another set of numbers into the cache.

Sequence numbers can be kept in the sequence cache in the System Global Area (SGA). Sequence numbers can be accessed more quickly in the sequence cache than they can be read from disk.

Follow these guidelines for fast access to all sequence numbers: Be sure the sequence cache can hold all the sequences used concurrently by your applications. Increase the number of values for each sequence held in the sequence cache.

答: I thinks with a 3.5 second insert time, your cache size is largely irrelevant! I would look at where the time is being spent; and I would start with an execution plan (or preferably a SQL Monitor report ) for the query.</p>

Body:
I have a multi-threaded application that uses 10 threads, each of which on average result in an insert of 40K rows into a table. These inserts will occur 24/7 around the clock with no pauses.

I ran some performance tests and noted the following:

With CACHE 20 and single threaded, each insert took about 3.5 seconds on average

With CACHE 20 and 10 threads, each insert took 100 seconds on average

After removing the primary key and the sequence, each insert, regardless of the number of threads used, took 3.1 seconds.

With CACHE 400000 and 10 threads, each insert took 5.6 seconds on average. (Incidentally, the average originally was 8, then dropped down to 5.6 over time)

I'm performing an INSERT like this:

INSERT INTO foo (id, bar, baz)
SELECT (foo_id_seq.nextval, bar, baz)
FROM (
    SELECT bar, baz
    FROM ...
)

Given my constraints of 10 threads processing 40K records each on average, how can I calculate the optimal cache size of a sequence?

I'm tempted to set the cache size = (10 threads * 40K records) == 400,000, but I would be worried about any trade offs that I haven't read about in the docs.

Moreover, the insert with 400K cache size is still 100% worse than the insert with no sequence/pk. Granted this is an acceptable time.

The docs say:

The CACHE clause preallocates a set of sequence numbers and keeps them in memory so that sequence numbers can be accessed faster. When the last of the sequence numbers in the cache has been used, the database reads another set of numbers into the cache.

Sequence numbers can be kept in the sequence cache in the System Global Area (SGA). Sequence numbers can be accessed more quickly in the sequence cache than they can be read from disk.

Follow these guidelines for fast access to all sequence numbers: Be sure the sequence cache can hold all the sequences used concurrently by your applications. Increase the number of values for each sequence held in the sequence cache.


问:
How to capture the pointermotion event and limit the pointer in an area?
I'm running two fullscreen apps on two monitors on Ubuntu 16.10. app1 needs the pointer and must be focused all time, so I need to lock the pointer in app1.

I had written a tool to grab the pointer like this:

```<code>#include <stdio.h>
#include <X11/Xlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
Display *display;
XEvent xevent;
Window window;
int x,y;
void setPos(int x,int y){
  XWarpPointer(display,None,window,0,0,0,0,x,y);
  XFlush(display);
}
int main(int argc, char **argv){
  if( (display = XOpenDisplay(NULL)) == NULL )
    return -1;
  window = DefaultRootWindow(display);

  XAllowEvents(display, AsyncBoth, CurrentTime);
  XGrabPointer(display,window,0,PointerMotionMask,GrabModeAsync,GrabModeAsync,None,None,CurrentTime);
  while(1) {
    XNextEvent(display, &xevent);
    switch (xevent.type) {
        case MotionNotify:
          if(xevent.xmotion.x_root>1920){
             setPos(1920,xevent.xmotion.y_root);
          }
        break;
     }
  }
  return 0;
}
</code>```

This tool can capture the pointer's event and limit the pointer stay in app1, but the pointer can't operate anything in app1. All pointer event except motion are not working. Is there any suggestion to the codes? Or any other idea to finish the work?

答:
finally Xephyr has solved the problem.
use this command to run Xephyr:

```<code>/usr/bin/Xephyr :1 -softCursor -name aaa -screen 1920x1080 -keybd   evdev,,device=/dev/input/eventkb,xkbrules=evdev,xkbmodel=evdev,xkblayout=us -mouse evdev,5,device=/dev/input/$eventmouse  -retro
</code>```

Xephyr will start a new Display  and grab the keyboard and mouse,then you can run your app in display :1.

btw:
1 the event number of keyboard and mouse maybe changed when you re plug the device,so make a shell script to run Xephey and get the event number in your script like this:

```<code>eventkb=`grep -A5 "pci0000:00/0000:00:14.0/usb2/2-5/2-5:1.0/0003:1A81:1007" /proc/bus/input/devices | grep 'H: Handlers=' | grep --only-matching -e 'event[0-9]*'`
</code>```

2 if you don't want to run Xephyr by root,you will receive an error about permission to grab the keyboard and mouse. you can create file /etc/udev/rules.d/my.rules and put SUBSYSTEM=="input", OWNER="username", GROUP="usernamer" in it. then you can run Xephyr by username. maybe you need to relogin or restart.

Body:
I'm running two fullscreen apps on two monitors on Ubuntu 16.10. app1 needs the pointer and must be focused all time, so I need to lock the pointer in app1.

I had written a tool to grab the pointer like this:

#include <stdio.h>
#include <X11/Xlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
Display *display;
XEvent xevent;
Window window;
int x,y;
void setPos(int x,int y){
  XWarpPointer(display,None,window,0,0,0,0,x,y);
  XFlush(display);
}
int main(int argc, char **argv){
  if( (display = XOpenDisplay(NULL)) == NULL )
    return -1;
  window = DefaultRootWindow(display);

  XAllowEvents(display, AsyncBoth, CurrentTime);
  XGrabPointer(display,window,0,PointerMotionMask,GrabModeAsync,GrabModeAsync,None,None,CurrentTime);
  while(1) {
    XNextEvent(display, &xevent);
    switch (xevent.type) {
        case MotionNotify:
          if(xevent.xmotion.x_root>1920){
             setPos(1920,xevent.xmotion.y_root);
          }
        break;
     }
  }
  return 0;
}

This tool can capture the pointer's event and limit the pointer stay in app1, but the pointer can't operate anything in app1. All pointer event except motion are not working. Is there any suggestion to the codes? Or any other idea to finish the work?

Body:
finally Xephyr has solved the problem.
use this command to run Xephyr:

/usr/bin/Xephyr :1 -softCursor -name aaa -screen 1920x1080 -keybd   evdev,,device=/dev/input/eventkb,xkbrules=evdev,xkbmodel=evdev,xkblayout=us -mouse evdev,5,device=/dev/input/$eventmouse  -retro

Xephyr will start a new Display  and grab the keyboard and mouse,then you can run your app in display :1.

btw:
1 the event number of keyboard and mouse maybe changed when you re plug the device,so make a shell script to run Xephey and get the event number in your script like this:

eventkb=`grep -A5 "pci0000:00/0000:00:14.0/usb2/2-5/2-5:1.0/0003:1A81:1007" /proc/bus/input/devices | grep 'H: Handlers=' | grep --only-matching -e 'event[0-9]*'`

2 if you don't want to run Xephyr by root,you will receive an error about permission to grab the keyboard and mouse. you can create file /etc/udev/rules.d/my.rules and put SUBSYSTEM=="input", OWNER="username", GROUP="usernamer" in it. then you can run Xephyr by username. maybe you need to relogin or restart.


问:
After map.data.loadGeoJson, events of circle is covered by polygons of Geo Json
After I load Geo Json file by map.data.loadGeoJson(), makers and circles are covered by polygons and their event cannot be clicked.
Here is sample codes. How should I do? and is there any other way to disable "clickable" of these polygons? Thank you.</p>

```<code>map.data.loadGeoJson(samplejson.json);
 // Add circle overlay and bind to marker
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 1600, // 10 miles in metres
                    fillColor: fill_color_val,
                    strokeColor: '#F5F5F5',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: latlng,
                    title: data[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                var infoWindow = new google.maps.InfoWindow({
                    content: "<div>Hello! World</div>",
                    maxWidth: 500
                });
                google.maps.event.addListener(circle, 'click', getInfoCallback(latlng, 14));
</code>```

答: use zindex to other layers not to cover by map.data</p>

Body:
After I load Geo Json file by map.data.loadGeoJson(), makers and circles are covered by polygons and their event cannot be clicked.
Here is sample codes. How should I do? and is there any other way to disable "clickable" of these polygons? Thank you.

map.data.loadGeoJson(samplejson.json);
 // Add circle overlay and bind to marker
                var circle = new google.maps.Circle({
                    map: map,
                    radius: 1600, // 10 miles in metres
                    fillColor: fill_color_val,
                    strokeColor: '#F5F5F5',
                    strokeWeight: 2,
                    fillOpacity: 1,
                });

                var marker = new google.maps.Marker({
                    position: latlng,
                    title: data[i].Author,
                    draggable: false,
                    map: map
                });
                marker.setVisible(false);

                circle.bindTo('center', marker, 'position');

                var infoWindow = new google.maps.InfoWindow({
                    content: "
Hello! World
",
                    maxWidth: 500
                });
                google.maps.event.addListener(circle, 'click', getInfoCallback(latlng, 14));


问:
Trouble installiing Shogun on Ubuntu
When I try to add the ppa to my system as

```<code>sudo add-apt-repository ppa:shogun-toolbox/stable
sudo apt-get update
</code>```

I get the following messages:

```<code>W: The repository 'http://ppa.launchpad.net/shogun-toolbox/stable/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/shogun-toolbox/stable/ubuntu/dists/xenial/main/binary-amd64/Packages 404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

How do I resolve these issues?

答:
if you check out the stable ppa repository you'll see that stable shogun packages are only available at this very moment for trusty.

if you want to use shogun on xenial (based on your logs) your current option is just to use the nightly ppa. with the new release this will change of course.

Title: Trouble installiing Shogun on Ubuntu

Body:
When I try to add the ppa to my system as

sudo add-apt-repository ppa:shogun-toolbox/stable
sudo apt-get update

I get the following messages:

W: The repository 'http://ppa.launchpad.net/shogun-toolbox/stable/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/shogun-toolbox/stable/ubuntu/dists/xenial/main/binary-amd64/Packages 404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

How do I resolve these issues?


问:
Diagnosing RangeError: Maximum call stack size exceeded in React KeyEscapeUtils
Background

Our webapp is written with React and Redux using the official react-redux bindings. Another primary library used in this web app is PaperJS. We recently transitioned this to being a Redux app, though it has used React for a while.

The Problem

Refreshing sometimes (usually every other refresh) causes a

```<code>RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at Object.unescape (KeyEscapeUtils.js:49)
at flattenSingleChildIntoContext (flattenChildren.js:32)
at flattenChildren.js:53
at traverseAllChildrenImpl (traverseAllChildren.js:69)
at traverseAllChildrenImpl (traverseAllChildren.js:85)
at traverseAllChildren (traverseAllChildren.js:157)
at flattenChildren (flattenChildren.js:52)
at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:209)
at ReactDOMComponent._updateChildren (ReactMultiChild.js:315)
</code>```

Here's the React source code where it's failing:

```<code>return ('' + keySubstring).replace(unescapeRegex, function (match) {
  return unescaperLookup[match];
});
</code>```

and in context:

```<code>/**
 * Unescape and unwrap key for human-readable display
 *
 * @param {string} key to unescape.
 * @return {string} the unescaped key.
 */
function unescape(key) {
  var unescapeRegex = /(=0|=2)/g;
  var unescaperLookup = {
    '=0': '=',
    '=2': ':'
  };
  var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);

  return ('' + keySubstring).replace(unescapeRegex, function (match) {
    return unescaperLookup[match];
  });
}
</code>```

This is probably indicative that somewhere I'm misusing React in my code, but since the stacktrace does not include references to any of my own code, I'm not sure what to look for. It seems to be an infinite loop of re-rendering, and I'm suspicious that it might be due to an improperly placed call to setState.

The Question

Is my suspicion likely? How can I further diagnose this issue, given that my own codebase is fairly extensive? What does it mean that this failed in KeyEscapeUtils?

答:
I don't think the place that it failed is significant, since you seem to be caught in an infinite loop, and this just happens to be the spot that the call stack limit is exceeded.

In order to diagnose, I would try turning on 'Pause on Exceptions' in chrome dev tools, if it's not already, and looking further up the stack trace for your own code when it pauses.

You are correct that improper setState calls could be causing this. For instance, if you were calling setState unchecked in componentDidUpdate or render. It's curious though that it only happens sometimes.

Body:
Background

Our webapp is written with React and Redux using the official react-redux bindings. Another primary library used in this web app is PaperJS. We recently transitioned this to being a Redux app, though it has used React for a while.

The Problem

Refreshing sometimes (usually every other refresh) causes a

RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at Object.unescape (KeyEscapeUtils.js:49)
at flattenSingleChildIntoContext (flattenChildren.js:32)
at flattenChildren.js:53
at traverseAllChildrenImpl (traverseAllChildren.js:69)
at traverseAllChildrenImpl (traverseAllChildren.js:85)
at traverseAllChildren (traverseAllChildren.js:157)
at flattenChildren (flattenChildren.js:52)
at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:209)
at ReactDOMComponent._updateChildren (ReactMultiChild.js:315)

Here's the React source code where it's failing:

return ('' + keySubstring).replace(unescapeRegex, function (match) {
  return unescaperLookup[match];
});

and in context:

/**
 * Unescape and unwrap key for human-readable display
 *
 * @param {string} key to unescape.
 * @return {string} the unescaped key.
 */
function unescape(key) {
  var unescapeRegex = /(=0|=2)/g;
  var unescaperLookup = {
    '=0': '=',
    '=2': ':'
  };
  var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);

  return ('' + keySubstring).replace(unescapeRegex, function (match) {
    return unescaperLookup[match];
  });
}

This is probably indicative that somewhere I'm misusing React in my code, but since the stacktrace does not include references to any of my own code, I'm not sure what to look for. It seems to be an infinite loop of re-rendering, and I'm suspicious that it might be due to an improperly placed call to setState.

The Question

Is my suspicion likely? How can I further diagnose this issue, given that my own codebase is fairly extensive? What does it mean that this failed in KeyEscapeUtils?


问:
Navigation Bar Transparency
Could Anybody help me with that, I have found this code here in this website, That code helps me to transparent the navigation bar:

```<code>self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
</code>```

The problem is how could I get the default navigation bar?
I have two ViewController The first I want it with normal navigation bar and the second with transparent navigation bar, and when I get back to the first I need to get default navigation bar back :).

答: I was working on an app which needed 3 navigation styles transparent, translucent and default. After all the investigation and tests finally I had to create a custom navigation bar. I have wasted almost a week to finally use this approach.  </p>

Title: Navigation Bar Transparency

Body:
Could Anybody help me with that, I have found this code here in this website, That code helps me to transparent the navigation bar:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear

The problem is how could I get the default navigation bar?
I have two ViewController The first I want it with normal navigation bar and the second with transparent navigation bar, and when I get back to the first I need to get default navigation bar back :).


问:
JSF - Create a Dynamic Menu by using AJAX & selectOneListbox
What I'd like to do is simple to explain :

bean

```<code>@ManagedBean
@ViewScoped
public class Articles {
    private String selectedMenu;

    @PostConstruct
    public void init() {
        if(selectedMenu==null || selectedMenu.trim().isEmpty()) {
            this.selectedMenu="0";
        }
    }

    public String getSelectedMenu() { return selectedMenu; }
    public void setSelectedMenu(String selectedMenu) { this.selectedMenu = selectedMenu; }
}
</code>```

page

```<code><h:selectOneListbox onchange="..?? ajax call that render on loadMenu and pass the value of the focused listbox to Articles Bean" id="category" size="0" >
    <f:selectItem itemLabel="first" itemValue="0" />
    <f:selectItem itemLabel="second" itemValue="1" />
    <f:selectItem itemLabel="third" itemValue="2" />
</h:selectOneListbox>

<h:panelGroup layout="block" id="loadMenu">
    <h:panelGroup rendered="#{articles.selectedMenu=='0'}">
        MENU 0
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='1'}">
        MENU 1
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='2'}">
        MENU 2
    </h:panelGroup>
</h:panelGroup>
</code>```

When I change the value of the listbox, the menu should change dinamically (by calling some function on the server). I think that the code above expresses what I'm looking for.

I must know how call it using the onchange option. Is it possible?

Cheers

UPDATE

```<code><h:panelGroup layout="block">
    <h:selectOneListbox styleClass="article_combo" size="0" id="selectedMenu" >
        <f:selectItem itemLabel="first" itemValue="0" />
        <f:selectItem itemLabel="second" itemValue="1" />
        <f:selectItem itemLabel="third" itemValue="2" />

        <f:ajax event="change" execute="@this" render="loadMenu" />
    </h:selectOneListbox>
</h:panelGroup>

<h:panelGroup layout="block" id="loadMenu">
    <h:panelGroup rendered="#{articles.selectedMenu=='0'}">
        MENU 0
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='1'}">
        MENU 1
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='2'}">
        MENU 2
    </h:panelGroup>
</h:panelGroup>
</code>```

答:
You can use the ajax support built in to JSF 2 to achieve this.  To do this nest an f:ajax tag in your h:selectOneListbox tag.  The f:ajax tag should look like:

```<code><f:ajax render="loadMenu" execute="@this" />
</code>```

This should process the changed value in your list box, and re-render the panelGroup.

for further details, see:
http://mkblog.exadel.com/2010/04/learning-jsf-2-ajax-in-jsf-using-fajax-tag/

Body:
What I'd like to do is simple to explain :

bean

@ManagedBean
@ViewScoped
public class Articles {
    private String selectedMenu;

    @PostConstruct
    public void init() {
        if(selectedMenu==null || selectedMenu.trim().isEmpty()) {
            this.selectedMenu="0";
        }
    }

    public String getSelectedMenu() { return selectedMenu; }
    public void setSelectedMenu(String selectedMenu) { this.selectedMenu = selectedMenu; }
}

page

<h:selectOneListbox onchange="..?? ajax call that render on loadMenu and pass the value of the focused listbox to Articles Bean" id="category" size="0" >
    <f:selectItem itemLabel="first" itemValue="0" />
    <f:selectItem itemLabel="second" itemValue="1" />
    <f:selectItem itemLabel="third" itemValue="2" />
</h:selectOneListbox>

<h:panelGroup layout="block" id="loadMenu">
    <h:panelGroup rendered="#{articles.selectedMenu=='0'}">
        MENU 0
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='1'}">
        MENU 1
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='2'}">
        MENU 2
    </h:panelGroup>
</h:panelGroup>

When I change the value of the listbox, the menu should change dinamically (by calling some function on the server). I think that the code above expresses what I'm looking for.

I must know how call it using the onchange option. Is it possible?

Cheers

UPDATE

<h:panelGroup layout="block">
    <h:selectOneListbox styleClass="article_combo" size="0" id="selectedMenu" >
        <f:selectItem itemLabel="first" itemValue="0" />
        <f:selectItem itemLabel="second" itemValue="1" />
        <f:selectItem itemLabel="third" itemValue="2" />

        <f:ajax event="change" execute="@this" render="loadMenu" />
    </h:selectOneListbox>
</h:panelGroup>

<h:panelGroup layout="block" id="loadMenu">
    <h:panelGroup rendered="#{articles.selectedMenu=='0'}">
        MENU 0
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='1'}">
        MENU 1
    </h:panelGroup>

    <h:panelGroup rendered="#{articles.selectedMenu=='2'}">
        MENU 2
    </h:panelGroup>
</h:panelGroup>

Body:
You can use the ajax support built in to JSF 2 to achieve this.  To do this nest an f:ajax tag in your h:selectOneListbox tag.  The f:ajax tag should look like:

<f:ajax render="loadMenu" execute="@this" />

This should process the changed value in your list box, and re-render the panelGroup.

for further details, see:
http://mkblog.exadel.com/2010/04/learning-jsf-2-ajax-in-jsf-using-fajax-tag/


问:
Overriding javascript function in Odoo 9
I want to disable demo data in sales dashboard in Odoo 9.0. I identified the exact lines in javascript that should be changed to work as I expect.
This is original code from sales_team/(...)/sales_team_dashboard.js

```<code>render: function() {
    var super_render = this._super;
    var self = this;

    return this.fetch_data().then(function(result){
        self.show_demo = result && result['nb_opportunities'] == 0;

        var sales_dashboard = QWeb.render('sales_team.SalesDashboard',{
            widget: self,
            show_demo: self.show_demo,
            values: result,
        });
        super_render.call(self);
        $(sales_dashboard).prependTo(self.$el);
    });
},
</code>```

All I need to change is, actually, this line:

```<code>self.show_demo = result && result['nb_opportunities'] == 0;
</code>```

as follows

```<code>self.show_demo = false;
</code>```

I tested the code and it works. However, I would like to keep the original Odoo modules untouched so I would like to override the original javascript from within my own module.
I tried this:

```<code>odoo.define('my_module.dashboard', function(require) {
"use strict";

console.log('dashboard #1');

var dashboard = require('sales_team.dashboard');

console.log('dashboard #2');
var SalesTeamDashboardView = dashboard.extend({
    template: 'sales_team.SalesDashboard',

    render: function() {
        console.log('dashboard #3');
        var super_render = this._super;
        var self = this;

        return this.fetch_data().then(function(result){
            console.log('dashboard #4');
            self.show_demo = false;

            var sales_dashboard = QWeb.render(template, {
                widget: self,
                show_demo: self.show_demo,
                values: result,
            });
            super_render.call(self);
            console.log('dashboard #5');
            $(sales_dashboard).prependTo(self.$el);
        });
    },
});

console.log('dashboard #6');
//core.view_registry.add('sales_team_dashboard', SalesTeamDashboardView);

return SalesTeamDashboardView;

});
</code>```

This appears in console after loading the page.

```<code>dashboard #1  web.assets_backend.js:4447
dashboard #2  web.assets_backend.js:4447
dashboard #6  web.assets_backend.js:4447
</code>```

It seems that the javascript has been run but the render function has not been overriden. What can I do to override it? Can I check if the function is not overriden later by another module?

Is there something I did wrong? As I am new to JS I am aware I might use javascript anti-patterns. Please feel free to point those out.

答:
Please try the below code:</p>

```<code>odoo.define('my_module.dashboard', function(require) {
"use strict";

console.log('dashboard #1');

var dashboard = require('sales_team.dashboard');

console.log('dashboard #2');
var SalesTeamDashboardView = dashboard.include({

    render: function() {
        console.log('dashboard #3');
        var super_render = this._super;
        var self = this;

        return this.fetch_data().then(function(result){
            console.log('dashboard #4');
            self.show_demo = false;

            var sales_dashboard = QWeb.render(template, {
                widget: self,
                show_demo: self.show_demo,
                values: result,
            });
            super_render.call(self);
            console.log('dashboard #5');
            $(sales_dashboard).prependTo(self.$el);
        });
    },
    });

});
</code>```

Body:
I want to disable demo data in sales dashboard in Odoo 9.0. I identified the exact lines in javascript that should be changed to work as I expect.
This is original code from sales_team/(...)/sales_team_dashboard.js

render: function() {
    var super_render = this._super;
    var self = this;

    return this.fetch_data().then(function(result){
        self.show_demo = result && result['nb_opportunities'] == 0;

        var sales_dashboard = QWeb.render('sales_team.SalesDashboard',{
            widget: self,
            show_demo: self.show_demo,
            values: result,
        });
        super_render.call(self);
        $(sales_dashboard).prependTo(self.$el);
    });
},

All I need to change is, actually, this line:

self.show_demo = result && result['nb_opportunities'] == 0;

as follows

self.show_demo = false;

I tested the code and it works. However, I would like to keep the original Odoo modules untouched so I would like to override the original javascript from within my own module.
I tried this:

odoo.define('my_module.dashboard', function(require) {
"use strict";

console.log('dashboard #1');

var dashboard = require('sales_team.dashboard');

console.log('dashboard #2');
var SalesTeamDashboardView = dashboard.extend({
    template: 'sales_team.SalesDashboard',

    render: function() {
        console.log('dashboard #3');
        var super_render = this._super;
        var self = this;

        return this.fetch_data().then(function(result){
            console.log('dashboard #4');
            self.show_demo = false;

            var sales_dashboard = QWeb.render(template, {
                widget: self,
                show_demo: self.show_demo,
                values: result,
            });
            super_render.call(self);
            console.log('dashboard #5');
            $(sales_dashboard).prependTo(self.$el);
        });
    },
});

console.log('dashboard #6');
//core.view_registry.add('sales_team_dashboard', SalesTeamDashboardView);

return SalesTeamDashboardView;

});

This appears in console after loading the page.

dashboard #1  web.assets_backend.js:4447
dashboard #2  web.assets_backend.js:4447
dashboard #6  web.assets_backend.js:4447

It seems that the javascript has been run but the render function has not been overriden. What can I do to override it? Can I check if the function is not overriden later by another module?

Is there something I did wrong? As I am new to JS I am aware I might use javascript anti-patterns. Please feel free to point those out.

Body:
Please try the below code:

odoo.define('my_module.dashboard', function(require) {
"use strict";

console.log('dashboard #1');

var dashboard = require('sales_team.dashboard');

console.log('dashboard #2');
var SalesTeamDashboardView = dashboard.include({

    render: function() {
        console.log('dashboard #3');
        var super_render = this._super;
        var self = this;

        return this.fetch_data().then(function(result){
            console.log('dashboard #4');
            self.show_demo = false;

            var sales_dashboard = QWeb.render(template, {
                widget: self,
                show_demo: self.show_demo,
                values: result,
            });
            super_render.call(self);
            console.log('dashboard #5');
            $(sales_dashboard).prependTo(self.$el);
        });
    },
    });

});