问:
catch .on('change) of textbox within modal
I have a modal that contains a text box. I would like to allow the user to simply type in the box and, when their input meets the requirement (length 4), call a function. The issue is the .on('change') function only seems to be processed when you click somewhere in the modal, or close the modal.

I am using bootstrap 3.3.7 and jquery 3.1.1

$('#signInModal').modal('show');

$('#signInModal-passwordText').on('change', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    //alert('4');
    signIn($(this).val());
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" tabindex="-1" role="dialog" id="signInModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Sign In</h4>
      </div>
      <div class="modal-body">
        <input id="signInModal-passwordText" type="password" class="form-control" />
        <span class="alert alert-danger" style="display: none;" role="alert" id="signInModal-failedSpan">Failed!</span>
      </div>
      <div class="modal-footer">
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal --></code>```

答:
I would use onkeyup since change needs a blur in many browsers to trigger:

Diffrence between keyup keydown keypress and input events

function signIn(val) { alert(val)}
$('#signInModal').modal('show');

$('#signInModal-passwordText').on('keyup', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    signIn($(this).val());
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" tabindex="-1" role="dialog" id="signInModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Sign In</h4>
      </div>
      <div class="modal-body">
        <input id="signInModal-passwordText" type="password" class="form-control" />
        <span class="alert alert-danger" style="display: none;" role="alert" id="signInModal-failedSpan">Failed!</span>
      </div>
      <div class="modal-footer">
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal --></code>```

Body:
I have a modal that contains a text box. I would like to allow the user to simply type in the box and, when their input meets the requirement (length 4), call a function. The issue is the .on('change') function only seems to be processed when you click somewhere in the modal, or close the modal.

I am using bootstrap 3.3.7 and jquery 3.1.1

$('#signInModal').modal('show');

$('#signInModal-passwordText').on('change', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    //alert('4');
    signIn($(this).val());
  }
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Sign In

        <input id="signInModal-passwordText" type="password" class="form-control" />
        Failed!

Body:
I would use onkeyup since change needs a blur in many browsers to trigger:

Diffrence between keyup keydown keypress and input events

function signIn(val) { alert(val)}
$('#signInModal').modal('show');

$('#signInModal-passwordText').on('keyup', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    signIn($(this).val());
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" tabindex="-1" role="dialog" id="signInModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Sign In</h4>
      </div>
      <div class="modal-body">
        <input id="signInModal-passwordText" type="password" class="form-control" />
        <span class="alert alert-danger" style="display: none;" role="alert" id="signInModal-failedSpan">Failed!</span>
      </div>
      <div class="modal-footer">
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->


来源: stackexchange

问:
How do I select a specific record from Many-to-many relationships which does not contain a specific item in Rails 2?
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

```<code>class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end
</code>```

What I want is to get a session which doesn't contain any specific session_type, eg.,

```<code>Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])
</code>```

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

```<code>select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id
</code>```

Any help will be appreciated.

Thanks.

答:
Try this:

```<code>Session.all(
  :include => :session_types,
  :conditions => ["session_types.id IS NOT NULL AND session_types.id != ?", 44])
)
</code>```

The include option uses LEFT JOIN hence this query will work.

ContentLicense: CC BY-SA 2.5

Body:
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end

What I want is to get a session which doesn't contain any specific session_type, eg.,

Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id

Any help will be appreciated.

Thanks.

Body:
Try this:

Session.all(
  :include => :session_types,
  :conditions => ["session_types.id IS NOT NULL AND session_types.id != ?", 44])
)

The include option uses LEFT JOIN hence this query will work.


问:
change table cell text to input value with jquery
I have a table in CRUD loaded from database, i want table rows to be editable by converting table cell to input field preserving cell text as input value. I am using jQuery for that.
So far i can add input field inside  tag. But data from all the cells becomes value of each input instead of becoming value of their respective input fields. Here is my code

```<code>$("#parEdit").click(function(){
$(this).text("Update");
$(this).closest('tr').children().wrapInner('<input type="text" value = ' + $('td').text() + '></input>');
    })
</code>```

table
ID| Name  | Position | Marks| Edit|

1 | Ahmad |   6th    |  525 | Edit Button|

After pressing Edit Button The output is like this

ID| Name  | Position | Marks| Edit|

1Ahmad6th525 | 1Ahmad6th525 | 1Ahmad6th525 | 1Ahmad6th525 | Update Button |

答:
You need apply the wrap to each td, your original code inserted every td text.</p>

```<code>$("#parEdit").click(function(){
   $(this).text("Update");
   $(this).closest('tr').children().each(function(){
      $(this).wrapInner('<input type="text" value = ' + $(this).text() + '></input>');
   });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table in CRUD loaded from database, i want table rows to be editable by converting table cell to input field preserving cell text as input value. I am using jQuery for that.
So far i can add input field inside  tag. But data from all the cells becomes value of each input instead of becoming value of their respective input fields. Here is my code

$("#parEdit").click(function(){
$(this).text("Update");
$(this).closest('tr').children().wrapInner('<input type="text" value = ' + $('td').text() + '></input>');
    })

table
ID| Name  | Position | Marks| Edit|

1 | Ahmad |   6th    |  525 | Edit Button|

After pressing Edit Button The output is like this

ID| Name  | Position | Marks| Edit|

1Ahmad6th525 | 1Ahmad6th525 | 1Ahmad6th525 | 1Ahmad6th525 | Update Button |

Body:
You need apply the wrap to each td, your original code inserted every td text.

$("#parEdit").click(function(){
   $(this).text("Update");
   $(this).closest('tr').children().each(function(){
      $(this).wrapInner('<input type="text" value = ' + $(this).text() + '></input>');
   });
});


问:
changing static variables from another method in java
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

```<code>public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}
</code>```

答:
You could write a class encapsulating your x, y, z as fields and convert your methods to its instance methods (that is, they should not be static anymore).

```<code>public class Calculation {
    private int x = 10, y = 20, z = 30;

    public boolean find()
    {
        x = 10;
        y = 20;
        z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    private void change(int changeX ,int changeY,int changeZ)
</code>```

and so on.

Then create an instance of it and call your methods on it:

```<code>Calculation calculation = new Calculation();
calculation.find();
...
</code>```

Body:
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}

Body:
You could write a class encapsulating your x, y, z as fields and convert your methods to its instance methods (that is, they should not be static anymore).

public class Calculation {
    private int x = 10, y = 20, z = 30;

    public boolean find()
    {
        x = 10;
        y = 20;
        z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    private void change(int changeX ,int changeY,int changeZ)

and so on.

Then create an instance of it and call your methods on it:

Calculation calculation = new Calculation();
calculation.find();
...


问:
Counting Duplicate Values for a CASE statement
In my query, I have a CASE statement where I want to cast the column as string value if condition matches. Also, I want to know the total number of duplicated values for that CASE statement's result.
For example:

```<code>select NULL as column_1,
   CASE WHEN name IS NOT NULL THEN CAST(name as string)
   ELSE '0' END as column_2,
    (select COUNT (cast(column_2 as string)) from input_table
     group by (cast(column_2 as string)) HAVING count(cast(column_2 as string)) > 1) as column_3
    from input_table
</code>```

Can I go for CASE statement and counting the condition output at the same time?
 Any suggestion please?

答:
I would use a CTE here. Not 100% clear on what your looking for but try this. </p>

```<code>;WITH Input_table as (

SELECT NULL AS column_1,
       CASE
           WHEN name IS NOT NULL
           THEN CAST(name AS STRING)
           ELSE '0'
       END AS column_2
)

select distinct Column_1, Column_2, count(Column_2) [Cnt] from Input_table
group by Column_1, Column_2
having count(Column_2) > 1
</code>```

Body:
In my query, I have a CASE statement where I want to cast the column as string value if condition matches. Also, I want to know the total number of duplicated values for that CASE statement's result.
For example:

select NULL as column_1,
   CASE WHEN name IS NOT NULL THEN CAST(name as string)
   ELSE '0' END as column_2,
    (select COUNT (cast(column_2 as string)) from input_table
     group by (cast(column_2 as string)) HAVING count(cast(column_2 as string)) > 1) as column_3
    from input_table

Can I go for CASE statement and counting the condition output at the same time?
 Any suggestion please?

Body:
I would use a CTE here. Not 100% clear on what your looking for but try this.

;WITH Input_table as (

SELECT NULL AS column_1,
       CASE
           WHEN name IS NOT NULL
           THEN CAST(name AS STRING)
           ELSE '0'
       END AS column_2
)

select distinct Column_1, Column_2, count(Column_2) [Cnt] from Input_table
group by Column_1, Column_2
having count(Column_2) > 1


问:
Unable to inspect/debug Qualtrics Javascript code in Firefox
I have added a very simple javascript/jQuery code in Qualtrics.  It is working fine.  But, for my own understanding and since I might be integrating more complex jQuery codes with Qualtrics in the future, I wanted to examine the flow in Firefox.  I tried both Firebug as well as the browser's inbuilt Web Developer tools, but I am unable to see any navigation into the javascript code.  In fact, Firebug is saying there are no javascript codes.

Following are my firefox and firebug versions:
Firefox 53.0.3
Firebug 2.0.19

Any help will be appreciated.

PS:  My Qualtrics code:

```<code>Qualtrics.SurveyEngine.addOnload(function()
{
   /*Place Your JavaScript Here*/

   var txtItem =jQuery("#hiddentext");

   if (txtItem.length ) {
        //alert("jquery retrieval worked - DOM element found");

        txtItem.fadeIn(5000);
        txtItem.css({"background-color": "yellow", "font-size": "200%", "display": "inline"});

    } else {
        alert("jquery retrieval did not work - DOM element NOT found");
    }
});
</code>```

答:
Firebug doesn't work anymore.  You'll have to use the built-in developer tools. If you are running under JFE in Qualtrics, add the following command to your script where you want to start stepping through.</p>

```<code>debugger;
</code>```

Body:
I have added a very simple javascript/jQuery code in Qualtrics.  It is working fine.  But, for my own understanding and since I might be integrating more complex jQuery codes with Qualtrics in the future, I wanted to examine the flow in Firefox.  I tried both Firebug as well as the browser's inbuilt Web Developer tools, but I am unable to see any navigation into the javascript code.  In fact, Firebug is saying there are no javascript codes.

Following are my firefox and firebug versions:
Firefox 53.0.3
Firebug 2.0.19

Any help will be appreciated.

PS:  My Qualtrics code:

Qualtrics.SurveyEngine.addOnload(function()
{
   /*Place Your JavaScript Here*/

   var txtItem =jQuery("#hiddentext");

   if (txtItem.length ) {
        //alert("jquery retrieval worked - DOM element found");

        txtItem.fadeIn(5000);
        txtItem.css({"background-color": "yellow", "font-size": "200%", "display": "inline"});

    } else {
        alert("jquery retrieval did not work - DOM element NOT found");
    }
});

Body:
Firebug doesn't work anymore.  You'll have to use the built-in developer tools. If you are running under JFE in Qualtrics, add the following command to your script where you want to start stepping through.

debugger;


问:
Java JTextfields
Just a quick question,
How do i ensure my JtextField only accepts numeric values?
I want it to to diplsy an error message if the user entered anything else
thank you</p>

答: Associate a key listener with the text field and check for the value just inserted. If value inserted is not an integer, then prompt error.</p>

Title: Java JTextfields


问:
Djangosaml2 configuration
Please help me for saml configuration for the OneLogin IdP with djangosml2 library(djangosaml2==0.14.5).

Once i come back on my app after successfully login it fails to parse xml response.

I'm getting error "SAML response has errors. Please check the logs"

Here is my configuration:-

```<code>SAML_CONFIG = {
  'xmlsec_binary': '/usr/bin/xmlsec1',
  'entityid': 'http://localhost:8006/saml2/metadata/',
  'service': {
      'sp' : {
          'name': 'Federated Django sample SP',
          'allow_unsolicited': True,
          'endpoints': {
              'assertion_consumer_service': [
                  ('http://localhost:8006/saml2/acs/',
                   saml2.BINDING_HTTP_POST),
                  ],
              'single_logout_service': [
                  ('http://localhost:8006/saml2/ls/',
                   saml2.BINDING_HTTP_REDIRECT),
                  ('http://localhost:8006/saml2/ls/post',
                   saml2.BINDING_HTTP_POST),
                  ],
              },
          'required_attributes': ['uid'],
          'optional_attributes': ['eduPersonAffiliation'],
          'idp': {
              'https://app.onelogin.com/saml/metadata/595757': {
                  'single_sign_on_service': {
                      saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-post/sso/595757',
                      },
                  'single_logout_service': {
                      saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-redirect/slo/595757',
                      },
                  },
              },
          },
      },
  'metadata': {
      'local': [os.path.join(BASE_DIR, 'new_onelogin_metadata.xml')],
      },
  'debug': 1,
  'cert_file': os.path.join(BASE_DIR, 'new_onelogin .pem'),
  'contact_person': [
      {'given_name': 'Lorenzo',
       'sur_name': 'Gil',
       'company': 'Yaco Sistemas',
       'email_address': 'lgs@yaco.es',
       'contact_type': 'technical'},
      {'given_name': 'Angel',
       'sur_name': 'Fernandez',
       'company': 'Yaco Sistemas',
       'email_address': 'angel@yaco.es',
       'contact_type': 'administrative'},
      ],
  'organization': {
      'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')],
      'display_name': [('Yaco', 'es'), ('Yaco', 'en')],
      'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')],
      },
  'valid_for': 24,
  }
