问:
How to fix this script to change the value from true to false
This is my first question on your forum, and I wish to find an answer, maybe it's a dumb question for everyone of you but I'm beginning with a JavaScript boot-camp and I'm curious how to do change the highlighted value with TamperMonkey

Another little question: Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

HTML

    <meta content="width=device-width,initial-scale=1.0,user-scalable=no"
    name="viewport">
    <meta id="fedora-keys" data-commit
    sha="f232f03c4db92d93cff3bee17185864b56d67336" data-env="production"
```

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

<pre class="lang-js prettyprint-override"><code>(function() {
  'use strict';
   var link = document.createElement('meta');
   link.setAttribute('name', 'data-env');
   link.content = "development";
   document.getElementsByTagName('head')[0].appendChild(link);
})();
</code>```

I'm trying to change "production" to "development" with TamperMonkey, but I blame my ignorance of the programming language.

Regards

答:
Try the following to change the element directly:</p>

```<code>(function() {
   'use strict';
   //get the meta element with id fedora-keys
   var link = document.querySelector('meta#fedora-keys');
   //set the data-env attribute to development
   link.setAttribute('data-env', 'development');
})();
</code>```

Body:
This is my first question on your forum, and I wish to find an answer, maybe it's a dumb question for everyone of you but I'm beginning with a JavaScript boot-camp and I'm curious how to do change the highlighted value with TamperMonkey

Another little question: Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

HTML

    <meta content="width=device-width,initial-scale=1.0,user-scalable=no"
    name="viewport">
    <meta id="fedora-keys" data-commit
    sha="f232f03c4db92d93cff3bee17185864b56d67336" data-env="production"

TamperMonkey Script

(function() {
  'use strict';
   var link = document.createElement('meta');
   link.setAttribute('name', 'data-env');
   link.content = "development";
   document.getElementsByTagName('head')[0].appendChild(link);
})();

I'm trying to change "production" to "development" with TamperMonkey, but I blame my ignorance of the programming language.

Regards

Body:
Try the following to change the element directly:

(function() {
   'use strict';
   //get the meta element with id fedora-keys
   var link = document.querySelector('meta#fedora-keys');
   //set the data-env attribute to development
   link.setAttribute('data-env', 'development');
})();


来源: stackexchange

问:
Using hibernate return wrong count value of a query
I'm trying to check if there is an username in a database that is equal to the passed String.
This is the method.

```<code>public  boolean alredyTakenUsername(String userna) {
   int numb = 0;
   s = sessionFactory.openSession();
   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       Query query = s.createQuery(sql);
       query.setParameter("usern",userna);
       numb = ((Number)query.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   }catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}
</code>```

I put in the database the username and with the query:

select count(*) from User where username='fabio'

TABLE:

```<code>USER( username CHAR(20),
      pass CHAR(40),
      loggedstatus BOOLEAN,
      PRIMARY KEY(username));
</code>```

It returns 1 that is correct.
But the method always return 0 when i use userna=fabio.
I can't use uniqueResult() because Hibernate5 doesn't allow it.
Why?

答:
I solved the problem like this:

```<code>public  boolean alredyTakenUsername(String userna) {
   s = sessionFactory.openSession();

   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       NativeQuery sqlQuery = s.createSQLQuery(sql);
       sqlQuery.setParameter("usern",userna);
       int numb = ((Number)sqlQuery.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   } catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}
</code>```

I think that the mistake was due at the use of the class Query that is specific for a query of Hibernate.
NativeQuery admit query of the dialect, in my case SQL (like the method that i use)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to check if there is an username in a database that is equal to the passed String.
This is the method.

public  boolean alredyTakenUsername(String userna) {
   int numb = 0;
   s = sessionFactory.openSession();
   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       Query query = s.createQuery(sql);
       query.setParameter("usern",userna);
       numb = ((Number)query.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   }catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}

I put in the database the username and with the query:

select count(*) from User where username='fabio'

TABLE:

USER( username CHAR(20),
      pass CHAR(40),
      loggedstatus BOOLEAN,
      PRIMARY KEY(username));

It returns 1 that is correct.
But the method always return 0 when i use userna=fabio.
I can't use uniqueResult() because Hibernate5 doesn't allow it.
Why?

Body:
I solved the problem like this:

public  boolean alredyTakenUsername(String userna) {
   s = sessionFactory.openSession();

   try {
       String sql = "SELECT COUNT(*) FROM User where User.username= :usern";
       NativeQuery sqlQuery = s.createSQLQuery(sql);
       sqlQuery.setParameter("usern",userna);
       int numb = ((Number)sqlQuery.getSingleResult()).intValue();
       if (numb == 1)
           return true;
       else
           return false;
   } catch (Exception e){
       e.printStackTrace();
   } finally {
       s.close();
   }
   return false;
}

I think that the mistake was due at the use of the class Query that is specific for a query of Hibernate.
NativeQuery admit query of the dialect, in my case SQL (like the method that i use)


问:
compare two lists to get non matching elements
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

```<code>len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890
</code>```

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

答:
You can use the Counter class from collections:

```<code>list1 = [1,1,2,3,4]
list2 = [3,3,4,5,6]

from collections import Counter
result = list((Counter(list1)-Counter(list2)).elements())

# [1, 1, 2]
</code>```

Or, if you want mutual exclusion:

```<code>count1 = Counter(list1)
count2 = Counter(list2)
r = list((count1-count2+(count2-count1)).elements())

# [1, 1, 2, 3, 5, 6]
</code>```

Body:
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

Body:
You can use the Counter class from collections:

list1 = [1,1,2,3,4]
list2 = [3,3,4,5,6]

from collections import Counter
result = list((Counter(list1)-Counter(list2)).elements())

# [1, 1, 2]

Or, if you want mutual exclusion:

count1 = Counter(list1)
count2 = Counter(list2)
r = list((count1-count2+(count2-count1)).elements())

# [1, 1, 2, 3, 5, 6]


问:
How to connect customUI events to macros in Word 2010?
I have a MS Word 2010 macro-enabled document template (.dotm file). I am working on embedding some custom Ribbon UI components by means of a customUI\customUI14.xml file within the .dotm archive.

The controls show up fine, but I am unable to link up the onAction events described in the XML with any of the macros defined in the template. I think the method signatures are correct, but I must be referencing them incorrectly in the XML. What am I doing wrong?

Here's the XML:

```<code><mso:customUI xmlns:x2="http://schemas.microsoft.com/office/2009/07/customui/macro" xmlns:x1="DPOfcX.DocumentRibbon" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
    <mso:ribbon>
        <mso:tabs>
            <mso:tab idQ="mso:TabHome">
                <mso:group id="TestGroup" label="TestGroup" autoScale="true">
                    <mso:button onAction="SendAsEmail.SendAsEmailRibbon" idQ="x2:TestSendAsEmail" label="Send As Email" imageMso="ListMacros" visible="true"/>
                    <mso:button onAction="SendAsEmail.ShowFormRibbon" idQ="x2:TestShowForm" label="Enter Letter Data" imageMso="ListMacros" visible="true"/>
                </mso:group>
            </mso:tab>
        </mso:tabs>
    </mso:ribbon>
</mso:customUI>
</code>```

Here are the method signatures in the SendAsEmail module:

```<code>Sub ShowFormRibbon(IControl As IRibbonControl)

End Sub

Sub SendAsEmailRibbon(IControl As IRibbonControl)

End Sub
</code>```

答: You don't need to reference the module. Simply remove SendAsEmail. from both of your onAction.

ContentLicense: CC BY-SA 3.0

Body:
I have a MS Word 2010 macro-enabled document template (.dotm file). I am working on embedding some custom Ribbon UI components by means of a customUI\customUI14.xml file within the .dotm archive.

The controls show up fine, but I am unable to link up the onAction events described in the XML with any of the macros defined in the template. I think the method signatures are correct, but I must be referencing them incorrectly in the XML. What am I doing wrong?

Here's the XML:

<mso:customUI xmlns:x2="http://schemas.microsoft.com/office/2009/07/customui/macro" xmlns:x1="DPOfcX.DocumentRibbon" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
    <mso:ribbon>
        <mso:tabs>
            <mso:tab idQ="mso:TabHome">
                <mso:group id="TestGroup" label="TestGroup" autoScale="true">
                    <mso:button onAction="SendAsEmail.SendAsEmailRibbon" idQ="x2:TestSendAsEmail" label="Send As Email" imageMso="ListMacros" visible="true"/>
                    <mso:button onAction="SendAsEmail.ShowFormRibbon" idQ="x2:TestShowForm" label="Enter Letter Data" imageMso="ListMacros" visible="true"/>
                </mso:group>
            </mso:tab>
        </mso:tabs>
    </mso:ribbon>
</mso:customUI>

Here are the method signatures in the SendAsEmail module:

Sub ShowFormRibbon(IControl As IRibbonControl)

End Sub

Sub SendAsEmailRibbon(IControl As IRibbonControl)

End Sub


问:
R: Getting note about using zip::zipr() instead of zip::zip() - is it cause for concern?
When I use write.xlsx from library(xlsx), the following appears in the console:

```<code>Note: zip::zip() is deprecated, please use zip::zipr() instead
</code>```

What does this mean? How important is it that I use zip::zipr(), and if it is important, how do I go about fixing that?

My code looks like this:

```<code>hs <- createStyle(textDecoration = "BOLD")

mwb <- write.xlsx(
list(a, b, c),
"./myfile.xlsx",
sheetName = c("Sheet A", "Sheet B", "Sheet C"),
col.names = TRUE,
ow.names = FALSE,
headerStyle = hs)
</code>```

答:
You can make this note disappear by loading your zip package first, because zipr function is in the new zip package and zip function has been disabled by the old zip package.
library(zip)</p>

Body:
When I use write.xlsx from library(xlsx), the following appears in the console:

Note: zip::zip() is deprecated, please use zip::zipr() instead

What does this mean? How important is it that I use zip::zipr(), and if it is important, how do I go about fixing that?

My code looks like this:

hs <- createStyle(textDecoration = "BOLD")

mwb <- write.xlsx(
list(a, b, c),
"./myfile.xlsx",
sheetName = c("Sheet A", "Sheet B", "Sheet C"),
col.names = TRUE,
ow.names = FALSE,
headerStyle = hs)