</code>```

答:
I've has similar problems in the past.  If I remember correctly, the message "SAML response has errors. Please check the logs" doesn't mean the SP found something wrong with the response, it means the IDP is telling you something is wrong.  IE for some reason, the IDP is unhappy and letting you know.  If my memory is telling me the truth, I had this error when the SP and IDP couldn't agree on attribute names... maybe?  The SP was putting a friendlyname in the name property for the attributes it was requesting... or something like that.

Anyway, doubt this helps you since this was 6 months ago, but it might help someone in the future.

Title: Djangosaml2 configuration

Body:
Please help me for saml configuration for the OneLogin IdP with djangosml2 library(djangosaml2==0.14.5).

Once i come back on my app after successfully login it fails to parse xml response.

I'm getting error "SAML response has errors. Please check the logs"

Here is my configuration:-

SAML_CONFIG = {
  'xmlsec_binary': '/usr/bin/xmlsec1',
  'entityid': 'http://localhost:8006/saml2/metadata/',
  'service': {
      'sp' : {
          'name': 'Federated Django sample SP',
          'allow_unsolicited': True,
          'endpoints': {
              'assertion_consumer_service': [
                  ('http://localhost:8006/saml2/acs/',
                   saml2.BINDING_HTTP_POST),
                  ],
              'single_logout_service': [
                  ('http://localhost:8006/saml2/ls/',
                   saml2.BINDING_HTTP_REDIRECT),
                  ('http://localhost:8006/saml2/ls/post',
                   saml2.BINDING_HTTP_POST),
                  ],
              },
          'required_attributes': ['uid'],
          'optional_attributes': ['eduPersonAffiliation'],
          'idp': {
              'https://app.onelogin.com/saml/metadata/595757': {
                  'single_sign_on_service': {
                      saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-post/sso/595757',
                      },
                  'single_logout_service': {
                      saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-redirect/slo/595757',
                      },
                  },
              },
          },
      },
  'metadata': {
      'local': [os.path.join(BASE_DIR, 'new_onelogin_metadata.xml')],
      },
  'debug': 1,
  'cert_file': os.path.join(BASE_DIR, 'new_onelogin .pem'),
  'contact_person': [
      {'given_name': 'Lorenzo',
       'sur_name': 'Gil',
       'company': 'Yaco Sistemas',
       'email_address': 'lgs@yaco.es',
       'contact_type': 'technical'},
      {'given_name': 'Angel',
       'sur_name': 'Fernandez',
       'company': 'Yaco Sistemas',
       'email_address': 'angel@yaco.es',
       'contact_type': 'administrative'},
      ],
  'organization': {
      'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')],
      'display_name': [('Yaco', 'es'), ('Yaco', 'en')],
      'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')],
      },
  'valid_for': 24,
  }


问:
YouTube API v3 and php returns "The request did not specify any referer"
I have this PHP code.

```<code><?php

require 'vendor/autoload.php';

$youtube_api_key = 'MY_KEY';

$playlist_id = 'PL3BE743993147F061';

$client = new \Google_Client();
$client->setDeveloperKey($youtube_api_key);
$youtube = new \Google_Service_YouTube($client);

try {
    $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
        'id' => $playlist_id
    ));
    echo '```'.print_r($playlistResponse, true).'```';
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '<h1>error!</h1>';
    echo '```'.print_r($gse_errors, true).'```';
}
</code>```

If I did not enable Key restriction, this code works fine. But if I enable Key restriction it returns...

The request did not specify any referer. Please ensure that the client
  is sending referer or use the API Console to remove the referer
  restrictions.

How to enable Key restriction and make it work?

My 2nd test is...

```<code><?php

require 'vendor/autoload.php';

session_start();

$youtube_api_key = 'MY_KEY';
$oauth_client_id = 'MY_CLIENT_ID';
$oauth_client_secret = 'MY_CLIENT_SECRET';

$playlist_id = 'PL3BE743993147F061';

//$client = new \Google_Client();
//$client->setDeveloperKey($youtube_api_key);

$client = new Google_Client();
$client->setClientId($oauth_client_id);
$client->setClientSecret($oauth_client_secret);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new \Google_Service_YouTube($client);

$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

try {
    if ($client->getAccessToken()) {
        $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
            'id' => $playlist_id
        ));
        echo '```'.print_r($playlistResponse, true).'```';
    } else {
        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;

        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
        echo $htmlBody;
    }
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '<h1>error!</h1>';
    echo '```'.print_r($gse_errors, true).'```';
}
</code>```

This code works fine with Key restriction but it required ALL users to authenticate using oAuth just to view the playlist and tracks info which is not good for any visitors at all.

The same question. How to enable Key restriction and make it work? (Without require any guest/user/visitor action.)

referrer:

https://developers.google.com/youtube/v3/code_samples/php#set_and_retrieve_localized_playlist_metadata

https://developers.google.com/youtube/v3/docs/

答:
This worked for me

```<code>$referrer = 'my.domain';
$api_key = 'apikey';
$client = new Google_Client();
$client->setDeveloperKey($api_key);

$headers = array('Referer' => $referrer);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), 'headers' => $headers ));
$client->setHttpClient($guzzleClient);
</code>```

UPDATE ( to describe how I got to the code from above ):

I was receiving the same error response from the api request "The request did not specify any referrer". As the environment was local I've installed Charles Web Proxy ( as described in the repository instructions https://github.com/google/google-api-php-client/blob/master/README.md  ) and have checked the request headers - then I've noticed that the referrer header was missing.

Then I looked for a way to pass that header to the request and noticed that the Guzzle HTTP Client Class had an option for that.

I'm not sure if that's the right way or if it's just a hack but it worked for me and hoped to be helpful for someone.

Body:
I have this PHP code.

<?php

require 'vendor/autoload.php';

$youtube_api_key = 'MY_KEY';

$playlist_id = 'PL3BE743993147F061';

$client = new \Google_Client();
$client->setDeveloperKey($youtube_api_key);
$youtube = new \Google_Service_YouTube($client);

try {
    $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
        'id' => $playlist_id
    ));
    echo '
'.print_r($playlistResponse, true).'
';
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '
error!
';
    echo '
'.print_r($gse_errors, true).'
';
}

If I did not enable Key restriction, this code works fine. But if I enable Key restriction it returns...

The request did not specify any referer. Please ensure that the client
  is sending referer or use the API Console to remove the referer
  restrictions.

How to enable Key restriction and make it work?

My 2nd test is...

<?php

require 'vendor/autoload.php';

session_start();

$youtube_api_key = 'MY_KEY';
$oauth_client_id = 'MY_CLIENT_ID';
$oauth_client_secret = 'MY_CLIENT_SECRET';

$playlist_id = 'PL3BE743993147F061';

//$client = new \Google_Client();
//$client->setDeveloperKey($youtube_api_key);

$client = new Google_Client();
$client->setClientId($oauth_client_id);
$client->setClientSecret($oauth_client_secret);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new \Google_Service_YouTube($client);

$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

try {
    if ($client->getAccessToken()) {
        $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
            'id' => $playlist_id
        ));
        echo '
'.print_r($playlistResponse, true).'
';
    } else {
        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;

        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END

Authorization Required

You need to authorize access before proceeding.

END;
        echo $htmlBody;
    }
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '
error!
';
    echo '
'.print_r($gse_errors, true).'
';
}

This code works fine with Key restriction but it required ALL users to authenticate using oAuth just to view the playlist and tracks info which is not good for any visitors at all.

The same question. How to enable Key restriction and make it work? (Without require any guest/user/visitor action.)

referrer:

https://developers.google.com/youtube/v3/code_samples/php#set_and_retrieve_localized_playlist_metadata

https://developers.google.com/youtube/v3/docs/

Body:
This worked for me

$referrer = 'my.domain';
$api_key = 'apikey';
$client = new Google_Client();
$client->setDeveloperKey($api_key);

$headers = array('Referer' => $referrer);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), 'headers' => $headers ));
$client->setHttpClient($guzzleClient);

UPDATE ( to describe how I got to the code from above ):

I was receiving the same error response from the api request "The request did not specify any referrer". As the environment was local I've installed Charles Web Proxy ( as described in the repository instructions https://github.com/google/google-api-php-client/blob/master/README.md  ) and have checked the request headers - then I've noticed that the referrer header was missing.

Then I looked for a way to pass that header to the request and noticed that the Guzzle HTTP Client Class had an option for that.

I'm not sure if that's the right way or if it's just a hack but it worked for me and hoped to be helpful for someone.


问:
Close Python Thread To Prevent Memory Leak
How to I close a Python thread in order to make sure that everything in memory within a thread is cleared from memory? Currently, I have a list of threads that I join in the following manner:

```<code>for t in threadlist:
    t.join(5)
</code>```

These threads were originally created looping over a list of arguments to pass to each thread with myfunc which appends results to a list:

```<code>threadlist = []
for r in arglist:
    t = Thread(target=myfunc, args=(r,))
    t.daemon = True
    threadlist.append(t)
</code>```

When I look at what's in memory with pympler all manner of things in the function called by the thread remain in memory after this executes. I need it to garbage collect as it would if I called myfunc normally without threading.

答:
Resolved in comments:

The objects being deleted were contained within an object function.

  Moving them outside of that object function and

  into a regular function allowed garbage collecting to occur following delete.

  Michael

Body:
How to I close a Python thread in order to make sure that everything in memory within a thread is cleared from memory? Currently, I have a list of threads that I join in the following manner:

for t in threadlist:
    t.join(5)

These threads were originally created looping over a list of arguments to pass to each thread with myfunc which appends results to a list:

threadlist = []
for r in arglist:
    t = Thread(target=myfunc, args=(r,))
    t.daemon = True
    threadlist.append(t)

When I look at what's in memory with pympler all manner of things in the function called by the thread remain in memory after this executes. I need it to garbage collect as it would if I called myfunc normally without threading.


问:
Getting data to display in shiny using rmarkdown
I am making a shiny app that uses rMarkdown, which is a little different than making a straight shiny app in that you don't use a ui and server section.

I want to display a table in Shiny using rMarkdown.

```<code>---
runtime: shiny
output: html_document
---

### Data

```{r echo=FALSE}
n <- c(2, 3, 5)
s <- c("aa", "bb", "cc")
b <- c(TRUE, FALSE, TRUE)
myDataFrame <- data.frame(n,s,b)

tableOutput("view")
textOutput("message")

output$view <-renderTable({myDataFrame})

output$message <- renderText({"test test test"})
```

The table "view" and the message "message" are not displaying.

答:
Just drop the assignment:

```<code>```{r echo=FALSE}
n <- c(2, 3, 5)
s <- c("aa", "bb", "cc")
b <- c(TRUE, FALSE, TRUE)
myDataFrame <- data.frame(n,s,b)

tableOutput("view")
textOutput("message")

renderTable({myDataFrame})

renderText({"test test test"})
```
</code>```

Body:
I am making a shiny app that uses rMarkdown, which is a little different than making a straight shiny app in that you don't use a ui and server section.

I want to display a table in Shiny using rMarkdown.

---
runtime: shiny
output: html_document
---

### Data

```{r echo=FALSE}
n <- c(2, 3, 5)
s <- c("aa", "bb", "cc")
b <- c(TRUE, FALSE, TRUE)
myDataFrame <- data.frame(n,s,b)

tableOutput("view")
textOutput("message")

output$view <-renderTable({myDataFrame})

output$message <- renderText({"test test test"})

The table "view" and the message "message" are not displaying.

Body:
Just drop the assignment:

```{r echo=FALSE}
n <- c(2, 3, 5)
s <- c("aa", "bb", "cc")
b <- c(TRUE, FALSE, TRUE)
myDataFrame <- data.frame(n,s,b)

tableOutput("view")
textOutput("message")

renderTable({myDataFrame})