问:
Using regex to find substring inside another substring
Using regex, how would one check for ANY portion of a string (substring) within another string(substring)?
For example:

```<code>str1 = "li_xxxyyy"
str2 = "123xxxyyy"
</code>```

I need a true response for the xxxyyy variable portion of the string.

I'm looking for any portion of str1 found in any portion of str2

答:
You can check like this:</p>

```<code>var subString = 'Hello';
var string = 'Hello World'
var isSubstring = new RegExp(subString).test(string);
</code>```

Body:
Using regex, how would one check for ANY portion of a string (substring) within another string(substring)?
For example:

str1 = "li_xxxyyy"
str2 = "123xxxyyy"

I need a true response for the xxxyyy variable portion of the string.

I'm looking for any portion of str1 found in any portion of str2

Body:
You can check like this:

var subString = 'Hello';
var string = 'Hello World'
var isSubstring = new RegExp(subString).test(string);


问:
Bootstrap modify breadcrumb with fontawesome icon separator with SASS
So I'm trying to change the default breadcrumb style with SASS. I've setup everything as mentioned in the official Bootstrap 4 beta 3 docs. I've changed the following in the custom.scss

```<code>$breadcrumb-divider: "\f105"; //fontawesome icon for fa-angle-right
</code>```

Now this also needs font family to set to

```<code>font-family: 'fontAwesome'; //How do I plug this in
</code>```

How do you setup the font for the .breadcrumb-item::before class in the right way?

答:
If you are using Bootstrap 4 and Font Awesome 5,</p>

```<code>.breadcrumb-item + .breadcrumb-item::before {
    font-family: "Font Awesome 5 Free";
    content: "\f105";
    font-weight: 900;
}
</code>```

Body:
So I'm trying to change the default breadcrumb style with SASS. I've setup everything as mentioned in the official Bootstrap 4 beta 3 docs. I've changed the following in the custom.scss

$breadcrumb-divider: "\f105"; //fontawesome icon for fa-angle-right

Now this also needs font family to set to

font-family: 'fontAwesome'; //How do I plug this in

How do you setup the font for the .breadcrumb-item::before class in the right way?

Body:
If you are using Bootstrap 4 and Font Awesome 5,

.breadcrumb-item + .breadcrumb-item::before {
    font-family: "Font Awesome 5 Free";
    content: "\f105";
    font-weight: 900;
}


问:
Array Handling from PHP to Javascript
I have this array that I generated in PHP and stored into a variable called "$auction_additionalrevenues".  With said array I have generated, a very nice data table using bootstrap.

My ultimate goal is to allow the user to click a row in said data table and then use a modal to allow them to edit (then next create a row in the table).

I have done this many times using FileMaker as the db source where the rows in the table are "related data" or child records to the parent record the user is viewing.  This time around, the data is not related, but rather in the parent record itself in "repeating fields" from which I have created a multi-dimensional array.

What I can't seem to get right in this particular instance is how to show the user the data in the model for the specific row they have clicked.  It's frustrating because I have ALL the data in that multi-deminensional (or nested?) PHP array stored in the global variable.  In other words, I don't have to go back to the DB to get that data as it is already in the array/variable.

How do I pass all this data between the rendered page/Javascript/PHP?  I can easily echo the record/row of the into JS via an "onclick" as below.

onClick=showadrev()

When I do that I can write the $mkey ($mkey = index/row) to the console log or alert it out no problem.

Next I want that modal popover to show the array that is nested at that index/row.

Here is my array:

```<code>Array
(
    [0] => Array
        (
        [0] => Raffle
        [1] => Pick of Live
        [2] =>
        [3] => 100
        [4] => 150
        [5] => Cocktail Only
        [6] => Struggled a bit, offered some from the stage to hit the minimum
    )

    [1] => Array
    (
        [0] => Raffle
        [1] => Ticket/Tangible
        [2] => $1000 gift certificate to Canlis
        [3] => 25
        [4] => Unlimited
        [5] => Cocktail Only
        [6] => Really don't know how this did, but the box was pretty full of tickets
    )

[2] => Array
    (
        [0] => Game
        [1] => Ticket/Tangible
        [2] => The Horse Race. Everyone is a winner. Receive a gift certificate ranging from $25 to $99.
        [3] => 25
        [4] => Unlimited
        [5] => Cocktail Only
        [6] => Great participation
    )

[3] => Array
    (
        [0] => Other
        [1] => Mystery/ Blind Pull
        [2] => Wine Pull
        [3] => 25
        [4] => 50
        [5] => cocktail only
        [6] => There was about a dozen or so left
    )

[4] => Array
    (
        [0] => Other
        [1] => Ticket/Tangible
        [2] => Centerpiece sales
        [3] => 25
        [4] => 35
        [5] => Pre & During
        [6] => Unknown
    )
</code>```

)

And here is the Data Table I am rendering:

```<code><div class="wizard-step-3">
    <fieldset>
        <legend class="pull-left width-full">Aditional Revenue</legend>
        <!-- <div class="table-responsive"> -->
        <table id="data-table" class="table table-bordered table-striped" width="100%">
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Type</th>
                    <th>Title</th>
                    <th>Price</th>
                    <th>Total Available</th>
                    <th>Sold By</th>
                    <th>Description</th>
                    <th>How did it Go?</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($auction_additionalrevenues as $mkey => $adrevitems){
                    $no = $mkey + 1;
                    ?><tr style="cursor:pointer;" onClick=showadrev(<?php echo $mkey ; ?>)><?php;
                    echo '<td>'.$no.'</td>';
                    echo '<td>'.$adrevitems[0].'</td>';
                    echo '<td>'.$adrevitems[1].'</td>';
                    echo '<td>'.$adrevitems[3].'</td>';
                    echo '<td>'.$adrevitems[4].'</td>';
                    echo '<td>'.$adrevitems[5].'</td>';
                    echo '<td>'.$adrevitems[2].'</td>';
                    echo '<td>'.$adrevitems[6].'</td>';
                    echo '</tr>';

            } ?>
            </tbody>
        </table>
        <!-- </div> -->
    </fieldset>
</div>
</code>```

答:
Artistics answer should be the accepted answer for this. Here is how I implemented it.

```<code>//echo $system_id;
//echo $system_auth_id;
print_r(json_encode($AuthData));
</code>```

I left the commented out stuff so that you see what I was doing before I read this and realized I needed to encode on the PHP side prior to sending it to my JS app.

Result:

```<code>[{"system_id":"61a694d0-3605-4502-952b-38d87b451a56","system_auth_id":"caa5906f-d9ae-4297-8e9f-5ea8d9ed8b51","system_lastauth_id":"ace681bb-48f5-4831-a23d-6608c696f264","system_rundate":"2019-04-27T22:46:07.090Z","system_auth_lastrundate":"2019-04-27T22:45:57.932Z","system_auth_updated_func":"main_init_auth_extend","system_auth_lastupdateddate":"2019-04-27T22:45:57.932Z","system_auth_lastupdated_func":"main_init_auth_extend","system_auth_request":"0","system_auth_request_lastfunc":"n\/a","system_auth_denials":"0","system_auth_denial_lastfunc":"n\/a","system_auth_success":"0","system_auth_success_lastfunc":"n\/a"}]
</code>```

Previous Result:

```<code>Array( [0] => stdClass Object ( [system_id] => 61a694d0-3605-4502-952b-38d87b451a56 [system_auth_id] => caa5906f-d9ae-4297-8e9f-5ea8d9ed8b51 [system_lastauth_id] => ace681bb-48f5-4831-a23d-6608c696f264 [system_rundate] => 2019-04-27T22:46:07.090Z [system_auth_lastrundate] => 2019-04-27T22:45:57.932Z [system_auth_updated_func] => main_init_auth_extend [system_auth_lastupdateddate] => 2019-04-27T22:45:57.932Z [system_auth_lastupdated_func] => main_init_auth_extend [system_auth_request] => 0 [system_auth_request_lastfunc] => n/a [system_auth_denials] => 0 [system_auth_denial_lastfunc] => n/a [system_auth_success] => 0 [system_auth_success_lastfunc] => n/a ) )
</code>```

Title: Array Handling from PHP to Javascript

Body:
I have this array that I generated in PHP and stored into a variable called "$auction_additionalrevenues".  With said array I have generated, a very nice data table using bootstrap.

My ultimate goal is to allow the user to click a row in said data table and then use a modal to allow them to edit (then next create a row in the table).

I have done this many times using FileMaker as the db source where the rows in the table are "related data" or child records to the parent record the user is viewing.  This time around, the data is not related, but rather in the parent record itself in "repeating fields" from which I have created a multi-dimensional array.

What I can't seem to get right in this particular instance is how to show the user the data in the model for the specific row they have clicked.  It's frustrating because I have ALL the data in that multi-deminensional (or nested?) PHP array stored in the global variable.  In other words, I don't have to go back to the DB to get that data as it is already in the array/variable.

How do I pass all this data between the rendered page/Javascript/PHP?  I can easily echo the record/row of the into JS via an "onclick" as below.

onClick=showadrev()

When I do that I can write the $mkey ($mkey = index/row) to the console log or alert it out no problem.

Next I want that modal popover to show the array that is nested at that index/row.

Here is my array:

Array
(
    [0] => Array
        (
        [0] => Raffle
        [1] => Pick of Live
        [2] =>
        [3] => 100
        [4] => 150
        [5] => Cocktail Only
        [6] => Struggled a bit, offered some from the stage to hit the minimum
    )

    [1] => Array
    (
        [0] => Raffle
        [1] => Ticket/Tangible
        [2] => $1000 gift certificate to Canlis
        [3] => 25
        [4] => Unlimited
        [5] => Cocktail Only
        [6] => Really don't know how this did, but the box was pretty full of tickets
    )

[2] => Array
    (
        [0] => Game
        [1] => Ticket/Tangible
        [2] => The Horse Race. Everyone is a winner. Receive a gift certificate ranging from $25 to $99.
        [3] => 25
        [4] => Unlimited
        [5] => Cocktail Only
        [6] => Great participation
    )

[3] => Array
    (
        [0] => Other
        [1] => Mystery/ Blind Pull
        [2] => Wine Pull
        [3] => 25
        [4] => 50
        [5] => cocktail only
        [6] => There was about a dozen or so left
    )

[4] => Array
    (
        [0] => Other
        [1] => Ticket/Tangible
        [2] => Centerpiece sales
        [3] => 25
        [4] => 35
        [5] => Pre & During
        [6] => Unknown
    )

)