renderText({"test test test"})
```


问:
Excel: Protect password not compatible with VBA password?
I know of the 2 possible ways to password-protect sheets in Excel -

Manual Password protect

Password protect using VBA

This is where I'm stumped. I have password-protected a sheet using VBA and then tried to unprotect it manually with the same password used in VBA. But Excel throws an error saying that the password provided is incorrect. I tried the opposite as well - Protected the file manually and then tried to unprotect using VBA providing the right password in the code; same error. Any ideas why this is happening?

答: If I am understanding your question correctly, it happens because each password is protecting something different. They are not the same thing. You can have a workbook that is not password protected but the VBA code is password protected.


问:
TRACE Macro Not Compiled Out Properly in Release Build - C++
When I do a Release build of my Visual Studio 2008 solution I get a bunch of errors like this:

error C2059: syntax error : ','

This is how I typically use TRACE:

```<code>TRACE(_T("My error message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
</code>```

There is also an instance where I use it with 5 parameters.

I thought TRACE was suppose to compile out completely for Release builds.  What do I need to do to make it compile out complete?  Thanks.

答:
First of all, it's __FILE__ as far as I know, not __WFILE__. that is why you get that comma error. Since preprocessor is unable to find it.

Second, why do you write the last three parameters in each TRACE? TRACE is a MACRO, right?

So you can define it like this: (also see the define __WFILE__ macro)

```<code>#define FULL_TRACE   //define FULL_TRACE here
#define __WFILE__  L##__FILE__ //since __WFILE__ is not a real macro in MCVC++
#define TRACE(msg) FULL_TRACE(msg, ::GetLastError(), __WFILE__, __FUNCTION__, __LINE__)
</code>```

Now, you can TRACE like this

```<code>TRACE("Error in I/O file")
</code>```

And you're done!

Body:
When I do a Release build of my Visual Studio 2008 solution I get a bunch of errors like this:

error C2059: syntax error : ','

This is how I typically use TRACE:

TRACE(_T("My error message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);

There is also an instance where I use it with 5 parameters.

I thought TRACE was suppose to compile out completely for Release builds.  What do I need to do to make it compile out complete?  Thanks.

Body:
First of all, it's __FILE__ as far as I know, not __WFILE__. that is why you get that comma error. Since preprocessor is unable to find it.

Second, why do you write the last three parameters in each TRACE? TRACE is a MACRO, right?

So you can define it like this: (also see the define __WFILE__ macro)

#define FULL_TRACE   //define FULL_TRACE here
#define __WFILE__  L##__FILE__ //since __WFILE__ is not a real macro in MCVC++
#define TRACE(msg) FULL_TRACE(msg, ::GetLastError(), __WFILE__, __FUNCTION__, __LINE__)

Now, you can TRACE like this

TRACE("Error in I/O file")

And you're done!


问:
vb linq select from two datatables using left join with grouping and giving Sum
I have create a linq allowing select from tabRealisation left join tabRealisation

```<code> Dim query =
    (From r In tabRealisation.AsEnumerable
     Group Join p In tabPrevision.AsEnumerable
     On r.Field(Of Integer)("code_part") Equals p.Field(Of Integer)("code_part")
     Into Group
     Let p = Group.FirstOrDefault
     Select
            nom_ville = r.Field(Of String)("nom_ville"),
            Designation_part = r.Field(Of String)("Designation_part"),
            NbrR = r.Field(Of Integer)("UniteVendu"),
            CaR = r.Field(Of Double?)("CAVendu"),
            NbrP = p.Field(Of Integer)("UniteVentePrev"),
            CaP = p.Field(Of Double?)("CAVentePrev")
            ).ToList
</code>```

But what i want is to transform this query to get Sum("UniteVendu"),Sum("CAVendu"),... grouping by "code_part"

答:
Try this</p>

```<code>Dim query =
        (From r In tabRealisation.AsEnumerable
         Join p In tabPrevision.AsEnumerable
         On r.Field(Of Integer)("code_part") Equals p.Field(Of Integer)("code_part")
         Select
                nom_ville = r.Field(Of String)("nom_ville"),
                Designation_part = r.Field(Of String)("Designation_part"),
                NbrR = r.Field(Of Integer)("UniteVendu"),
                CaR = r.Field(Of Double?)("CAVendu"),
                NbrP = p.Field(Of Integer)("UniteVentePrev"),
                CaP = p.Field(Of Double?)("CAVentePrev"),
                codePart = r.Field(Of Integer)("code_part")
         ).GroupBy(Function(x) x.codePart).Select(Function(x) New With { _
                                                      .codepart = x.Key,
                                                      .NbrRSum = x.Sum(Function(y) y.NbrR),
                                                      .CarSum = x.Sum(Function(y) y.CaR)
                                                  ).ToList()
</code>```

Body:
I have create a linq allowing select from tabRealisation left join tabRealisation

 Dim query =
    (From r In tabRealisation.AsEnumerable
     Group Join p In tabPrevision.AsEnumerable
     On r.Field(Of Integer)("code_part") Equals p.Field(Of Integer)("code_part")
     Into Group
     Let p = Group.FirstOrDefault
     Select
            nom_ville = r.Field(Of String)("nom_ville"),
            Designation_part = r.Field(Of String)("Designation_part"),
            NbrR = r.Field(Of Integer)("UniteVendu"),
            CaR = r.Field(Of Double?)("CAVendu"),
            NbrP = p.Field(Of Integer)("UniteVentePrev"),
            CaP = p.Field(Of Double?)("CAVentePrev")
            ).ToList

But what i want is to transform this query to get Sum("UniteVendu"),Sum("CAVendu"),... grouping by "code_part"

Body:
Try this

Dim query =
        (From r In tabRealisation.AsEnumerable
         Join p In tabPrevision.AsEnumerable
         On r.Field(Of Integer)("code_part") Equals p.Field(Of Integer)("code_part")
         Select
                nom_ville = r.Field(Of String)("nom_ville"),
                Designation_part = r.Field(Of String)("Designation_part"),
                NbrR = r.Field(Of Integer)("UniteVendu"),
                CaR = r.Field(Of Double?)("CAVendu"),
                NbrP = p.Field(Of Integer)("UniteVentePrev"),
                CaP = p.Field(Of Double?)("CAVentePrev"),
                codePart = r.Field(Of Integer)("code_part")
         ).GroupBy(Function(x) x.codePart).Select(Function(x) New With { _
                                                      .codepart = x.Key,
                                                      .NbrRSum = x.Sum(Function(y) y.NbrR),
                                                      .CarSum = x.Sum(Function(y) y.CaR)
                                                  ).ToList()


问:
JavaScript: Login on website using autohotkey
I am new to javascript and autohotkey programmation. I am trying to log into a website, but so far I am unable to submit the form properly.

Here is the HTML of the page :

     <form ng-show="!maintenanceCritique" class="form ng-pristine ng-valid-pattern ng-valid-maxlength ng-valid ng-valid-required" name="formMobile" ng-submit="login(formMobile)" novalidate="" touch-submit="">

                    Code permanent

                  <input style="width:100%" name="codePermanent" ng-model="user.codePermanent" ng-pattern="/^[A-Za-z]{4}(0[1-9]|[12][0-9]|3[01]|6[3-9]|[78][0-9]|9[0-3]|99)([0,5][1-9]|[1,6][012]|13|63)[0-9]{4}$/" maxlength="12" tabindex="1" placeholder="(ex. : ABDC12034566)" autofocus="" required="" class="ng-pristine ng-valid-pattern ng-valid-maxlength ng-not-empty ng-valid ng-valid-required ng-touched">

                    NIP

                  <input style="width:100%" type="password" name="password" ng-model="user.password" ng-pattern="/^[0-9]{5}$/" maxlength="5" tabindex="2" placeholder="(ex. : 12345)" required="" class="ng-pristine ng-valid-pattern ng-valid-maxlength ng-not-empty ng-valid ng-valid-required ng-touched">

                      <button class="btn btn-default btn-inverse btn-lg btn-login text-uppercase" type="submit" click="submitted=true" tabindex="3">
                        Connexion
                     </button>

     </form>

```
</div>
</div>
</p>

<p>And here is my code : </p>

```WB := ComObjCreate("InternetExplorer.Application")
WB.Visible := True
WB.Navigate(URL)

loop
If !WB.busy
 break
sleep 1000

WB.document.getElementsByName("codePermanent")[0].focus()
WB.document.getElementsByName("codePermanent")[0].value := "username"
sleep 1000
WB.document.getElementsByName("password")[0].focus()
WB.document.getElementsByName("password")[0].value := "password"

form := WB.document.getElementsByName("form")[0]
form.method := "post"
form.submit()
```

答:
You can try this:

```<code>wb.document.getElementsByClassName("btn btn-default btn-inverse btn-lg btn-login text-uppercase")[0].click()
</code>```

This will click the submit button if that button is the first one on the page with that class name. Remeber, getElementsByClassName() returns a nodelist, so you have to specify which specific element you're wanting to click by including its reference in the square brackets.

From there, it's just a matter of using the .click() method.

If this answers your question, please mark the question answered.
If not, let me know so we can get it answered.

Body:
I am new to javascript and autohotkey programmation. I am trying to log into a website, but so far I am unable to submit the form properly.

Here is the HTML of the page :

     <form ng-show="!maintenanceCritique" class="form ng-pristine ng-valid-pattern ng-valid-maxlength ng-valid ng-valid-required" name="formMobile" ng-submit="login(formMobile)" novalidate="" touch-submit="">

                    Code permanent

                  <input style="width:100%" name="codePermanent" ng-model="user.codePermanent" ng-pattern="/^[A-Za-z]{4}(0[1-9]|[12][0-9]|3[01]|6[3-9]|[78][0-9]|9[0-3]|99)([0,5][1-9]|[1,6][012]|13|63)[0-9]{4}$/" maxlength="12" tabindex="1" placeholder="(ex. : ABDC12034566)" autofocus="" required="" class="ng-pristine ng-valid-pattern ng-valid-maxlength ng-not-empty ng-valid ng-valid-required ng-touched">

                    NIP

                  <input style="width:100%" type="password" name="password" ng-model="user.password" ng-pattern="/^[0-9]{5}$/" maxlength="5" tabindex="2" placeholder="(ex. : 12345)" required="" class="ng-pristine ng-valid-pattern ng-valid-maxlength ng-not-empty ng-valid ng-valid-required ng-touched">

                      <button class="btn btn-default btn-inverse btn-lg btn-login text-uppercase" type="submit" click="submitted=true" tabindex="3">
                        Connexion
                     </button>

     </form>

And here is my code :

WB := ComObjCreate("InternetExplorer.Application")
WB.Visible := True
WB.Navigate(URL)

loop
If !WB.busy
 break
sleep 1000

WB.document.getElementsByName("codePermanent")[0].focus()
WB.document.getElementsByName("codePermanent")[0].value := "username"
sleep 1000
WB.document.getElementsByName("password")[0].focus()
WB.document.getElementsByName("password")[0].value := "password"

form := WB.document.getElementsByName("form")[0]
form.method := "post"
form.submit()

Body:
You can try this:

wb.document.getElementsByClassName("btn btn-default btn-inverse btn-lg btn-login text-uppercase")[0].click()

This will click the submit button if that button is the first one on the page with that class name. Remeber, getElementsByClassName() returns a nodelist, so you have to specify which specific element you're wanting to click by including its reference in the square brackets.

From there, it's just a matter of using the .click() method.

If this answers your question, please mark the question answered.
If not, let me know so we can get it answered.


问:
Move a button by setting CSS using Javascript

 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

 ```

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

答:
Use this in your moveButtonRand() function:

```<code>buttonTag[0].style.top=positionTop+"%";
buttonTag[0].style.left=positionLeft+"%";
</code>```

Or add an ID to that button, then use:

```<code>var buttonTag=document.getElementById('id_button2');
</code>```

Body:
 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

Body:
Use this in your moveButtonRand() function:

buttonTag[0].style.top=positionTop+"%";
buttonTag[0].style.left=positionLeft+"%";

Or add an ID to that button, then use:

var buttonTag=document.getElementById('id_button2');


问:
Find out if a Security Account Manager (SAM) name is a user or a group
edited from original question because the real problem was something unrelated to the question

I got a list of trustees from NTFS permissions and now I want to expand the groups to show membership. If I have a SAM name like MyDomain\name, there's no indication of whether that is a group or not. The Get-ADobject command has an ObjectClass property which will indicate group or user if this is an Active Directory domain object. One can use:
Get-ADObject -filter 'SamAccountName -eq "My Users"' or
$sam = "My Users"
Get-ADObject -filter 'SamAccountName -eq $sam'
Thanks to JPBlanc who had an alternate form of writing that with a script block and some other suggestions.
And thanks, user2142466. That looks like a good suggestion for my original script.

答:
I was asked to list all members of the groups, along with their ID,        Name, and Description as well, so I added a couple of lines.  </p>

```<code>cls
$Users = @()
$Groups = @()
$list = Get-Content z:\pcm2.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
  If ($ObjectClass -eq "User")
  {
  $U = Get-ADUser -Properties * -Identity $o
  $User = "" | Select FullUserName, LoginID, Description
  $User.FullUserName = $U.DisplayName
  $User.LoginID = $U.SamAccountName
  $User.Description = $U.description
  $Users += $User
  }
 Else
 {
 If ($ObjectClass -eq "Group")
 {
 $G = Get-ADGroup -Properties * -Identity $o
 $GM = Get-ADGroupMember -Identity $G.name -Recursive | Get-ADUser -Properties *
 Foreach ($gmember in $GM)
 {
 $Group = "" | Select GroupName, GroupDescription, GroupMemberName, GroupMemberLoginID, GroupMemberDesc
 $Group.GroupName = $G.Name
 $Group.GroupDescription = $G.Description
 $Group.GroupMemberName = $gmember.Name
 $Group.GroupMemberLoginID = $gmember.SamAccountName
 $Group.GroupMemberDesc = $gmember.Description
 $Groups += $Group
 }
}
}
}
$Users | Export-Csv z:\PCMUsers.csv -NoTypeInformation
$Groups | Export-Csv z:\PCMGroups.csv -NoTypeInformation
</code>```

Body:
I was asked to list all members of the groups, along with their ID,        Name, and Description as well, so I added a couple of lines.

cls
$Users = @()
$Groups = @()
$list = Get-Content z:\pcm2.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
  If ($ObjectClass -eq "User")
  {
  $U = Get-ADUser -Properties * -Identity $o
  $User = "" | Select FullUserName, LoginID, Description
  $User.FullUserName = $U.DisplayName
  $User.LoginID = $U.SamAccountName
  $User.Description = $U.description
  $Users += $User
  }
 Else
 {
 If ($ObjectClass -eq "Group")
 {
 $G = Get-ADGroup -Properties * -Identity $o
 $GM = Get-ADGroupMember -Identity $G.name -Recursive | Get-ADUser -Properties *
 Foreach ($gmember in $GM)
 {
 $Group = "" | Select GroupName, GroupDescription, GroupMemberName, GroupMemberLoginID, GroupMemberDesc
 $Group.GroupName = $G.Name
 $Group.GroupDescription = $G.Description
 $Group.GroupMemberName = $gmember.Name
 $Group.GroupMemberLoginID = $gmember.SamAccountName
 $Group.GroupMemberDesc = $gmember.Description
 $Groups += $Group
 }
}
}
}
$Users | Export-Csv z:\PCMUsers.csv -NoTypeInformation
$Groups | Export-Csv z:\PCMGroups.csv -NoTypeInformation


问:
How to optimize an hybrid Mobile App for slow internet connections
I have an ionic mobile application that has been developed, but it throws a lot of connection error when used on phones with poor internet connection.

Is there a way I can optimize my application to function well on devices with poor internet connection. i.e (GPRS or EDGE connection)

答:
You can convert your http calls to contain a longer timeout (here 3 minutes in ms). Also make sure you handle the error case gracefully.

this.http.get(url)
    .timeout(180000)
    .map(...)
    .subcribe(
        (success) => {...},
        (err) => { // Deal here with timeout error.
    }
);
```

Also make sure you cache any data that can be reused using ionic-storage, like fonts, images, JSON responses, etc.

Body:
You can convert your http calls to contain a longer timeout (here 3 minutes in ms). Also make sure you handle the error case gracefully.

this.http.get(url)
    .timeout(180000)
    .map(...)
    .subcribe(
        (success) => {...},
        (err) => { // Deal here with timeout error.
    }
);

Also make sure you cache any data that can be reused using ionic-storage, like fonts, images, JSON responses, etc.


问:
How do I change the color of all the elements (onHover) in a  even though some are wrapped in ?
The implementation is here: http://jsfiddle.net/chp8y/1/

If you hover over the first box, #1, you will see the 'Add Client' change color but the #1 won't. How do I achieve that without using JS ?

If you do a .sit-in-the-corner:hover it will only work when you hover over the 1. But that's not what I want.

Thoughts?

答:
Isn't it a case of changing the last rule to:</p>

```<code>table td:hover, table td:hover span {
      color: #aa5650;
}
</code>```

Title: How do I change the color of all the elements (onHover) in a <td> even though some are wrapped in <span>?

Body:
Isn't it a case of changing the last rule to:

table td:hover, table td:hover span {
      color: #aa5650;
}


问:
Cordova Media Plugin not working
I can't get the cordova media plugin to work, I get error code 1 which signals that the file is not getting loaded. I've tried a number of variations, but can't figure out which path is correct.

Currently my code looks like this:

```<code>function onDeviceMediaReady () {
var path = window.cordova.file.applicationDirectory + 'why.mp3';
    console.log(path);
    narrative = new Media(path, // success callback
        function() {
            console.log("playAudio():Audio Success");
        },

        // error callback
        function(err) {
            console.log("playAudio():Audio Error: "+ err.code);
        });
}
</code>```

this gives me a path that's file://var/cotainers/Bundle/Application/[GUID]/Cordova400.app/why.mp3

I don't get why I can't find it. the file is in the telerik appbuilder root directory.

答: If you're using appBuilder to test your app te aplication folder is the telerik folder, you must deploy your app as APK and test the folder</p>

Title: Cordova Media Plugin not working

Body:
I can't get the cordova media plugin to work, I get error code 1 which signals that the file is not getting loaded. I've tried a number of variations, but can't figure out which path is correct.

Currently my code looks like this:

function onDeviceMediaReady () {
var path = window.cordova.file.applicationDirectory + 'why.mp3';
    console.log(path);
    narrative = new Media(path, // success callback
        function() {
            console.log("playAudio():Audio Success");
        },

        // error callback
        function(err) {
            console.log("playAudio():Audio Error: "+ err.code);
        });
}

this gives me a path that's file://var/cotainers/Bundle/Application/[GUID]/Cordova400.app/why.mp3

I don't get why I can't find it. the file is in the telerik appbuilder root directory.


问:
Copy files with MsBuild
I have a solution with two projects. One of them is a simple project that doesn't depend on any special assemblies to build. However, the application is allowed to launch an external executable (that I also own -- this is the second project of my solution). When I build the project, I would like the executable (+ dependencies such as app.config) of the external project to be copied under the target directory of my project.

How can I achieve this with MsBuild? My first idea was to add a reference to the executable (even though I don't need it to build) to copy the file. This seem a bit hacky to me.

Thanks!

P.S. Another question: Let's say that I can tell MsBuild to copy the executable. What if the executable isn't build? Can I force it to build?

答:
In your case you should make your MSBuild script replace your solution and declare the desired dependency there:

```<code><Project DefaultTargets="Executable_A">
    <Target Name="Executable_A" DependsOnTargets="Executable_B">
        <MSBuild Projects="Executable_A.proj" Targets="Build" />
    </Target>

    <Target Name="Executable_B">
        <MSBuild Projects="Executable_B.proj" Targets="Build">
            <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuilt" />
        </MSBuild>
        <Copy SourceFiles="@(AssembliesBuilt)" DestinationFolder="C:\My_Target_Path\" SkipUnchangedFiles="true" />
    </Target>
</Project>
</code>```

... and you can instruct the target of your second project to copy its output to the desired location. You could even instruct your first project to store its output path into a variable to use when copying the output of your second project (DestinationFolder).

Title: Copy files with MsBuild

Body:
In your case you should make your MSBuild script replace your solution and declare the desired dependency there:

<Project DefaultTargets="Executable_A">
    <Target Name="Executable_A" DependsOnTargets="Executable_B">
        <MSBuild Projects="Executable_A.proj" Targets="Build" />
    </Target>

    <Target Name="Executable_B">
        <MSBuild Projects="Executable_B.proj" Targets="Build">
            <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuilt" />
        </MSBuild>
        <Copy SourceFiles="@(AssembliesBuilt)" DestinationFolder="C:\My_Target_Path\" SkipUnchangedFiles="true" />
    </Target>
</Project>

... and you can instruct the target of your second project to copy its output to the desired location. You could even instruct your first project to store its output path into a variable to use when copying the output of your second project (DestinationFolder).


问:
Referencing symbols in other files using PPC assembly
How can you reference a symbol external to the current file in ppc assembly? I've tried looking at the .extern keyword as well as adding a new symbol in the linker file but with no success.

I have two ppc assembly files that are part of a larger project. I wish to reference a symbol (__head) in file1 from file2 in this way:

file1.S:

```<code>    .section ".head","ax"

    . = 0
.global __head
__head:
</code>```

file2.S:

```<code>    .section ".head","ax"
...
    LOAD_32(%r3, file2_symbol_name - __head)
</code>```

where LOAD_32 is

```<code>#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;
</code>```

...but am getting the following error:

```<code>file2.S: Assembler messages:
file2.S:113: Error: can't resolve `file2_symbol_name' {.head section} - `__head' {*UND* section}
file2.S:113: Error: expression too complex
</code>```

When used in file1 LOAD_32(%r3, file1_symbol_name - __head) works just fine so I know I'm not importing the symbol name correctly.  How can I do this?

EDIT:

I have reduced my problem to the bare minimum parts so that I am clear about the problem. Below is all of the code, linker file, Makefile, and the terminal output for "make quick".

NB: When I comment out line 9 of other.S the project compiles without error.

head.S:

```<code>#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

    . = 0x0

.global __head
__head:
    LOAD_32(%r3, file1_symbol_name - __head)
    b   .

file1_symbol_name:
    b   .
</code>```

other.S

```<code>#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

.global other
other:
    LOAD_32(%r3, file2_symbol_name)
    LOAD_32(%r3, file2_symbol_name - __head)
    b   .

file2_symbol_name:
    b   .
</code>```

asm-defines.h:

```<code>#ifndef ASM_DEFINES_H
#define ASM_DEFINES_H

/* Load an immediate 32-bit value into a register */
#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

#endif //ASM_DEFINES_H
</code>```

quick.lds

```<code>ENTRY(__head);
</code>```

Makefile

```<code>CC=$(CROSS)gcc
QFLAGS := -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib

quick:
    $(CC) $(QFLAGS) -T quick.lds head.S other.S -o quick.o
</code>```

$(CROSS) is a path to the cross compiler which I have omitted.
The CC is powerpc64le-buildroot-linux-gnu-gcc

Terminal

```<code>$ make quick
powerpc64le-buildroot-linux-gnu-gcc -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib -T quick.lds head.S other.S -o quick.o
other.S: Assembler messages:
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
make: *** [quick] Error 1
</code>```

答: The assembler cannot know the placement / relative position of head.S and other.S at assembly time to be able to compute the relative displacement of the file2_symbol_name and __head labels.  This is a general assembly language question, not PPC specific.</p>

Body:
How can you reference a symbol external to the current file in ppc assembly? I've tried looking at the .extern keyword as well as adding a new symbol in the linker file but with no success.

I have two ppc assembly files that are part of a larger project. I wish to reference a symbol (__head) in file1 from file2 in this way:

file1.S:

    .section ".head","ax"

    . = 0
.global __head
__head:

file2.S:

    .section ".head","ax"
...
    LOAD_32(%r3, file2_symbol_name - __head)

where LOAD_32 is

#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

...but am getting the following error:

file2.S: Assembler messages:
file2.S:113: Error: can't resolve `file2_symbol_name' {.head section} - `__head' {*UND* section}
file2.S:113: Error: expression too complex

When used in file1 LOAD_32(%r3, file1_symbol_name - __head) works just fine so I know I'm not importing the symbol name correctly.  How can I do this?

EDIT:

I have reduced my problem to the bare minimum parts so that I am clear about the problem. Below is all of the code, linker file, Makefile, and the terminal output for "make quick".

NB: When I comment out line 9 of other.S the project compiles without error.

head.S:

#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

    . = 0x0

.global __head
__head:
    LOAD_32(%r3, file1_symbol_name - __head)
    b   .

file1_symbol_name:
    b   .

other.S

#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

.global other
other:
    LOAD_32(%r3, file2_symbol_name)
    LOAD_32(%r3, file2_symbol_name - __head)
    b   .

file2_symbol_name:
    b   .

asm-defines.h:

#ifndef ASM_DEFINES_H
#define ASM_DEFINES_H

/* Load an immediate 32-bit value into a register */
#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

#endif //ASM_DEFINES_H

quick.lds

ENTRY(__head);

Makefile

CC=$(CROSS)gcc
QFLAGS := -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib

quick:
    $(CC) $(QFLAGS) -T quick.lds head.S other.S -o quick.o

$(CROSS) is a path to the cross compiler which I have omitted.
The CC is powerpc64le-buildroot-linux-gnu-gcc

Terminal

$ make quick
powerpc64le-buildroot-linux-gnu-gcc -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib -T quick.lds head.S other.S -o quick.o
other.S: Assembler messages:
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
make: *** [quick] Error 1


问:
In C language, Structure, subtle difference in definition
I have seen format below for defining a structure

```<code>typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
};
</code>```

Some places I see the format below for defining a structure

```<code>typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;
</code>```

and some places I see the format below for defining a structure

```<code>typedef struct
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;
</code>```

If you notice the Tag syntax is after struct and also at the closing brace.

Questions.

1) What is the difference between the 3?

2) Is one preferred over the other or When are the best conditions you may want to use one over the other?

答:
According to the C Standard (6.2.3 Name spaces of identifiers)

1 If more than one declaration of a particular identifier is visible
  at any point in a translation unit, the syntactic context
  disambiguates uses that refer to different entities. Thus, there are
  separate name spaces for various categories of identifiers, as
  follows:

— label names (disambiguated by the syntax of the label declaration
  and use);

— the tags of structures, unions, and enumerations (disambiguated by
  following any32) of the keywords struct, union, or enum);