And here is the Data Table I am rendering:

    <fieldset>
        <legend class="pull-left width-full">Aditional Revenue</legend>

                    Item
                    Type
                    Title
                    Price
                    Total Available
                    Sold By
                    Description
                    How did it Go?

                <?php foreach ($auction_additionalrevenues as $mkey => $adrevitems){
                    $no = $mkey + 1;
                    ?><tr style="cursor:pointer;" onClick=showadrev(<?php echo $mkey ; ?>)><?php;
                    echo ''.$no.'	';
                    echo ''.$adrevitems[0].'	';
                    echo ''.$adrevitems[1].'	';
                    echo ''.$adrevitems[3].'	';
                    echo ''.$adrevitems[4].'	';
                    echo ''.$adrevitems[5].'	';
                    echo ''.$adrevitems[2].'	';
                    echo ''.$adrevitems[6].'	';
                    echo '
';

            } ?>

    </fieldset>

Body:
Artistics answer should be the accepted answer for this. Here is how I implemented it.

//echo $system_id;
//echo $system_auth_id;
print_r(json_encode($AuthData));

I left the commented out stuff so that you see what I was doing before I read this and realized I needed to encode on the PHP side prior to sending it to my JS app.

Result:

[{"system_id":"61a694d0-3605-4502-952b-38d87b451a56","system_auth_id":"caa5906f-d9ae-4297-8e9f-5ea8d9ed8b51","system_lastauth_id":"ace681bb-48f5-4831-a23d-6608c696f264","system_rundate":"2019-04-27T22:46:07.090Z","system_auth_lastrundate":"2019-04-27T22:45:57.932Z","system_auth_updated_func":"main_init_auth_extend","system_auth_lastupdateddate":"2019-04-27T22:45:57.932Z","system_auth_lastupdated_func":"main_init_auth_extend","system_auth_request":"0","system_auth_request_lastfunc":"n\/a","system_auth_denials":"0","system_auth_denial_lastfunc":"n\/a","system_auth_success":"0","system_auth_success_lastfunc":"n\/a"}]

Previous Result:

Array( [0] => stdClass Object ( [system_id] => 61a694d0-3605-4502-952b-38d87b451a56 [system_auth_id] => caa5906f-d9ae-4297-8e9f-5ea8d9ed8b51 [system_lastauth_id] => ace681bb-48f5-4831-a23d-6608c696f264 [system_rundate] => 2019-04-27T22:46:07.090Z [system_auth_lastrundate] => 2019-04-27T22:45:57.932Z [system_auth_updated_func] => main_init_auth_extend [system_auth_lastupdateddate] => 2019-04-27T22:45:57.932Z [system_auth_lastupdated_func] => main_init_auth_extend [system_auth_request] => 0 [system_auth_request_lastfunc] => n/a [system_auth_denials] => 0 [system_auth_denial_lastfunc] => n/a [system_auth_success] => 0 [system_auth_success_lastfunc] => n/a ) )


问:
conditional if/else statements across two data frames in R
I have a data.frame of a few columns of known/expected results and want to compare these to a second data.frame with the same structure but potentially different results. There are four possible scenarios:

TruePositive (TP) == elements of the known/observed vectors contain the same information and neither are NA

TrueNegative (TN) == elements of the known/observed vectors are both NA

FalsePositive (FP) == known is NA, while observed is some nonNA value

FalseNegative (FN) == known is some nonNA value, observed is NA

I'd like to to produce a new data.frame that evaluates those four conditions for each of the columns among the known/observed data.frames

I have come across posts that describe multiple conditions within a vector, but I haven't seen any information on comparing the elements of two vectors that share the same index (in R).

Let's say for simplicity you have a pair of maps: the "True" map is what we expect, and the "observed" map is what we have recorded. For both maps, these observations occur at identical locations, and each location is broken up into three parts (Country, Region, and Zone).

```<code>true_map <- data.frame(
  MapSection = paste0("mapsection", seq(1:5)),
  Country = c(rep("Canada", 3), rep("UnitedStates", 2)),
  Region = c(rep("Ontario", 3), "NewYork", "Alaska"),
  Zone = c("Toronto", "Ottawa", NA, "Albany", NA)
)

obsrvd_map <- data.frame(
  MapSection = paste0("mapsection", seq(1:5)),
  Country = c(rep("Canada", 3), rep("UnitedStates", 2)),
  Region = c(rep("Ontario", 2), NA, "NewYork", "Alaska"),
  Zone = c("Toronto", "Ottawa", NA, "Albany", "Fairbanks")
)
</code>```

At the Country level, the true and observed maps are identical. At the Region level however, mapsection3 is missing information in the "observed" map (NA), while the "true" map has a location (Ontario). This would be classified as a FalseNegative, because we are missing information where we expect it to be.
Conversely, mapsection5 is missing information in the "true" map at the Zone level, while the "observed" map contains information (Fairbanks). This would be classified as a FalsePositive because there is additional information where we do not expect information. However, both the "true" and "observed" maps are lacking information in the Zone level for mapsection3. This would be considered a TrueNegative because both are missing information.

The final result would summarize these observations as follows:

```<code>MapSection Country Region Zone
mapsection1      TP     TP   TP
mapsection2      TP     TP   TP
mapsection3      TP     FN   TN
mapsection4      TP     TP   TP
mapsection5      TP     TP   FP
</code>```

Thank you for your assistance!

答:
Following Bruce's advice, I pulled out just a single location type and tried evaluating the four conditions I described. I think it's working...</p>

```<code>Zone_df <- merge(true_map[,c("Zone", "MapSection")], obsrvd_map[,c("Zone", "MapSection")], by="MapSection") %>%
  rename(., exp.Zone=Zone.x, obs.Zone=Zone.y) %>%
  mutate_if(is.factor, as.character)

Zone_df %>%
  mutate(EvalCase = case_when(
    (exp.Zone) == (obs.Zone)  ~ "TP",
    is.na(exp.Zone) == is.na(obs.Zone)  ~ "TN",
    is.na(exp.Zone) & !is.na(obs.Zone)  ~ "FP",
    !is.na(exp.Zone) & is.na(obs.Zone)  ~ "FN",
))
</code>```

Body:
I have a data.frame of a few columns of known/expected results and want to compare these to a second data.frame with the same structure but potentially different results. There are four possible scenarios:

TruePositive (TP) == elements of the known/observed vectors contain the same information and neither are NA

TrueNegative (TN) == elements of the known/observed vectors are both NA

FalsePositive (FP) == known is NA, while observed is some nonNA value

FalseNegative (FN) == known is some nonNA value, observed is NA

I'd like to to produce a new data.frame that evaluates those four conditions for each of the columns among the known/observed data.frames

I have come across posts that describe multiple conditions within a vector, but I haven't seen any information on comparing the elements of two vectors that share the same index (in R).

Let's say for simplicity you have a pair of maps: the "True" map is what we expect, and the "observed" map is what we have recorded. For both maps, these observations occur at identical locations, and each location is broken up into three parts (Country, Region, and Zone).

true_map <- data.frame(
  MapSection = paste0("mapsection", seq(1:5)),
  Country = c(rep("Canada", 3), rep("UnitedStates", 2)),
  Region = c(rep("Ontario", 3), "NewYork", "Alaska"),
  Zone = c("Toronto", "Ottawa", NA, "Albany", NA)
)

obsrvd_map <- data.frame(
  MapSection = paste0("mapsection", seq(1:5)),
  Country = c(rep("Canada", 3), rep("UnitedStates", 2)),
  Region = c(rep("Ontario", 2), NA, "NewYork", "Alaska"),
  Zone = c("Toronto", "Ottawa", NA, "Albany", "Fairbanks")
)

At the Country level, the true and observed maps are identical. At the Region level however, mapsection3 is missing information in the "observed" map (NA), while the "true" map has a location (Ontario). This would be classified as a FalseNegative, because we are missing information where we expect it to be.
Conversely, mapsection5 is missing information in the "true" map at the Zone level, while the "observed" map contains information (Fairbanks). This would be classified as a FalsePositive because there is additional information where we do not expect information. However, both the "true" and "observed" maps are lacking information in the Zone level for mapsection3. This would be considered a TrueNegative because both are missing information.

The final result would summarize these observations as follows:

MapSection Country Region Zone
mapsection1      TP     TP   TP
mapsection2      TP     TP   TP
mapsection3      TP     FN   TN
mapsection4      TP     TP   TP
mapsection5      TP     TP   FP

Thank you for your assistance!

Body:
Following Bruce's advice, I pulled out just a single location type and tried evaluating the four conditions I described. I think it's working...

Zone_df <- merge(true_map[,c("Zone", "MapSection")], obsrvd_map[,c("Zone", "MapSection")], by="MapSection") %>%
  rename(., exp.Zone=Zone.x, obs.Zone=Zone.y) %>%
  mutate_if(is.factor, as.character)

Zone_df %>%
  mutate(EvalCase = case_when(
    (exp.Zone) == (obs.Zone)  ~ "TP",
    is.na(exp.Zone) == is.na(obs.Zone)  ~ "TN",
    is.na(exp.Zone) & !is.na(obs.Zone)  ~ "FP",
    !is.na(exp.Zone) & is.na(obs.Zone)  ~ "FN",
))


问:
How can i convert scraping script as web-service?
I want to build a api that accepts a string and returns html code.

Here is my scraping code that i want as a web-service.

Code

```<code>from selenium import webdriver
import bs4
import requests
import time

url = "https://www.pnrconverter.com/"
browser = webdriver.Firefox()
browser.get(url)
string = "3 PS 232 M 03FEB 7 JFKKBP HK2 1230A 420P 03FEB E
PS/JPIX8U"
button =
browser.find_element_by_xpath("//textarea[@class='dataInputChild']")
button.send_keys(string) #accept string
button.submit()
time.sleep(5)
soup = bs4.BeautifulSoup(browser.page_source,'html.parser')
html = soup.find('div',class_="main-content") #returns html
print(html)
</code>```

Can anyone tell me the best possible solution to wrap up my code as a api/web-service.

答:
I am the owner of PNR Converter, so I can shed some light on your attempt to scrape content from our site. Unfortunately scraping from PNR Converter is not recommended. We are developing an API which looks like it would suit your needs, and should be ready in the not too distant future. If you contact us through the site we would be happy to work with you should you wish to use PNR Converter legitimately. PNR Converter gets at least one complete update per year and as such we change all the code on a regular basis. We also monitor all requests to our site, and we will block any requests which are deemed as improper usage. Our filter has already picked up your IP address (ends in 250.144) as potential misuse.

Like I said, should you wish to work with us at PNR Converter legitimately and not scrape our content then we would be happy to do so! please keep checking https://www.pnrconverter.com/api-introduction for information relating to our API.

We are releasing a backend upgrade this weekend, which will have a different HTML structure, and dynamically named elements which will cause a serious issue for web scrapers!

Body:
I want to build a api that accepts a string and returns html code.

Here is my scraping code that i want as a web-service.

Code

from selenium import webdriver
import bs4
import requests
import time

url = "https://www.pnrconverter.com/"
browser = webdriver.Firefox()
browser.get(url)
string = "3 PS 232 M 03FEB 7 JFKKBP HK2 1230A 420P 03FEB E
PS/JPIX8U"
button =
browser.find_element_by_xpath("//textarea[@class='dataInputChild']")
button.send_keys(string) #accept string
button.submit()
time.sleep(5)
soup = bs4.BeautifulSoup(browser.page_source,'html.parser')
html = soup.find('div',class_="main-content") #returns html
print(html)

Can anyone tell me the best possible solution to wrap up my code as a api/web-service.


问:
How should I think about implement the closing of an open equity position in my portfolio app?
I have a model PortStock that has a schema that looks like this:

```<code># == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  transaction_price :float
#  current_price     :float
#  percent_change    :float
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  current_value     :float
#  dollar_change     :float
#  total_spend       :float
#  transaction_date  :datetime
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#  slug              :string
#
</code>```

When someone buys a stock, the app creates a port_stock that has position: "open", action: :buy in their portfolio.

When they sell that position, essentially what happens is they create another port_stock but it just has position: "closed", action: :sell.

I have a few questions:

Is that really the most optimal structure? One immediate issue I see with this is that I have to close the buy position. So in essence, the full completed position would be two closed  buy and sell port_stock records. If there is only one, then the position is considered open. But does that make sense?

Should I create a method in my model to both close and open positions? I originally did this just in my controllers, but now that I am writing unit tests I don't have a clean way to close an existing open position.

Should I be approaching the buying & selling of port_stock differently?

Thoughts?

答:
There is one concept which is missed . This makes your approach non-optimal. The equity transactions in real world also have Partial executions which are not handled here.
Partial executions can occur both during Buy and Sell.

For eg. If you created a limit order to buy 1000 shares at 1 $. The only matching order the ROMS system (or whichever trade matching system you use) can find is for 500 shares.
  In this case , you need to maintain a variable with
  quantity:500 , action : partial

Also , partial executions can happen during market order.

For eg. You triggered a sale of 1000 shares at market price. The first 200 shares get sold at 1 $ , and remaining 800 shares at .8$. The action : close can only happen once the completed sale has taken place.

I agree that the method should be kept in the model for buying and selling.

Body:
I have a model PortStock that has a schema that looks like this:

# == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  transaction_price :float
#  current_price     :float
#  percent_change    :float
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  current_value     :float
#  dollar_change     :float
#  total_spend       :float
#  transaction_date  :datetime
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#  slug              :string
#

When someone buys a stock, the app creates a port_stock that has position: "open", action: :buy in their portfolio.

When they sell that position, essentially what happens is they create another port_stock but it just has position: "closed", action: :sell.

I have a few questions:

Is that really the most optimal structure? One immediate issue I see with this is that I have to close the buy position. So in essence, the full completed position would be two closed  buy and sell port_stock records. If there is only one, then the position is considered open. But does that make sense?

Should I create a method in my model to both close and open positions? I originally did this just in my controllers, but now that I am writing unit tests I don't have a clean way to close an existing open position.

Should I be approaching the buying & selling of port_stock differently?

Thoughts?


问:
Remote XML Web services using C#
I have been tasked with creating a Remote Web service. I am asking this question to get the best approach to what I need to accomplish and see if there is code examples out there that  might help.

Task

Create a web service that accepts parameters when on button click of other programs. One is a windows app done in C# and the app is old fortran as400 app. I need to create this web service to acept these parameters coming from the other systems and then in the web services I need to take these parameters and send them to a Stored procedure and with the results create an XML file and post it back to the clients end.

Is this possible and if it is can someone point me to where I can see some examples or provide some help.

答:
Web service is not a fixed and well defined technology, so you have different options. The most common ones are SOAP and REST. In my opinion SOAP is to bloated and makes only sense in certain situations. Otherwise REST is the first choice. You can get a first overview of REST at http://en.wikipedia.org/wiki/Representational_State_Transfer. One big benefit of REST is that it's just HTTP. So compared to using SOAP it's much more likely that you have the required libraries available.

In .Net you can implement REST services in different ways. As Darin mentioned, WCF is one choice. But it's also possible using Asp.Net MVC. MVC is much simpler but still flexible and powerful in my opinion. If you are an WCF expert (unlikely when asking this question), go for it. If not, I'll go for MVC. You can learn more about MVC at http://www.asp.net/mvc. Just ask Google for "Asp.Net MVC Rest" and you'll get some hints how to combine both.

Title: Remote XML Web services using C#


问:
Cannot import javax.servlet after adding dependency in gradle
I cannot import javax.servlet even though I have already added the package in my gradle dependencies.

Here's my gradle dependency:

```<code>dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api',
    ...
    ...
}
</code>```

I've also tried:

```<code>dependencies {
    compile "javax.servlet:servlet-api:3.0.1"
}
</code>```

But when I import it using:

```<code>import javax.servlet.http.HttpServletResponse;
</code>```

I get the error: Cannot resolve symbol "HttpServletResponse".

答:
I think it should be:</p>

```<code>// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
</code>```

Body:
I cannot import javax.servlet even though I have already added the package in my gradle dependencies.

Here's my gradle dependency:

dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api',
    ...
    ...
}

I've also tried:

dependencies {
    compile "javax.servlet:servlet-api:3.0.1"
}

But when I import it using:

import javax.servlet.http.HttpServletResponse;

I get the error: Cannot resolve symbol "HttpServletResponse".

Body:
I think it should be:

// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'


问:
Loop through 2 list of dictionaries
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

```<code>list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']
</code>```

The output I'm getting is

```<code>A
B
B
</code>```

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

答:
Currently in your double for loop you print item['name'] for a mismatch between any two elements of list1 and list2, which is not what you want.

Instead you can convert the names in both lists to a set and take the set difference

```<code>list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

#Iterate through both lists and convert the names to a set in both lists
set1 = {item['name'] for item in list1}
set2 = {item['name'] for item in list2}

#Take the set difference to find items in list1 not in list2
output = set1 - set2
print(output)
</code>```

The output will be

```<code>{'B'}
</code>```

Title: Loop through 2 list of dictionaries

Body:
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']

The output I'm getting is

A
B
B

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

Body:
Currently in your double for loop you print item['name'] for a mismatch between any two elements of list1 and list2, which is not what you want.

Instead you can convert the names in both lists to a set and take the set difference

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

#Iterate through both lists and convert the names to a set in both lists
set1 = {item['name'] for item in list1}
set2 = {item['name'] for item in list2}

#Take the set difference to find items in list1 not in list2
output = set1 - set2
print(output)

The output will be

{'B'}


问:
Correct method of authorising users to certain pages using Auth0
I'm using Auth0 to create a user authorisation, I've also assigned users to groups and then roles within the group. What is the correct convention of restricting users from certain pages and routes?

Currently I am doing the following:

```<code>def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    if 'profile' not in session:
      # Redirect to Login page here
      return redirect('/')
    return f(*args, **kwargs)
  return decorated

@app.route('/dashboard')
@requires_auth
def dashboard():
    if not authorization_check(['GroupNameExample']):
        return redirect(url_for('logout')) # instead of an error page for now
    else:
        return render_template('dashboard.html')

def authorization_check(groups):
    user_group = session['profile']['security']['groups'][0]
    if user_group not in groups:
        return False
    else:
        return True
</code>```

So I'm just doing a basic IF statement, does that seem right?

答:
This can be done actively through roles and direct user IDs. Below is an example that leverages the ID token for an Access Denied error:

```<code>function (user, context, callback) {
  if (context.clientID === "BANNED_CLIENT_ID") {
    return callback(new UnauthorizedError('Access to this application has been temporarily revoked'));
  }

  callback(null, user, context);
}
</code>```