— the members of structures or unions; each structure or union has a
  separate name space for its members (disambiguated by the type of the
  expression used to access the member via the . or -> operator);

— all other identifiers, called ordinary identifiers (declared in
  ordinary declarators or as enumeration constants).

This is

```<code>struct Tag
{
  type Tag;
  <and so on..>
};
</code>```

a structure declaration with the name Tag and at the same time it is a structure definition because it not only introduces the type struct Tag but also declares its members.

You may at first declare a structure and then define it. For example

```<code>#include <stdio.h>

struct Tag;

struct Tag
{
    int Tag;
};

int main(void)
{
    struct Tag Tag = { .Tag = 10 };

    printf( "Tag.Tag = %d\n", Tag.Tag );

    return 0;
}
</code>```

The program output is

```<code>Tag.Tag = 10
</code>```

In this declaration

```<code>struct Tag
{
  type Tag;
  <and so on..>
} Tag;
</code>```

there is declared an object of the type struct Tag with the identifier Tag. The structure has a data member with name Tag. Thus there are declared two entities: a type struct Tag and an object with the name Tag of the structure type.

In this declaration

```<code>struct
{
  type Tag;
  <and so on..>
} Tag;
</code>```

there is declared an object of unnamed structure type with the identifier Tag. The problem with this declaration is that you can not refer to the type of the object.