This will cause a redirect to your callback URL with an error querystring parameter containing the message you set. (such as https://yourapp.com/callback?error=unauthorized&error_description=Access%20to%20this%20application%20has%20been%20temporarily%20revoked). Make sure to call the callback with an instance of UnauthorizedError (not Error).

Body:
I'm using Auth0 to create a user authorisation, I've also assigned users to groups and then roles within the group. What is the correct convention of restricting users from certain pages and routes?

Currently I am doing the following:

def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    if 'profile' not in session:
      # Redirect to Login page here
      return redirect('/')
    return f(*args, **kwargs)
  return decorated

@app.route('/dashboard')
@requires_auth
def dashboard():
    if not authorization_check(['GroupNameExample']):
        return redirect(url_for('logout')) # instead of an error page for now
    else:
        return render_template('dashboard.html')

def authorization_check(groups):
    user_group = session['profile']['security']['groups'][0]
    if user_group not in groups:
        return False
    else:
        return True

So I'm just doing a basic IF statement, does that seem right?

Body:
This can be done actively through roles and direct user IDs. Below is an example that leverages the ID token for an Access Denied error:

function (user, context, callback) {
  if (context.clientID === "BANNED_CLIENT_ID") {
    return callback(new UnauthorizedError('Access to this application has been temporarily revoked'));
  }

  callback(null, user, context);
}

This will cause a redirect to your callback URL with an error querystring parameter containing the message you set. (such as https://yourapp.com/callback?error=unauthorized&error_description=Access%20to%20this%20application%20has%20been%20temporarily%20revoked). Make sure to call the callback with an instance of UnauthorizedError (not Error).


问:
Partition a table in teradata using SAS DI studio 4.902
For ETL operations we use SAS DI studio and then finally the tables are loaded in Teradata. DDL is dynamically generated in SAS DI Studio for the tables created. But when we want to customize the DDL to include partitions it throws an error. Can anyone suggest a workaround?
Note: We cannot create the DDL in Teradata first and then register the table in SAS DI Studio to be using it.

In the table properties->Options->advanced and write custom SQL in create table option it works fine for UNIQUE PRIMARY INDEX(NOTI_DT)
But when we try

```<code>UNIQUE PRIMARY INDEX(NOTI_DT)
PARTITION BY RANGE_N(NOTI__DT BETWEEN DATE'1950-01-01'AND DATE'2022-12-31' EACH INTERVAL '1' MONTH)
</code>```

it throws an error:

答:
The "invalid option name" error appears to be due to having quotes within the option string. Try doubling the quotes:</p>

```<code>UNIQUE PRIMARY INDEX(NOTI_ASSIGN_DT)
PARTITION BY RANGE_N(NOTI_ASSIGN_DT BETWEEN DATE''1950-01-01'' AND DATE''2022-12-31'' EACH INTERVAL ''1'' MONTH)
</code>```

Body:
For ETL operations we use SAS DI studio and then finally the tables are loaded in Teradata. DDL is dynamically generated in SAS DI Studio for the tables created. But when we want to customize the DDL to include partitions it throws an error. Can anyone suggest a workaround?
Note: We cannot create the DDL in Teradata first and then register the table in SAS DI Studio to be using it.

In the table properties->Options->advanced and write custom SQL in create table option it works fine for UNIQUE PRIMARY INDEX(NOTI_DT)
But when we try

UNIQUE PRIMARY INDEX(NOTI_DT)
PARTITION BY RANGE_N(NOTI__DT BETWEEN DATE'1950-01-01'AND DATE'2022-12-31' EACH INTERVAL '1' MONTH)

it throws an error:

Body:
The "invalid option name" error appears to be due to having quotes within the option string. Try doubling the quotes:

UNIQUE PRIMARY INDEX(NOTI_ASSIGN_DT)
PARTITION BY RANGE_N(NOTI_ASSIGN_DT BETWEEN DATE''1950-01-01'' AND DATE''2022-12-31'' EACH INTERVAL ''1'' MONTH)


问:
an instance of the app crashed: APP/PROC/WEB: Exited with status 127
I'm working a Flask python (I'm using Python 3.6.8) web app, but when I run the command "cf push" or "ibmcloud app push" the program can't start the app (Waiting for app to start...
Start unsuccessful)

app.py:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Main module """
import os
import cf_deployment_tracker
from datetime import datetime
from flask import Flask, render_template, request, Response, make_response, abort
from flask_httpauth import HTTPBasicAuth
from dotenv import load_dotenv

# Emit Bluemix deployment event
cf_deployment_tracker.track()

app = Flask(__name__)

# define basic auth
auth = HTTPBasicAuth()

# On Bluemix, get the port number from the environment variable PORT
# When running this app on the local machine, default the port to 8000
port = int(os.getenv('PORT', 8000))

if __name__ == '__main__':
    load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))

@app.route('/')
def home():
    return "Hello world!"

###################### /API ENDPOINTS ##############################
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port, debug=True, threaded=True)
</code>```

setup.py:

```<code># Always prefer setuptools over distutils
from setuptools import setup, find_packages

setup(
    name='hello-world',
    version='1.0.0',
    url='',
    license='Apache-2.0'
)
</code>```

manifest.yml:

```<code>---
applications:
 - name: hello-world
   memory: 256MB
   stack:  cflinuxfs3
   buildpack:  https://github.com/cloudfoundry/buildpack-python.git
</code>```

requirements.txt:

```<code>cf-deployment-tracker==1.0.5
Flask==0.12.1
Flask-HTTPAuth==3.2.4
python-dotenv==0.9.1
</code>```

runtime.txt:

```<code>python-3.6.8
</code>```

Procfile:

```<code>web: python app.py
</code>```

There is the CF events:

```<code>2019-05-31T09:28:06.00-0600   app.crash                  liza-speakfreely   index: 0, reason: CRASHED, cell_id: d3330ee1-fbaf-4a02-b5bd-cadb9f384f63, instance: fec4b3fc-5d18-4236-74e2-9a38, exit_description: APP/PROC/WEB: Exited with status 127
2019-05-31T09:28:06.00-0600   audit.app.process.crash    web                index: 0, reason: CRASHED, cell_id: d3330ee1-fbaf-4a02-b5bd-cadb9f384f63, instance: fec4b3fc-5d18-4236-74e2-9a38, exit_description: APP/PROC/WEB: Exited with status 127
</code>```

And there is the logs:

```<code>2019-05-31T11:09:45.99-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 creating container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:09:50.84-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 successfully created container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:09:57.74-0600 [CELL/0] OUT Starting health monitoring of container
2019-05-31T11:10:07.10-0600 [APP/PROC/WEB/0] ERR  * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
2019-05-31T11:10:07.23-0600 [APP/PROC/WEB/0] ERR  * Restarting with stat
2019-05-31T11:10:07.30-0600 [APP/PROC/WEB/0] ERR /usr/bin/env: ‘python3\r’: No such file or directory
2019-05-31T11:10:08.18-0600 [APP/PROC/WEB/0] OUT Exit status 127
2019-05-31T11:10:08.22-0600 [CELL/SSHD/0] OUT Exit status 0
2019-05-31T11:10:14.38-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 stopping instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:10:14.38-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 destroying container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:10:14.44-0600 [API/15] OUT Process has crashed with type: "web"
2019-05-31T11:10:14.46-0600 [API/15] OUT App instance exited with guid f48a4d09-f515-4c8c-8f6e-f416c50f496d payload: {"instance"=>"49f46b7b-57ae-4479-5297-e47e", "index"=>0, "cell_id"=>"ed57f560-073e-48e1-a5b8-e42888f07850", "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 127", "crash_count"=>13, "crash_timestamp"=>1559322614375644796, "version"=>"48ca89cd-deaf-42dc-be23-699ef02a2c70"}
2019-05-31T11:10:14.74-0600 [PROXY/0] OUT Exit status 137
2019-05-31T11:10:16.70-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 successfully destroyed container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:26:27.87-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb creating container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:28.95-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb successfully created container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:33.78-0600 [CELL/0] OUT Starting health monitoring of container
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR  * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR  * Restarting with stat
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR /usr/bin/env: ‘python3\r’: No such file or directory
2019-05-31T11:26:34.89-0600 [APP/PROC/WEB/0] OUT Exit status 127
2019-05-31T11:26:34.89-0600 [CELL/SSHD/0] OUT Exit status 0
2019-05-31T11:26:41.42-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb stopping instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:41.42-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb destroying container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:41.48-0600 [API/26] OUT Process has crashed with type: "web"
2019-05-31T11:26:41.50-0600 [API/26] OUT App instance exited with guid f48a4d09-f515-4c8c-8f6e-f416c50f496d payload: {"instance"=>"9e03bf72-5d07-45a8-7c93-244f", "index"=>0, "cell_id"=>"64b8fbdd-c811-404e-a739-d7b7de546dcb", "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 127", "crash_count"=>14, "crash_timestamp"=>1559323601416178033, "version"=>"48ca89cd-deaf-42dc-be23-699ef02a2c70"}
2019-05-31T11:26:41.62-0600 [PROXY/0] OUT Exit status 137
2019-05-31T11:26:42.75-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb successfully destroyed container for instance 9e03bf72-5d07-45a8-7c93-244f
</code>```

答:
Try changing

#!/usr/bin/env python3

to

#!/usr/bin/python3

Body:
I'm working a Flask python (I'm using Python 3.6.8) web app, but when I run the command "cf push" or "ibmcloud app push" the program can't start the app (Waiting for app to start...
Start unsuccessful)

app.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Main module """
import os
import cf_deployment_tracker
from datetime import datetime
from flask import Flask, render_template, request, Response, make_response, abort
from flask_httpauth import HTTPBasicAuth
from dotenv import load_dotenv

# Emit Bluemix deployment event
cf_deployment_tracker.track()

app = Flask(__name__)

# define basic auth
auth = HTTPBasicAuth()

# On Bluemix, get the port number from the environment variable PORT
# When running this app on the local machine, default the port to 8000
port = int(os.getenv('PORT', 8000))

if __name__ == '__main__':
    load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))

@app.route('/')
def home():
    return "Hello world!"

###################### /API ENDPOINTS ##############################
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port, debug=True, threaded=True)

setup.py:

# Always prefer setuptools over distutils
from setuptools import setup, find_packages

setup(
    name='hello-world',
    version='1.0.0',
    url='',
    license='Apache-2.0'
)

manifest.yml:

---
applications:
 - name: hello-world
   memory: 256MB
   stack:  cflinuxfs3
   buildpack:  https://github.com/cloudfoundry/buildpack-python.git

requirements.txt:

cf-deployment-tracker==1.0.5
Flask==0.12.1
Flask-HTTPAuth==3.2.4
python-dotenv==0.9.1

runtime.txt:

python-3.6.8

Procfile:

web: python app.py

There is the CF events:

2019-05-31T09:28:06.00-0600   app.crash                  liza-speakfreely   index: 0, reason: CRASHED, cell_id: d3330ee1-fbaf-4a02-b5bd-cadb9f384f63, instance: fec4b3fc-5d18-4236-74e2-9a38, exit_description: APP/PROC/WEB: Exited with status 127
2019-05-31T09:28:06.00-0600   audit.app.process.crash    web                index: 0, reason: CRASHED, cell_id: d3330ee1-fbaf-4a02-b5bd-cadb9f384f63, instance: fec4b3fc-5d18-4236-74e2-9a38, exit_description: APP/PROC/WEB: Exited with status 127

And there is the logs:

2019-05-31T11:09:45.99-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 creating container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:09:50.84-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 successfully created container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:09:57.74-0600 [CELL/0] OUT Starting health monitoring of container
2019-05-31T11:10:07.10-0600 [APP/PROC/WEB/0] ERR  * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
2019-05-31T11:10:07.23-0600 [APP/PROC/WEB/0] ERR  * Restarting with stat
2019-05-31T11:10:07.30-0600 [APP/PROC/WEB/0] ERR /usr/bin/env: ‘python3\r’: No such file or directory
2019-05-31T11:10:08.18-0600 [APP/PROC/WEB/0] OUT Exit status 127
2019-05-31T11:10:08.22-0600 [CELL/SSHD/0] OUT Exit status 0
2019-05-31T11:10:14.38-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 stopping instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:10:14.38-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 destroying container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:10:14.44-0600 [API/15] OUT Process has crashed with type: "web"
2019-05-31T11:10:14.46-0600 [API/15] OUT App instance exited with guid f48a4d09-f515-4c8c-8f6e-f416c50f496d payload: {"instance"=>"49f46b7b-57ae-4479-5297-e47e", "index"=>0, "cell_id"=>"ed57f560-073e-48e1-a5b8-e42888f07850", "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 127", "crash_count"=>13, "crash_timestamp"=>1559322614375644796, "version"=>"48ca89cd-deaf-42dc-be23-699ef02a2c70"}
2019-05-31T11:10:14.74-0600 [PROXY/0] OUT Exit status 137
2019-05-31T11:10:16.70-0600 [CELL/0] OUT Cell ed57f560-073e-48e1-a5b8-e42888f07850 successfully destroyed container for instance 49f46b7b-57ae-4479-5297-e47e
2019-05-31T11:26:27.87-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb creating container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:28.95-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb successfully created container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:33.78-0600 [CELL/0] OUT Starting health monitoring of container
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR  * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR  * Restarting with stat
2019-05-31T11:26:34.82-0600 [APP/PROC/WEB/0] ERR /usr/bin/env: ‘python3\r’: No such file or directory
2019-05-31T11:26:34.89-0600 [APP/PROC/WEB/0] OUT Exit status 127
2019-05-31T11:26:34.89-0600 [CELL/SSHD/0] OUT Exit status 0
2019-05-31T11:26:41.42-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb stopping instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:41.42-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb destroying container for instance 9e03bf72-5d07-45a8-7c93-244f
2019-05-31T11:26:41.48-0600 [API/26] OUT Process has crashed with type: "web"
2019-05-31T11:26:41.50-0600 [API/26] OUT App instance exited with guid f48a4d09-f515-4c8c-8f6e-f416c50f496d payload: {"instance"=>"9e03bf72-5d07-45a8-7c93-244f", "index"=>0, "cell_id"=>"64b8fbdd-c811-404e-a739-d7b7de546dcb", "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 127", "crash_count"=>14, "crash_timestamp"=>1559323601416178033, "version"=>"48ca89cd-deaf-42dc-be23-699ef02a2c70"}
2019-05-31T11:26:41.62-0600 [PROXY/0] OUT Exit status 137
2019-05-31T11:26:42.75-0600 [CELL/0] OUT Cell 64b8fbdd-c811-404e-a739-d7b7de546dcb successfully destroyed container for instance 9e03bf72-5d07-45a8-7c93-244f


问:
How to read state property accessors outside the dialog in V4 Bot Framework
I'm using bot framework version 4. I would like to access user state properties in the validator method but I didn't find any solution to it.

GitHub

In the GitHub sample above, we have a validator AgePromptValidatorAsync which validates age.
But I would want to access Name which I have stored in State property.
How could that be achieved.
And is it possible to access state/use GetAsync in a method outside dialog which doesn't contain context.

@mdrichardson could you please help me in this.Thank you in advance.

答:
1. Ensure that UserProfile.Name is saved before hitting validation.

That sample doesn't do this on it's own, so you would:

private async Task<DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    stepContext.Values["name"] = (string)stepContext.Result;

    // ADDED: This code block saves the Name
    if (!string.IsNullOrEmpty((string)stepContext.Result)) {
        var userProfile = await _userProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);
        userProfile.Name = (string)stepContext.Result;
        await _userProfileAccessor.SetAsync(stepContext.Context, userProfile);
    }

    // We can send messages to the user at any point in the WaterfallStep.
    await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Thanks {stepContext.Result}."), cancellationToken);

    // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
    return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to give your age?") }, cancellationToken);
}
```

<h3>2. Access the User Profile</h3>

<pre class="lang-cs prettyprint-override"><code>// CHANGED: Since this accesses the userProfile, the method is no longer static. Also must be async
private async Task<bool> AgePromptValidatorAsync(PromptValidatorContext<int> promptContext, CancellationToken cancellationToken)
{
    // ADDED: Here is how you can access the Name
    //   Note: You can use promptContext.Context instead of stepContext.Context since they're both ITurnContext
    var userProfile = await _userProfileAccessor.GetAsync(promptContext.Context, () => new UserProfile(), cancellationToken);
    var name = userProfile.Name;
    // Do whatever you want with the Name

    // CHANGED: Since this is now async, we don't return Task.FromResult(). We just return the result
    return promptContext.Recognized.Succeeded && promptContext.Recognized.Value > 0 && promptContext.Recognized.Value < 150;
}
</code>```

Accessing the UserProfile Without Context

This is kind of possible, but you can't do this easily or out-of-the-box. There are some options that you can use, however (mostly in order from least difficult to most):

Pass the context to whatever method/function you need to use it in. Just about every bot method you'd use has some kind of context that you can pass into another method. This is definitely your best option.

Create a separate class that you use to store variables in bot memory

Either Write Directly to Storage or Implement Custom Storage that you use to track the UserProfile. Note, you'd have to pass around your Storage object, so you may as well just pass around the context, instead.

Use the new Adaptive Dialogs, since they do state management differently. I highly recommend against this, though, as these are "experimental", meaning that there's still bugs and we barely use this internally. I'm adding this as an option more for posterity and users that want to play with new stuff.

Body:
1. Ensure that UserProfile.Name is saved before hitting validation.

That sample doesn't do this on it's own, so you would:

private async Task<DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    stepContext.Values["name"] = (string)stepContext.Result;

    // ADDED: This code block saves the Name
    if (!string.IsNullOrEmpty((string)stepContext.Result)) {
        var userProfile = await _userProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);
        userProfile.Name = (string)stepContext.Result;
        await _userProfileAccessor.SetAsync(stepContext.Context, userProfile);
    }

    // We can send messages to the user at any point in the WaterfallStep.
    await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Thanks {stepContext.Result}."), cancellationToken);

    // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
    return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to give your age?") }, cancellationToken);
}

2. Access the User Profile

// CHANGED: Since this accesses the userProfile, the method is no longer static. Also must be async
private async Task<bool> AgePromptValidatorAsync(PromptValidatorContext<int> promptContext, CancellationToken cancellationToken)
{
    // ADDED: Here is how you can access the Name
    //   Note: You can use promptContext.Context instead of stepContext.Context since they're both ITurnContext
    var userProfile = await _userProfileAccessor.GetAsync(promptContext.Context, () => new UserProfile(), cancellationToken);
    var name = userProfile.Name;
    // Do whatever you want with the Name

    // CHANGED: Since this is now async, we don't return Task.FromResult(). We just return the result
    return promptContext.Recognized.Succeeded && promptContext.Recognized.Value > 0 && promptContext.Recognized.Value < 150;
}

Accessing the UserProfile Without Context

This is kind of possible, but you can't do this easily or out-of-the-box. There are some options that you can use, however (mostly in order from least difficult to most):

Pass the context to whatever method/function you need to use it in. Just about every bot method you'd use has some kind of context that you can pass into another method. This is definitely your best option.

Create a separate class that you use to store variables in bot memory

Either Write Directly to Storage or Implement Custom Storage that you use to track the UserProfile. Note, you'd have to pass around your Storage object, so you may as well just pass around the context, instead.

Use the new Adaptive Dialogs, since they do state management differently. I highly recommend against this, though, as these are "experimental", meaning that there's still bugs and we barely use this internally. I'm adding this as an option more for posterity and users that want to play with new stuff.


问:
is there an ios app development age rating official definition page?
Is there an official apple page explaining the age rating system for ios app development?

For example, specifically what qualifies as 4+, 9+, 17+ etc...

I saw online an image of a page where you can select radio buttons but I am not finding it on the developer website or an official definition of what is 4+ 9+ etc.

答:
You are looking for App Store Help App Ratings:</p>

```
Rating  Definition
4+      Apps in this category contain no objectionable material.

9+      Apps in this category may contain instances of the following content that may not be suitable for children under the age of 9:

        - Infrequent or mild cartoon or fantasy violence
        - Infrequent or mild profanity or crude humor
        - Infrequent or mild mature, suggestive, or horror or fear themed

12+     Apps in this category may contain instances of the following content that may not be suitable for children under the age of 12:

        - Infrequent or mild medical or treatment-focused content
        - Infrequent or mild references to alcohol, tobacco, or drug use
Simulated gambling
        - Infrequent or mild sexual content or nudity
        - Frequent or intense profanity or crude humor
        - Frequent or intense horror or fear themed content
        - Frequent or intense cartoon or fantasy violence
        - Infrequent or mild occurrences of realistic violence

17+     Apps in this category may contain instances of the following content that may not be suitable for children under the age of 17:

        - Unrestricted web access, such as with an embedded browser
Gambling or contests
        - Frequent or intense mature or suggestive content
        - Frequent or intense medical or treatment-focused content
        - Frequent or intense references to alcohol, tobacco, or drug use
        - Frequent or intense sexual content or nudity
        - Frequent or intense realistic violence
```

Body:
You are looking for App Store Help App Ratings:

Rating  Definition
4+      Apps in this category contain no objectionable material.

9+      Apps in this category may contain instances of the following content that may not be suitable for children under the age of 9:

        - Infrequent or mild cartoon or fantasy violence
        - Infrequent or mild profanity or crude humor
        - Infrequent or mild mature, suggestive, or horror or fear themed

12+     Apps in this category may contain instances of the following content that may not be suitable for children under the age of 12:

        - Infrequent or mild medical or treatment-focused content
        - Infrequent or mild references to alcohol, tobacco, or drug use