You can meet one more declaration like

```<code>typedef struct Tag
{
  type Tag;
  <and so on..>
} Tag;
</code>```

In this typedef declaration the identifier Tag serves as an alias of the type struct Tag.

Or

```<code>typedef struct
{
  type Tag;
  <and so on..>
} Tag;
</code>```

In this typedef declaration the identifier Tag serves as an alias of the unnamed structure type.

The C 2011 allows to declare anonymous structures.
From the C Standard (6.7.2.1 Structure and union specifiers)

13 An unnamed member of structure type with no tag is called an
  anonymous structure; an unnamed member of union type with no tag is
  called an anonymous union. The members of an anonymous structure or
  union are considered to be members of the containing structure or
  union. This applies recursively if the containing structure or union
  is also anonymous.

Body:
I have seen format below for defining a structure

typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
};

Some places I see the format below for defining a structure

typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

and some places I see the format below for defining a structure

typedef struct
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

If you notice the Tag syntax is after struct and also at the closing brace.

Questions.

1) What is the difference between the 3?

2) Is one preferred over the other or When are the best conditions you may want to use one over the other?

Body:
According to the C Standard (6.2.3 Name spaces of identifiers)

1 If more than one declaration of a particular identifier is visible
  at any point in a translation unit, the syntactic context
  disambiguates uses that refer to different entities. Thus, there are
  separate name spaces for various categories of identifiers, as
  follows:

— label names (disambiguated by the syntax of the label declaration
  and use);

— the tags of structures, unions, and enumerations (disambiguated by
  following any32) of the keywords struct, union, or enum);

— the members of structures or unions; each structure or union has a
  separate name space for its members (disambiguated by the type of the
  expression used to access the member via the . or -> operator);

— all other identifiers, called ordinary identifiers (declared in
  ordinary declarators or as enumeration constants).

This is

struct Tag
{
  type Tag;
  <and so on..>
};

a structure declaration with the name Tag and at the same time it is a structure definition because it not only introduces the type struct Tag but also declares its members.

You may at first declare a structure and then define it. For example

#include <stdio.h>

struct Tag;

struct Tag
{
    int Tag;
};

int main(void)
{
    struct Tag Tag = { .Tag = 10 };

    printf( "Tag.Tag = %d\n", Tag.Tag );

    return 0;
}

The program output is

Tag.Tag = 10

In this declaration

struct Tag
{
  type Tag;
  <and so on..>
} Tag;

there is declared an object of the type struct Tag with the identifier Tag. The structure has a data member with name Tag. Thus there are declared two entities: a type struct Tag and an object with the name Tag of the structure type.

In this declaration

struct
{
  type Tag;
  <and so on..>
} Tag;

there is declared an object of unnamed structure type with the identifier Tag. The problem with this declaration is that you can not refer to the type of the object.

You can meet one more declaration like

typedef struct Tag
{
  type Tag;
  <and so on..>
} Tag;