Simulated gambling
        - Infrequent or mild sexual content or nudity
        - Frequent or intense profanity or crude humor
        - Frequent or intense horror or fear themed content
        - Frequent or intense cartoon or fantasy violence
        - Infrequent or mild occurrences of realistic violence

17+     Apps in this category may contain instances of the following content that may not be suitable for children under the age of 17:

        - Unrestricted web access, such as with an embedded browser
Gambling or contests
        - Frequent or intense mature or suggestive content
        - Frequent or intense medical or treatment-focused content
        - Frequent or intense references to alcohol, tobacco, or drug use
        - Frequent or intense sexual content or nudity
        - Frequent or intense realistic violence


问:
What is the java keyevent field for windows icon?
```<code>public static void main(String[] args) throws InterruptedException {
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_***windowsicon***);
            } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
</code>```

I need to press windows icon key. But I could not find any virtual key command for or (KeyEvent.VK_windowsicon)  some similar command.

Thanks.

答:
Actually Windows start menu pops up on key release, if that's your desired action (check it by slowly pressing and releasing the Windows key manually).

So you must release the key after pressing it,

```<code>Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_WINDOWS);
robot.keyRelease(KeyEvent.VK_WINDOWS);
</code>```

Body:
public static void main(String[] args) throws InterruptedException {
        try {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_***windowsicon***);
            } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

I need to press windows icon key. But I could not find any virtual key command for or (KeyEvent.VK_windowsicon)  some similar command.

Thanks.

Body:
Actually Windows start menu pops up on key release, if that's your desired action (check it by slowly pressing and releasing the Windows key manually).

So you must release the key after pressing it,

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_WINDOWS);
robot.keyRelease(KeyEvent.VK_WINDOWS);


问:
Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release
react-native run-android command terminates by leaving a message in android simulator. The message is as follows:

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release.

What am I doing wrong?

答:
These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
```

Step 3:
Build your APK: react-native run-android

Please use index.js in latest version.

Enjoy :)

Body:
These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Step 3:
Build your APK: react-native run-android

Please use index.js in latest version.

Enjoy :)


答:
That's (obviously) not the logic of your code.  You iterate through all combinations of names, and print the one from list1 every time it doesn't match any name in list2.

Instead, don't print it until you know it is a mismatch for all of those names:

```<code>for item in list1:
    found = False
    for ii in list2:
        if item['name'] == ii['name']:
            found = True

    if not found:
        print item['name']
</code>```

This is the direct change to your implementation.  There are one-liners that can do this using comprehensions, all, and other Python capabilities.

Title: Loop through 2 list of dictionaries

Body:
That's (obviously) not the logic of your code.  You iterate through all combinations of names, and print the one from list1 every time it doesn't match any name in list2.

Instead, don't print it until you know it is a mismatch for all of those names:

for item in list1:
    found = False
    for ii in list2:
        if item['name'] == ii['name']:
            found = True

    if not found:
        print item['name']

This is the direct change to your implementation.  There are one-liners that can do this using comprehensions, all, and other Python capabilities.


问:
TYPO3 8.7 EXT:form - Flash messages not shown in finisher until refresh page
I created a custom finisher for EXT:form. Among other things, my finisher has to show a flash message:

```<code>  class CreateRequestActionFinisher extends \TYPO3\CMS\Form\Domain\Finishers\AbstractFinisher
  {
    // Validations ...
    $flashMessage = $this->objectManager->get(
      FlashMessage::class,
      'Everything is fine.',
      'Thanks',
      \TYPO3\CMS\Core\Messaging\AbstractMessage::OK,
      true
    );
    $this->finisherContext->getControllerContext()->getFlashMessageQueue()->addMessage($flashMessage);
  }
</code>```

My problem is that, in frontend, my flash message does not appear inmediately when I send my form. When I refresh my browser page (sending my form twice), my flash message appears. ¿What can I do? Thanks.

答:
Workaround for TYPO3 v8.7:
I think this is based on this open issue regarding caching of flash messages. As a workaround, I currently use this additional finisher (last one in finisher array) to get it working properly:

```<code>-
    options:
      pageUid: '1' # uid of the page with the form
      additionalParameters: 'no_cache=1'
    identifier: Redirect
</code>```

TYPO3 v9.5.6 and newer:

I think that this problem has now been solved because of this patch and a workaround is no longer necessary.

Body:
I created a custom finisher for EXT:form. Among other things, my finisher has to show a flash message:

  class CreateRequestActionFinisher extends \TYPO3\CMS\Form\Domain\Finishers\AbstractFinisher
  {
    // Validations ...
    $flashMessage = $this->objectManager->get(
      FlashMessage::class,
      'Everything is fine.',
      'Thanks',
      \TYPO3\CMS\Core\Messaging\AbstractMessage::OK,
      true
    );
    $this->finisherContext->getControllerContext()->getFlashMessageQueue()->addMessage($flashMessage);
  }

My problem is that, in frontend, my flash message does not appear inmediately when I send my form. When I refresh my browser page (sending my form twice), my flash message appears. ¿What can I do? Thanks.

Body:
Workaround for TYPO3 v8.7:
I think this is based on this open issue regarding caching of flash messages. As a workaround, I currently use this additional finisher (last one in finisher array) to get it working properly:

-
    options:
      pageUid: '1' # uid of the page with the form
      additionalParameters: 'no_cache=1'
    identifier: Redirect

TYPO3 v9.5.6 and newer:

I think that this problem has now been solved because of this patch and a workaround is no longer necessary.


问:
Are there built-in extension methods in the .NET framework that don't apply to LINQ?
For the purpose of a course I am developing, I am looking for some examples of where Microsoft has already implemented extension methods themselves. But since the students are not yet acquainted to LINQ, I would like to find some other example.

So, are there any methods defined in the .NET framework that are defined as an extension method, but do not refer to the LINQ framework or IEnumerable?

答:
There are quite a few actually. I downloaded the .Net Framework source code for version 4.8 (May 2019 upgrade). To do so yourself just click Download in the reference source website

Unzip the file then open the solution with Visual Studio and search for (using regular expressions) :

Class .*Extensions

It returned 61 hits to me, I'm sure you will be able to find proper examples for your course. I suppose the best one would be DoubleExtensions (see here) as it is an easy one to understand.


问:
HelloWorld example for Perl gives two errors when not specifying use 5.30.0
NEWBIE: So today I started a tutorial on learning Perl and was doing okay until I got to the use #.###;

Can someone please explain what the default value is for Perl when the version is omitted?

When I put the value of use 5.30.0; the example will run. However if I do not specify the line at all I get the following two errors depending on the position of the main and calls to the sayit().

The 1st error occurs if the package main; say hello::sayit()... at top of file.

Can't locate object method "say" via package "hello::sayit" (perhaps you forgot to load "hello::sayit"?) at helloWorld.pl line 7.

```<code>#!/usr/bin/perl
use strict;
#use warnings;
use warnings FATAL => 'all';
# default namespace is main
package main;
say hello::sayit();
say world::sayit();

# new namespace called hello
package hello;
sub sayit {
    return "hello";
}

# new namespace called world
package world;
sub sayit {
    return "world";
}
</code>```

The 2nd error occurs if the package main; say hello::sayit()... at bottom of file.

Bareword found where operator expected at helloWorld.pl line 20, near "say hello::sayit"

```<code>#!/usr/bin/perl
use strict;
#use warnings;
use warnings FATAL => 'all';

# new namespace called hello
package hello;
sub sayit {
    return "hello";
}

# new namespace called world
package world;
sub sayit {
    return "world";
}

# default namespace is main
package main;
say hello::sayit();
say world::sayit();
</code>```

答:
Can someone please explain what the default value is for Perl when the version is omitted?

use VERSION; has three purposes:

It performs a compile-time check of Perl's version.

[Only if VERSION is v5.10+] It enables features as if use feature ":VERSION"; had been specified.

[Only if VERSION is v5.12+] It enables strictures as if use strict; had been specified.

The default is to not perform any version checks, and to not enable any features or strictures.

Here I explain why the snippets you posted result in error.

When say was added to Perl, backwards compatibility prevented it from being made globally available by default. It would have broken scripts and modules that had a sub named say. For that reason, one must take steps to make say available before using it.

say can be made available using use feature qw( say );.

say can also be made available using use 5.10.0; (and higher) because this enables the say feature for you (among other things). This is why use 5.30.0; worked for you.

Alternatively, the feature need not be enabled to use CORE::say instead of say. (This requires 5.12+.)

$ perl -e'say "foo"'
String found where operator expected at -e line 1, near "say "foo""
        (Do you need to predeclare say?)
syntax error at -e line 1, near "say "foo""
Execution of -e aborted due to compilation errors.

$ perl -e'use feature qw( say ); say "foo"'
foo

$ perl -e'use 5.10.0; say "foo"'
foo

$ perl -e'CORE::say "foo"'
foo
```

This is documented.

Body:
NEWBIE: So today I started a tutorial on learning Perl and was doing okay until I got to the use #.###;

Can someone please explain what the default value is for Perl when the version is omitted?

When I put the value of use 5.30.0; the example will run. However if I do not specify the line at all I get the following two errors depending on the position of the main and calls to the sayit().

The 1st error occurs if the package main; say hello::sayit()... at top of file.

Can't locate object method "say" via package "hello::sayit" (perhaps you forgot to load "hello::sayit"?) at helloWorld.pl line 7.

#!/usr/bin/perl
use strict;
#use warnings;
use warnings FATAL => 'all';
# default namespace is main
package main;
say hello::sayit();
say world::sayit();

# new namespace called hello
package hello;
sub sayit {
    return "hello";
}

# new namespace called world
package world;
sub sayit {
    return "world";
}

The 2nd error occurs if the package main; say hello::sayit()... at bottom of file.

Bareword found where operator expected at helloWorld.pl line 20, near "say hello::sayit"

#!/usr/bin/perl
use strict;
#use warnings;
use warnings FATAL => 'all';

# new namespace called hello
package hello;
sub sayit {
    return "hello";
}

# new namespace called world
package world;
sub sayit {
    return "world";
}

# default namespace is main
package main;
say hello::sayit();
say world::sayit();

Body:
Can someone please explain what the default value is for Perl when the version is omitted?

use VERSION; has three purposes:

It performs a compile-time check of Perl's version.

[Only if VERSION is v5.10+] It enables features as if use feature ":VERSION"; had been specified.

[Only if VERSION is v5.12+] It enables strictures as if use strict; had been specified.

The default is to not perform any version checks, and to not enable any features or strictures.

Here I explain why the snippets you posted result in error.

When say was added to Perl, backwards compatibility prevented it from being made globally available by default. It would have broken scripts and modules that had a sub named say. For that reason, one must take steps to make say available before using it.

say can be made available using use feature qw( say );.

say can also be made available using use 5.10.0; (and higher) because this enables the say feature for you (among other things). This is why use 5.30.0; worked for you.

Alternatively, the feature need not be enabled to use CORE::say instead of say. (This requires 5.12+.)

$ perl -e'say "foo"'
String found where operator expected at -e line 1, near "say "foo""
        (Do you need to predeclare say?)
syntax error at -e line 1, near "say "foo""
Execution of -e aborted due to compilation errors.

$ perl -e'use feature qw( say ); say "foo"'
foo

$ perl -e'use 5.10.0; say "foo"'
foo

$ perl -e'CORE::say "foo"'
foo

This is documented.


问:
rust-how to combine this marco with loop/recursive?
I have some code like this:

macro_rules! match_token_pattern {
    ($parser:ident, $a:ident) => {{
        let a = $parser.$a();

        if a != None {
            Some(a)
        } else {
            None
        }
    }};

    ($parser:ident, $a:ident, $b:ident) => {{
        let a = $parser.$a();
        let b = $parser.$b();

        if a != None && b != None {
            Some((a, b))
        } else {
            None
        }
    }};

    ($parser:ident, $a:ident, $b:ident, $c:ident) => {{
        let a = $parser.$a();
        let b = $parser.$b();
        let c = $parser.$c();

        if a != None && b != None && c != None {
            Some((a, b, c))
        } else {
            None
        }
    }};
}
```

Can I combine the second/third rule to one?
And now I am tring use variable marco parameters, but the marco result() is like Some(a, Some(b, c)), or Some(a, Some(b, Some(c, d)))...

Thanks.

答:
We can start by writing a macro that accepts any number of arguments:

```<code>macro_rules! match_token_patten {
    ($parser:ident, $($arg:ident),*)) => {{
        /* macro body */
    }};
}
</code>```

$($arg:ident),* will capture any number identifiers, separated by commas.

Next, we need to compute the results for each method. A simple way to do this is to just store them in a tuple, e.g. (parser.a(), parser.b(), parser.c()). We'll use $( ... ),* syntax again to expand the captured variadic arguments:

```<code>macro_rules! match_token_patten {
    ($parser:ident, $($arg:ident),*)) => {{
        let results = ( $( $parser.$arg() ),* );
    }};
}
</code>```

Now we want to turn (Some(x), Some(y), ...) into a Some((x, y, ...)). We can use pattern matching for this! We can write this as:

```<code>if let (Some(a), Some(b), Some(c)) = results {
    // only if results is a tuple of three Some values
    Some((a, b, c)
} else {
    // at least one of the results is None
    None
}
</code>```

Finally, writing this in the variadic macro form, we get:

```<code>macro_rules! match_token_pattern {
    ($parser:ident, $($a:ident),*) => {{
        let results = ( $($parser.$a()),* );
        if let ( $(Some($a)),* ) = results {
            Some( ( $($a),* ) )
        } else {
            None
        }
    }};
}
</code>```

Body:
I have some code like this:

macro_rules! match_token_pattern {
    ($parser:ident, $a:ident) => {{
        let a = $parser.$a();

        if a != None {
            Some(a)
        } else {
            None
        }
    }};

    ($parser:ident, $a:ident, $b:ident) => {{
        let a = $parser.$a();
        let b = $parser.$b();

        if a != None && b != None {
            Some((a, b))
        } else {
            None
        }
    }};

    ($parser:ident, $a:ident, $b:ident, $c:ident) => {{
        let a = $parser.$a();
        let b = $parser.$b();
        let c = $parser.$c();

        if a != None && b != None && c != None {
            Some((a, b, c))
        } else {
            None
        }
    }};
}

Can I combine the second/third rule to one?
And now I am tring use variable marco parameters, but the marco result() is like Some(a, Some(b, c)), or Some(a, Some(b, Some(c, d)))...

Thanks.

Body:
We can start by writing a macro that accepts any number of arguments:

macro_rules! match_token_patten {
    ($parser:ident, $($arg:ident),*)) => {{
        /* macro body */
    }};
}

$($arg:ident),* will capture any number identifiers, separated by commas.

Next, we need to compute the results for each method. A simple way to do this is to just store them in a tuple, e.g. (parser.a(), parser.b(), parser.c()). We'll use $( ... ),* syntax again to expand the captured variadic arguments:

macro_rules! match_token_patten {
    ($parser:ident, $($arg:ident),*)) => {{
        let results = ( $( $parser.$arg() ),* );
    }};
}

Now we want to turn (Some(x), Some(y), ...) into a Some((x, y, ...)). We can use pattern matching for this! We can write this as:

if let (Some(a), Some(b), Some(c)) = results {
    // only if results is a tuple of three Some values
    Some((a, b, c)
} else {
    // at least one of the results is None
    None
}

Finally, writing this in the variadic macro form, we get:

macro_rules! match_token_pattern {
    ($parser:ident, $($a:ident),*) => {{
        let results = ( $($parser.$a()),* );
        if let ( $(Some($a)),* ) = results {
            Some( ( $($a),* ) )
        } else {
            None
        }
    }};
}


问:
XML layout in tab android (tabhost)
I'm trying to get a tabbed layout working on android. Using an example I managed to get the tabs working but my different tabs are in different activities. Each tab is similar, it's almost the same so I want them in the same activity.

I want an xml file in the layout folder as content.

This works, seperate classes:

```<code>tabSpec1.setIndicator("tabName1").setContent(new Intent(this, FirstTab.class));
</code>```

This doesn't work:

```<code>tabSpec2.setIndicator("tabName2").setContent(R.layout.tab);
</code>```

The setContent function accepts id's like that. The reference to tab is also in my R class. This is the XML in my tab:

```<code><?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is the tab from XML"/> </LinearLayout>
</code>```

答:
I think what you need is to have Views, not activities, in each tab. Try something like this...

In the tab activity:

```<code>/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_page_layout);

    //Setting up TabWidget
    Resources res = getResources();
    TabHost tabHost = getTabHost();
    TabHost.TabSpec spec;
    spec = tabHost.newTabSpec("firstTab")
            .setIndicator(res.getString(R.string.tab1_label), res.getDrawable(R.drawable.tab1_icon))
            .setContent(R.id.tab1_layout);
    tabHost.addTab(spec);
    spec = tabHost.newTabSpec("secondTab")
            .setIndicator(res.getString(R.string.tab2_label), res.getDrawable(R.drawable.tab2_icon))
            .setContent(R.id.tab2_layout);
    tabHost.addTab(spec);
    tabHost.setCurrentTab(0);
}
</code>```

In the tab_page_layout.xml file:

```<code>    <FrameLayout android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout android:id="@+id/tab1_layout"
        />
        <!--your stuff-->
        </LinearLayout>
        <LinearLayout android:id="@+id/tab2_layout"
        />
        <!--your stuff-->
        </LinearLayout>
    </FrameLayout>
</code>```

(The above is just a fragment, of course. You'll still need to include the TabWidget and use the appropriate identification)

Title: XML layout in tab android (tabhost)

Body:
I'm trying to get a tabbed layout working on android. Using an example I managed to get the tabs working but my different tabs are in different activities. Each tab is similar, it's almost the same so I want them in the same activity.

I want an xml file in the layout folder as content.

This works, seperate classes:

tabSpec1.setIndicator("tabName1").setContent(new Intent(this, FirstTab.class));

This doesn't work:

tabSpec2.setIndicator("tabName2").setContent(R.layout.tab);

The setContent function accepts id's like that. The reference to tab is also in my R class. This is the XML in my tab:

<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is the tab from XML"/> </LinearLayout>

Body:
I think what you need is to have Views, not activities, in each tab. Try something like this...

In the tab activity:

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_page_layout);

    //Setting up TabWidget
    Resources res = getResources();
    TabHost tabHost = getTabHost();
    TabHost.TabSpec spec;
    spec = tabHost.newTabSpec("firstTab")
            .setIndicator(res.getString(R.string.tab1_label), res.getDrawable(R.drawable.tab1_icon))
            .setContent(R.id.tab1_layout);
    tabHost.addTab(spec);
    spec = tabHost.newTabSpec("secondTab")
            .setIndicator(res.getString(R.string.tab2_label), res.getDrawable(R.drawable.tab2_icon))
            .setContent(R.id.tab2_layout);
    tabHost.addTab(spec);
    tabHost.setCurrentTab(0);
}

In the tab_page_layout.xml file:

    <FrameLayout android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout android:id="@+id/tab1_layout"
        />
        <!--your stuff-->
        </LinearLayout>
        <LinearLayout android:id="@+id/tab2_layout"
        />
        <!--your stuff-->
        </LinearLayout>
    </FrameLayout>

(The above is just a fragment, of course. You'll still need to include the TabWidget and use the appropriate identification)


问:
How to convert a List[List[Long]] to a List[List[Int]]?
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

```<code>val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
</code>```

how can it be converted to List[List[Int]]?

答:
You can also use cats lib for that and compose List functors

```<code>import cats.Functor
import cats.implicits._
import cats.data._

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

Functor[List].compose[List].map(l)(_.toInt)
//or
Nested(l).map(_.toInt).value
</code>```

and one more pure scala approach (not very safe, though)

```<code>val res:List[List[Int]] = l.asInstanceOf[List[List[Int]]]
</code>```

Body:
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

how can it be converted to List[List[Int]]?

Body:
You can also use cats lib for that and compose List functors

import cats.Functor
import cats.implicits._
import cats.data._

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

Functor[List].compose[List].map(l)(_.toInt)
//or
Nested(l).map(_.toInt).value

and one more pure scala approach (not very safe, though)

val res:List[List[Int]] = l.asInstanceOf[List[List[Int]]]