In this typedef declaration the identifier Tag serves as an alias of the type struct Tag.

Or

typedef struct
{
  type Tag;
  <and so on..>
} Tag;

In this typedef declaration the identifier Tag serves as an alias of the unnamed structure type.

The C 2011 allows to declare anonymous structures.
From the C Standard (6.7.2.1 Structure and union specifiers)

13 An unnamed member of structure type with no tag is called an
  anonymous structure; an unnamed member of union type with no tag is
  called an anonymous union. The members of an anonymous structure or
  union are considered to be members of the containing structure or
  union. This applies recursively if the containing structure or union
  is also anonymous.


问:
Big difference in time taken to perform graph queries
Based on the following collections:

```<code>data_invoices (document, 100,000 total records, 2 tenants)
    hash: tenantId
    persistent: createdOn

data_jobs (document, 10,000 total records, 2 tenants)
    hash: tenantId
    persistent: createdOn

data_links (edge, 100,000 total records)
    persistent: createdOn
    persistent (sparse): replacedOn
</code>```

The links collection will connect one invoice to a random job, so a job may have zero or more invoices.  An invoice should have one or more jobs, but in my data, each invoice is matched to only one job.  The date filter does not actually filter out any data (they are all less than the specified date value) and neither does the tenantId filter since all the data is either xxx or yyy.

The generic structure of data_jobs and data_invoices is:

```<code>tenantId: string;
createdOn: number;
data: [{
    createdOn: number;
    values: {
        ...collection specific data here...
    };
}];
</code>```

The collection specific data structure for data_invoices is:

```<code>number: number;
amount: number;
</code>```

The collection specific data structure for data_jobs is:

```<code>name: string;
</code>```

The structure of the data_links table is:

```<code>createdOn: number;
replacedOn?: number; // though I don't have any records with this value set
</code>```

The createdOn field is the date value represented as ticks from 1970, and is a random date from 01 Jan 2000 to today.

The amount field is a random currency value (2 decimal places) from 10 to 10,000.

The number field is an autonumber type field.

I have two very similar (in my opinion) queries, one way (jobs to invoices) works very, very quickly, the other one takes ages.

This query takes 1.85 seconds:

```<code>LET date = 1495616898128

FOR job IN data_jobs
    FILTER job.tenantId IN ['xxx', 'yyy']
    FILTER job.createdOn<=date
    LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    FILTER CONTAINS(jobData.values.name, 'a')
    LET invoices = (
        FOR invoice, link IN 1 INBOUND job data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL OR
                link.replacedOn>date)
            LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER invoiceData.values.amount>1000
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER invoices.count>0
    SORT jobData.values.name ASC
    LIMIT 0,8
    RETURN job
</code>```

This query takes 8.5 seconds:

```<code>LET date = 1495616898128

FOR invoice IN data_invoices
    FILTER invoice.tenantId IN ['xxx', 'yyy']
    FILTER invoice.createdOn<=date
    LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    FILTER invoiceData.values.amount>1000
    LET jobs = (
        FOR job, link IN 1 OUTBOUND invoice data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL
                OR link.replacedOn>date)
            LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER CONTAINS(jobData.values.name, 'a')
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER jobs.count>0
    SORT invoiceData.values.amount ASC
    LIMIT 0,8
    RETURN invoice
</code>```

I realise that both queries are providing different data, but the processing time should be the same shouldn't it?  They are both filtering both tables through the links table and both performing aggregations on the other.  I don't understand why one way is much quicker than the other way.  Is there anything I can do to increase the performance of these queries please?

答:
Okay, strange but I have stumbled upon a very counter-intuitive (at least to me) solution.  Sort first, then filter...???

This query now takes 1.4 seconds:

```<code>LET date = 1495616898128

FOR invoice IN data_invoices
    FILTER invoice.tenantId IN ['xxx', 'yyy']
    FILTER invoice.createdOn<=date
    LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    SORT invoiceData.values.amount ASC
    FILTER invoiceData.values.amount>1000
    LET jobs = (
        FOR job, link IN 1 OUTBOUND invoice data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL
                OR link.replacedOn>date)
            LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER CONTAINS(jobData.values.name, 'a')
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER jobs.count>0
    LIMIT 0,8
    RETURN invoice
</code>```

Despite adding a persistent index on data[*].values.amount, it still does not use it (I even tried SORT invoice.data[0].values.amount ASC and it still didn't seem to use the index?)

Can anyone explain this please?

Body:
Based on the following collections:

data_invoices (document, 100,000 total records, 2 tenants)
    hash: tenantId
    persistent: createdOn

data_jobs (document, 10,000 total records, 2 tenants)
    hash: tenantId
    persistent: createdOn

data_links (edge, 100,000 total records)
    persistent: createdOn
    persistent (sparse): replacedOn

The links collection will connect one invoice to a random job, so a job may have zero or more invoices.  An invoice should have one or more jobs, but in my data, each invoice is matched to only one job.  The date filter does not actually filter out any data (they are all less than the specified date value) and neither does the tenantId filter since all the data is either xxx or yyy.

The generic structure of data_jobs and data_invoices is:

tenantId: string;
createdOn: number;
data: [{
    createdOn: number;
    values: {
        ...collection specific data here...
    };
}];

The collection specific data structure for data_invoices is:

number: number;
amount: number;

The collection specific data structure for data_jobs is:

name: string;

The structure of the data_links table is:

createdOn: number;
replacedOn?: number; // though I don't have any records with this value set

The createdOn field is the date value represented as ticks from 1970, and is a random date from 01 Jan 2000 to today.

The amount field is a random currency value (2 decimal places) from 10 to 10,000.

The number field is an autonumber type field.

I have two very similar (in my opinion) queries, one way (jobs to invoices) works very, very quickly, the other one takes ages.

This query takes 1.85 seconds:

LET date = 1495616898128

FOR job IN data_jobs
    FILTER job.tenantId IN ['xxx', 'yyy']
    FILTER job.createdOn<=date
    LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    FILTER CONTAINS(jobData.values.name, 'a')
    LET invoices = (
        FOR invoice, link IN 1 INBOUND job data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL OR
                link.replacedOn>date)
            LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER invoiceData.values.amount>1000
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER invoices.count>0
    SORT jobData.values.name ASC
    LIMIT 0,8
    RETURN job

This query takes 8.5 seconds:

LET date = 1495616898128

FOR invoice IN data_invoices
    FILTER invoice.tenantId IN ['xxx', 'yyy']
    FILTER invoice.createdOn<=date
    LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    FILTER invoiceData.values.amount>1000
    LET jobs = (
        FOR job, link IN 1 OUTBOUND invoice data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL
                OR link.replacedOn>date)
            LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER CONTAINS(jobData.values.name, 'a')
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER jobs.count>0
    SORT invoiceData.values.amount ASC
    LIMIT 0,8
    RETURN invoice

I realise that both queries are providing different data, but the processing time should be the same shouldn't it?  They are both filtering both tables through the links table and both performing aggregations on the other.  I don't understand why one way is much quicker than the other way.  Is there anything I can do to increase the performance of these queries please?

Body:
Okay, strange but I have stumbled upon a very counter-intuitive (at least to me) solution.  Sort first, then filter...???

This query now takes 1.4 seconds:

LET date = 1495616898128

FOR invoice IN data_invoices
    FILTER invoice.tenantId IN ['xxx', 'yyy']
    FILTER invoice.createdOn<=date
    LET invoiceData = (invoice.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
    SORT invoiceData.values.amount ASC
    FILTER invoiceData.values.amount>1000
    LET jobs = (
        FOR job, link IN 1 OUTBOUND invoice data_links
            FILTER link.createdOn<=date AND (link.replacedOn == NULL
                OR link.replacedOn>date)
            LET jobData = (job.data[* FILTER CURRENT.createdOn<=date LIMIT 1])[0]
            FILTER CONTAINS(jobData.values.name, 'a')
            COLLECT WITH COUNT INTO count
            RETURN {
                count
            }
    )[0]
    FILTER jobs.count>0
    LIMIT 0,8
    RETURN invoice

Despite adding a persistent index on data[*].values.amount, it still does not use it (I even tried SORT invoice.data[0].values.amount ASC and it still didn't seem to use the index?)

Can anyone explain this please?


问:
Creating pages from Ninja form data
I've created a WordPress page with a Ninja form on it that collects miscellaneous data about a product, including some uploaded images.  The page with the form is accessible from the main menu by clicking the "Input" item, so the user doesn't need to access the backend to upload their product data.

I now want to put this data into a custom post type called "Listing."  There will eventually be thousands of these data sets and so thousands of "Listing" pages,  as people come to the site, click Input in  the main menu to get to the page with the Ninja form and fill it out.

Could someone tell me how they would go about now building these listing pages from the data the form has collected?

I'm running Ninja's Front-End Post option which supposedly will create a page from the form data.  This plugin has some Post creation settings where you can select the post type to create, but this isn't working for me. I would expect the submitted form data to show up under dashboard | Listings, but there's nothing there after submitting the form.

Has anyone gotten this to work?

Thanks for your help.

答:
I think you can use only Ninja Forms without extensions, and hook directly in 'ninja_forms_after_submission' that fires after submission and allow you to use data submitted and perform actions.

This is a starter codebase to achieve your result, but needs to be customized on your needs and your form structure.

```<code>add_action( 'ninja_forms_after_submission', 'create_page_from_ninjaform' );
function create_page_from_ninjaform( $form_data ){

    // your fields data
    $form_fields = $form_data[ 'fields' ];

    // !!! this is an example, it depends form fields in your form
    $title = $form_fields[ 1 ][ 'value' ];
    $content = $form_fields[ 2 ][ 'value' ];
    $sample_meta_field = $form_fields[ 3 ][ 'value' ];

    $new_post = array(
        'post_title' => $title,
        'post_content' => $content,
        'post_status' => 'publish',
        'post_type' => 'listing', // be sure this is the post type name
    );

    $new_post_id = wp_insert_post( $new_post );

    update_post_meta( $new_post_id, 'your_meta_key', $sample_meta_field );

}
</code>```

This code should be copied in functions.php file

Not tested of course.

Good luck ;)

Title: Creating pages from Ninja form data

Body:
I think you can use only Ninja Forms without extensions, and hook directly in 'ninja_forms_after_submission' that fires after submission and allow you to use data submitted and perform actions.

This is a starter codebase to achieve your result, but needs to be customized on your needs and your form structure.

add_action( 'ninja_forms_after_submission', 'create_page_from_ninjaform' );
function create_page_from_ninjaform( $form_data ){

    // your fields data
    $form_fields = $form_data[ 'fields' ];

    // !!! this is an example, it depends form fields in your form
    $title = $form_fields[ 1 ][ 'value' ];
    $content = $form_fields[ 2 ][ 'value' ];
    $sample_meta_field = $form_fields[ 3 ][ 'value' ];

    $new_post = array(
        'post_title' => $title,
        'post_content' => $content,
        'post_status' => 'publish',
        'post_type' => 'listing', // be sure this is the post type name
    );

    $new_post_id = wp_insert_post( $new_post );

    update_post_meta( $new_post_id, 'your_meta_key', $sample_meta_field );

}

This code should be copied in functions.php file

Not tested of course.

Good luck ;)


问:
Windows store application to authenticate against azure function
I'm trying to replicate the following example https://github.com/Azure-Samples/active-directory-dotnet-windows-store (a Windows store application authenticating against azure AD), but I'm replacing the Web App by an Azure Function.

In the Function, the code checking whether the user is logged in is the following:

```<code>ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation"))
</code>```

but this does not contain the required values, and  other calls don't return any value either (e.g. ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName));

Do you have any idea what is going on?

答:
See this issue https://github.com/Azure-Samples/active-directory-dotnet-daemon/issues/1

That scope is not in the claims list. You can try the following to dump all the claims you get and see what's available.

foreach (Claim claim in ClaimsPrincipal.Current.Claims)
{
   log.Info("CLAIM TYPE: " + claim.Type + "; CLAIM VALUE: " + claim.Value);
}
```

Body:
I'm trying to replicate the following example https://github.com/Azure-Samples/active-directory-dotnet-windows-store (a Windows store application authenticating against azure AD), but I'm replacing the Web App by an Azure Function.

In the Function, the code checking whether the user is logged in is the following:

ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Contains("user_impersonation"))

but this does not contain the required values, and  other calls don't return any value either (e.g. ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName));

Do you have any idea what is going on?


问:
Swift UIButton With Icon and Text (not using edgeinsets)
I'm trying to get a button with an icon to the left of some text:

Having trouble with my understanding of UIButton. Adding a title to the button works fine:

```<code>import UIKit

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 25))
button.backgroundColor = .green
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .fill
button.titleLabel!.backgroundColor = .blue
button.setTitle("639", for: .normal)
button.setTitleColor(.white, for: .normal)
</code>```

but then when you add an image

```<code>button.setImage(UIImage(named: "test"), for: .normal)
button.imageView!.backgroundColor = .clear
button.imageView!.contentMode = .scaleAspectFit
</code>```

it keeps it's original size (300px) and pushes the title out the right side out of the buttons bounds. (can't see it in screenshot as its only showing button frame)

What am I doing wrong? Why does the image retain it's original width even though its been scaled down? What does contentHorizontalAlignment even do if it allows items to be pushed out of frame?

I'm aware that you can set insets but this is being used in a re-useable view so I can't hardcode values.

Thanks for the help

答:
I just made a button just like what you said.

By the way why don't you use inset.Apple has given us the opportunity to use this.Then why shouldn't we use this?

Note: You have to make trial and error to position the image and text correctly.

Autolayout:

And inset:

If it's not accurate i said you have to make trial and error. happy coding. :)

Body:
I'm trying to get a button with an icon to the left of some text:

Having trouble with my understanding of UIButton. Adding a title to the button works fine:

import UIKit

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 25))
button.backgroundColor = .green
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .fill
button.titleLabel!.backgroundColor = .blue
button.setTitle("639", for: .normal)
button.setTitleColor(.white, for: .normal)

but then when you add an image

button.setImage(UIImage(named: "test"), for: .normal)
button.imageView!.backgroundColor = .clear
button.imageView!.contentMode = .scaleAspectFit

it keeps it's original size (300px) and pushes the title out the right side out of the buttons bounds. (can't see it in screenshot as its only showing button frame)

What am I doing wrong? Why does the image retain it's original width even though its been scaled down? What does contentHorizontalAlignment even do if it allows items to be pushed out of frame?

I'm aware that you can set insets but this is being used in a re-useable view so I can't hardcode values.

Thanks for the help


问:
Simple cross-platform OS-based startup/routing script
I am developing an open source cross platform utility which contains some wrappers for housekeeping and variable setup based on operating system. This housekeeping is within it's own script and is, for the most part, generated.

For simplicity, and DRYness, I would love to have a single simple startup-script which selected another script to run based on operating system.

In essence this is what I would like:

```<code>::# Somehow run this on osx/windows/linux +++
switch OSTYPE
when "win32"
   windows_script.bat ARGS
when "linux"
   linux_script.sh ARGS
when "darwin"
   darwin_script.sh ARGS
....
</code>```

That way it would be even less to deal with when making cross platform applications. The value is to not special case which script to run when developing another app

Is there any way of achieving this without installing external dependencies?

答:
In my use case I just needed some similar variables in separate powershell and bash scripts. I modified Steven's answer and came up with this example:

```<code>${0+: \} <#}
#only runs in bash and sets these variables in linux
export foo="foovalue"
export bar="barvalue"
export baz="bazvalue"
#only runs in powershell and sets the same variables#>
${0+: \} <#}
##>; $foo="foovalue"
${0+: \} <#}
##>; $bar="barvalue"
${0+: \} <#}
##>; $baz="bazvalue"
</code>```

It reads like machine code, but I am using terraform to template the values on the systems I'll be pushing this to.

Body:
I am developing an open source cross platform utility which contains some wrappers for housekeeping and variable setup based on operating system. This housekeeping is within it's own script and is, for the most part, generated.

For simplicity, and DRYness, I would love to have a single simple startup-script which selected another script to run based on operating system.

In essence this is what I would like:

::# Somehow run this on osx/windows/linux +++
switch OSTYPE
when "win32"
   windows_script.bat ARGS
when "linux"
   linux_script.sh ARGS
when "darwin"
   darwin_script.sh ARGS
....

That way it would be even less to deal with when making cross platform applications. The value is to not special case which script to run when developing another app

Is there any way of achieving this without installing external dependencies?

Body:
In my use case I just needed some similar variables in separate powershell and bash scripts. I modified Steven's answer and came up with this example:

${0+: \} <#}
#only runs in bash and sets these variables in linux
export foo="foovalue"
export bar="barvalue"
export baz="bazvalue"
#only runs in powershell and sets the same variables#>
${0+: \} <#}
##>; $foo="foovalue"
${0+: \} <#}
##>; $bar="barvalue"
${0+: \} <#}
##>; $baz="bazvalue"

It reads like machine code, but I am using terraform to template the values on the systems I'll be pushing this to.


问:
Getting days since last occurence in Pandas DataFrame?
Let's say I have a Pandas DataFrame df:

```<code>Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0
</code>```

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

```<code>Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2
</code>```

I could do a loop:

```<code>for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last
</code>```

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

答:
Let's try this using cumsum, cumcount, and groupby:

```<code>mask = df.Value.cumsum().replace(0,False).astype(bool) #Mask starting zeros as NaN
df_out = df.assign(Last_Occurance=df.groupby(df.Value.astype(bool).cumsum()).cumcount().where(mask))
print(df_out)
</code>```

output:

```<code>       Date  Value  Last_Occurance
0  01/01/17      0             NaN
1  01/02/17      0             NaN
2  01/03/17      1             0.0
3  01/04/17      0             1.0
4  01/05/17      0             2.0
5  01/06/17      0             3.0
6  01/07/17      1             0.0
7  01/08/17      0             1.0
8  01/09/17      0             2.0
</code>```

Body:
Let's say I have a Pandas DataFrame df:

Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2

I could do a loop:

for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

Body:
Let's try this using cumsum, cumcount, and groupby:

mask = df.Value.cumsum().replace(0,False).astype(bool) #Mask starting zeros as NaN
df_out = df.assign(Last_Occurance=df.groupby(df.Value.astype(bool).cumsum()).cumcount().where(mask))
print(df_out)

output:

       Date  Value  Last_Occurance
0  01/01/17      0             NaN
1  01/02/17      0             NaN
2  01/03/17      1             0.0
3  01/04/17      0             1.0
4  01/05/17      0             2.0
5  01/06/17      0             3.0
6  01/07/17      1             0.0
7  01/08/17      0             1.0
8  01/09/17      0             2.0