问:
Testing local server with MAMP/wordpress on mobile device?
I am currently developing a wordpress site locally using MAMP PRO, which obviously involves using a local database.

I would like to test this site on my iPhone via a remote link. I have managed to do this by typing the following into my mobile phone URL...

```<code>192.234.2.32:8888
</code>```

(IP Address : Port number)

The problem is the index page is displayed but with no CSS styling. Then when I click on another page, it says the page cannot be found

It seems it has connected to the server properly, but not to the wordpress database. (at least I think this is the problem)

Does anyone have any information on how to get this working or point me in the right direction? Do you need another application to do this, or can it be done with mamp/IP address etc?

Thanks in advance

答:
In general settings WordPress; Change The WordPress address from

localhost to the IP address of your desktop pc/mac (URL)

In the MAMP PRO general tab; Check; via Xip.io (LAN only)and copy that address

In general settings WordPress Paste the Xip.io addres in Site Address (URL)

you can acces the mobile devices via;
http://localhost.IPAddressOfYourLocalComputer.xip.io

screenshot Wordpress

Body:
I am currently developing a wordpress site locally using MAMP PRO, which obviously involves using a local database.

I would like to test this site on my iPhone via a remote link. I have managed to do this by typing the following into my mobile phone URL...

192.234.2.32:8888

(IP Address : Port number)

The problem is the index page is displayed but with no CSS styling. Then when I click on another page, it says the page cannot be found

It seems it has connected to the server properly, but not to the wordpress database. (at least I think this is the problem)

Does anyone have any information on how to get this working or point me in the right direction? Do you need another application to do this, or can it be done with mamp/IP address etc?

Thanks in advance


来源: stackexchange

问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答:
By creating a .gitignore file. See here for details: Git Book - Ignoring files

Also check this one out: How do you make Git ignore files without using .gitignore?

ContentLicense: CC BY-SA 4.0

Title: How to ignore certain files in Git

ContentLicense: CC BY-SA 3.0


问:
How to correctly link an external library using CMake?
I'm trying to use the Chilkat C++ library to do a cryptography assignment, but I cannot seem to get the library to link properly. As of right now the header file CkRsa.h cannot be found by the compiler. I've spent a few hours searching across the internet for solutions to no avail. Here is what I have so far (this is all in a Mac OS X environment):

The lib files are installed in /users/Adam/Desktop/chilkat/libDyn and the header files are in /users/Adam/Desktop/chilkat/include
Here is my CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.6)
project(SocketEncryption)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_library(chilkat STATIC IMPORTED)
set_property(
        TARGET chilkat
        PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
add_executable(SocketEncryption ${SOURCE_FILES})

target_link_libraries(SocketEncryption chilkat)
</code>```

Here is my main.cpp

```<code>#include <iostream>
#include <CkRsa.h>
//#include <CkPrivateKey.h>
//#include <CkSocket.h>

int main() {
    CkRsa alice;
    CkRsa bob;

    // Key Generation
    bool success = alice.GenerateKey(1024);
    const char *alicePublicKey = alice.exportPublicKey();
    const char *alicePrivateKey = alice.exportPrivateKey();
    const char *aliceMessage = "Hi, Bob. How are you?";

    // Encryption Step
    std::cout << "Encryption started." << std::endl;
    CkRsa rsaEncryptor;
    rsaEncryptor.put_EncodingMode("hex");
    success = rsaEncryptor.ImportPublicKey(alicePublicKey);
    bool usePrivateKey = false;
    const char * ciphertext = rsaEncryptor.encryptStringENC(aliceMessage, success);
    std::cout << ciphertext << std::endl;

    return 0;
}
</code>```

答:
change your code like this (quotation):</p>

```<code>include_directories("/users/Adam/Desktop/chilkat/include")
link_directories("/users/Adam/Desktop/chilkat/libDyn")
</code>```

Body:
I'm trying to use the Chilkat C++ library to do a cryptography assignment, but I cannot seem to get the library to link properly. As of right now the header file CkRsa.h cannot be found by the compiler. I've spent a few hours searching across the internet for solutions to no avail. Here is what I have so far (this is all in a Mac OS X environment):

The lib files are installed in /users/Adam/Desktop/chilkat/libDyn and the header files are in /users/Adam/Desktop/chilkat/include
Here is my CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(SocketEncryption)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_library(chilkat STATIC IMPORTED)
set_property(
        TARGET chilkat
        PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
add_executable(SocketEncryption ${SOURCE_FILES})

target_link_libraries(SocketEncryption chilkat)

Here is my main.cpp

#include <iostream>
#include <CkRsa.h>
//#include <CkPrivateKey.h>
//#include <CkSocket.h>

int main() {
    CkRsa alice;
    CkRsa bob;

    // Key Generation
    bool success = alice.GenerateKey(1024);
    const char *alicePublicKey = alice.exportPublicKey();
    const char *alicePrivateKey = alice.exportPrivateKey();
    const char *aliceMessage = "Hi, Bob. How are you?";

    // Encryption Step
    std::cout << "Encryption started." << std::endl;
    CkRsa rsaEncryptor;
    rsaEncryptor.put_EncodingMode("hex");
    success = rsaEncryptor.ImportPublicKey(alicePublicKey);
    bool usePrivateKey = false;
    const char * ciphertext = rsaEncryptor.encryptStringENC(aliceMessage, success);
    std::cout << ciphertext << std::endl;

    return 0;
}

Body:
change your code like this (quotation):

include_directories("/users/Adam/Desktop/chilkat/include")
link_directories("/users/Adam/Desktop/chilkat/libDyn")


问:
how to put multiple jquery dataTables in one page?
I want to use jquery dataTables to show something.

It works well when i just put one dataTable in one page, then i add one more, but they occupied almost the same position, and one of them doesn't work well.

Do you know how to deal with that?

答:
Still working on it... but this could be helpful

```<code><div class="col-md-12">
          <!-- Custom Tabs -->
          <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
              <li class="active"><a href="#tab_1" data-toggle="tab" aria-expanded="true">Web Design and Development</a></li>
              <li class=""><a href="#tab_2" data-toggle="tab" aria-expanded="false">Domain Registration</a></li>
              <li class=""><a href="#tab_3" data-toggle="tab" aria-expanded="false">Cloud Computing Services</a></li>
              <li class=""><a href="#tab_4" data-toggle="tab" aria-expanded="false">Android application Development</a></li>
              <li class=""><a href="#tab_5" data-toggle="tab" aria-expanded="false">Web Hosting</a></li>
              <li class=""><a href="#tab_6" data-toggle="tab" aria-expanded="false">SEO and Online Marketing</a></li>
              <li class="pull-right"><a href="#" class="text-muted"><i class="fa fa-gear"></i></a></li>
            </ul>
            <div class="tab-content">
              <div class="tab-pane active" id="tab_1">
                <b>Web Deign and development hires:</b>

                <table class="table" id="webdesignTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>

              </div>
              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_2">
              <b>Domain Registration</b>

              <table class="table" id="domainregistrationTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>

              </div>
              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_3">
               <b>Cloud Computing</b>

              <table class="table" id="cloudcomputingTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_4">
               <b>Android application Development</b>

              <table class="table" id="androidappTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_5">
               <b>Web Hosting</b>

              <table class="table" id="webhostingTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_6">
               <b>SEO and Online Marketing</b>

              <table class="table" id="seoTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->
            </div>
            <!-- /.tab-content -->
          </div>
          <!-- nav-tabs-custom -->
        </div>
</code>```

The script

```<code>// global the manage tables
var manageMemberTable;
//var tbl1 = $('#webdesignTable').DataTable( );

$(document).ready(function() {

     $('table.display').dataTable(); //focus here

    manageMemberTable = $("#webdesignTable").DataTable({
        "ajax": "webdesign_action/retrieve.php", //get data for your tables
        "order": []
    });

    domainregistrationTable = $("#domainregistrationTable").DataTable({
        "ajax": "domainregistration_action/retrieve.php", //get data for your tables
        "order": []
    });
//It continues
</code>```

Body:
Still working on it... but this could be helpful

<div class="col-md-12">
          <!-- Custom Tabs -->
          <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
              <li class="active"><a href="#tab_1" data-toggle="tab" aria-expanded="true">Web Design and Development</a></li>
              <li class=""><a href="#tab_2" data-toggle="tab" aria-expanded="false">Domain Registration</a></li>
              <li class=""><a href="#tab_3" data-toggle="tab" aria-expanded="false">Cloud Computing Services</a></li>
              <li class=""><a href="#tab_4" data-toggle="tab" aria-expanded="false">Android application Development</a></li>
              <li class=""><a href="#tab_5" data-toggle="tab" aria-expanded="false">Web Hosting</a></li>
              <li class=""><a href="#tab_6" data-toggle="tab" aria-expanded="false">SEO and Online Marketing</a></li>
              <li class="pull-right"><a href="#" class="text-muted"><i class="fa fa-gear"></i></a></li>
            </ul>
            <div class="tab-content">
              <div class="tab-pane active" id="tab_1">
                <b>Web Deign and development hires:</b>

                <table class="table" id="webdesignTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>

              </div>
              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_2">
              <b>Domain Registration</b>

              <table class="table" id="domainregistrationTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>

              </div>
              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_3">
               <b>Cloud Computing</b>

              <table class="table" id="cloudcomputingTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_4">
               <b>Android application Development</b>

              <table class="table" id="androidappTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_5">
               <b>Web Hosting</b>

              <table class="table" id="webhostingTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->

              <!-- /.tab-pane -->
              <div class="tab-pane" id="tab_6">
               <b>SEO and Online Marketing</b>

              <table class="table" id="seoTable">
                    <thead>
                        <tr>
                            <th>S.no</th>
                            <th>Order By</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Message</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Options</th>
                        </tr>
                    </thead>
                </table>
              </div>
              <!-- /.tab-pane -->
            </div>
            <!-- /.tab-content -->
          </div>
          <!-- nav-tabs-custom -->
        </div>

The script

// global the manage tables
var manageMemberTable;
//var tbl1 = $('#webdesignTable').DataTable( );

$(document).ready(function() {

     $('table.display').dataTable(); //focus here

    manageMemberTable = $("#webdesignTable").DataTable({
        "ajax": "webdesign_action/retrieve.php", //get data for your tables
        "order": []
    });

    domainregistrationTable = $("#domainregistrationTable").DataTable({
        "ajax": "domainregistration_action/retrieve.php", //get data for your tables
        "order": []
    });
//It continues


问:
Android : How to send app invite message using whatsapp,facebook,gmail,etc from my app
I need to send app invitation message from my app to friends via whatsapp,facebook,hike,... with the message and playstore link.I have seen this kind of invitations in other apps like hike,whatscall,... like the attached image below.

I want to send exactly the same kind of message with the playstore link and app logo for my app also and it should be shared using all the available sharing option in users mobile.In my application i have included a inform friends menu and on clicking on that this function should work.I have seen firebase app invite examples but it needs google-services.json and i think it will only send text message from users email,I am not sure about that.

答:
You need to create an intent as follows which will allow you to share your app using any other app :</p>

```<code>    try {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("text/plain");
        i.putExtra(Intent.EXTRA_SUBJECT, "My app name");
        String strShareMessage = "\nLet me recommend you this application\n\n";
        strShareMessage = strShareMessage + "https://play.google.com/store/apps/details?id=" + getPackageName();
        Uri screenshotUri = Uri.parse("android.resource://packagename/drawable/image_name");
        i.setType("image/png");
        i.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        i.putExtra(Intent.EXTRA_TEXT, strShareMessage);
        startActivity(Intent.createChooser(i, "Share via"));
    } catch(Exception e) {
        //e.toString();
    }
</code>```

Body:
You need to create an intent as follows which will allow you to share your app using any other app :

    try {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("text/plain");
        i.putExtra(Intent.EXTRA_SUBJECT, "My app name");
        String strShareMessage = "\nLet me recommend you this application\n\n";
        strShareMessage = strShareMessage + "https://play.google.com/store/apps/details?id=" + getPackageName();
        Uri screenshotUri = Uri.parse("android.resource://packagename/drawable/image_name");
        i.setType("image/png");
        i.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        i.putExtra(Intent.EXTRA_TEXT, strShareMessage);
        startActivity(Intent.createChooser(i, "Share via"));
    } catch(Exception e) {
        //e.toString();
    }


问:
Google Analytics Reporting API v4 missing required authentication credential
I'm new to using this API, and I am struggling with retrieving my data using Google Analytics Reporting API v4. I am only attempting to retrieve the analytics for a website so I can build a dashboard.  I am following the example here: Hello Analytics Reporting API v4; JavaScript quick start for web applications

I am able to make a request, however, I keep getting a 400 error that is might be this: 400: Invalid Credentials

```<code>`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`
</code>```

I have no idea what I am doing wrong, and I am hoping someone can point me in the right direction.

This is a react application. I am making the request after the component mounts.

```<code>import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}
</code>```

What am I doing wrong? How can I properly do a batchRequest to retrieve all data from 7 days using Google Analytics Reporting APIv4? I feel as though I am using all required fields, however, I do not know what I am missing. Can you point me in the right direction?

答:
401: Invalid Credentials Invalid authorization header. The access
  token you're using is either expired or invalid.

This basically means that you need to sign in again.

Click the Sign in button, and authorize access to Google Analytics.

Remember access tokens are only valid for an hour your going to have to sign it in again when ever it expires.

Body:
I'm new to using this API, and I am struggling with retrieving my data using Google Analytics Reporting API v4. I am only attempting to retrieve the analytics for a website so I can build a dashboard.  I am following the example here: Hello Analytics Reporting API v4; JavaScript quick start for web applications

I am able to make a request, however, I keep getting a 400 error that is might be this: 400: Invalid Credentials

`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`

I have no idea what I am doing wrong, and I am hoping someone can point me in the right direction.

This is a react application. I am making the request after the component mounts.

import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (

    )
  }
}

What am I doing wrong? How can I properly do a batchRequest to retrieve all data from 7 days using Google Analytics Reporting APIv4? I feel as though I am using all required fields, however, I do not know what I am missing. Can you point me in the right direction?


问:
Python iterate nested dictionary to remove keys
I want to remove nested keys in a dictionary whose values are empty.

Example:

```<code>d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }
</code>```

For each of the main keys, there is a sub key and a sub sub key.
If any of the key's values are empty, i want to remove the entire key.

However, i get the error :RuntimeError: dictionary changed size during iteration
when i loop through the dictionary to delete empty values.

```<code>for k,v in d.iteritems():
    if not v:
        del d[k]
    else:
        for a,b in v.iteritems():
        if not b:
            del d[k][a]
</code>```

desired output:

```<code>d = {'A': {'a': {1: [('string1', 'string2')]}}}
</code>```

答:
```<code>for k, v in d.items():

  if not v:
    del d[k]
  else:
    for a,b in v.items():
        if not b:
            if len(d[k])==1:
                del d[k][a]
                del d[k]
            else:
                del d[k][a]
print d
</code>```

Body:
I want to remove nested keys in a dictionary whose values are empty.

Example:

d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

For each of the main keys, there is a sub key and a sub sub key.
If any of the key's values are empty, i want to remove the entire key.

However, i get the error :RuntimeError: dictionary changed size during iteration
when i loop through the dictionary to delete empty values.

for k,v in d.iteritems():
    if not v:
        del d[k]
    else:
        for a,b in v.iteritems():
        if not b:
            del d[k][a]

desired output:

d = {'A': {'a': {1: [('string1', 'string2')]}}}


问:
How to pass form values as FormData in reactjs on submit function
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.</p>
```<code>var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (
          <div className={group.Type}>
            <div for="let value of group.Values">
              {group.Values.map(el=> (
                <label><input name="radios"/>{el.Value}</label>
              ))}
            </div>
          </div>
        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (
        <div>
          <label for={group.Label}>{group.Label}</label>
          <div>
            {this._renderElement(group)}
          </div>
        </div>
      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (
      <div className="container">
        <br/>
        <div className="panel panel-primary">
          <div className="panel-heading">Form</div>
          <div className="panel-body">
            <form>
              <div className="form-group">
                <div className="col-xs-5">
                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));
</code>```

答:
You can access FormData like this:

```<code>handleSubmit(event) {
    // Prevent default behavior
    event.preventDefault();

    const data = new FormData(event.target);
    // Access FormData fields with `data.get(fieldName)`
    // For example, converting to upper case
    data.set('username', data.get('username').toUpperCase());

    // Do your Axios stuff here
}
</code>```

This is the code for the form:

```<code>render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />
        <button>Send data!</button>
      </form>
    );
</code>```

Body:
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.

var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (

              {group.Values.map(el=> (
                <input name="radios"/>{el.Value}
              ))}

        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (

          {group.Label}

            {this._renderElement(group)}

      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (

Form

            <form>

                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>

            </form>

    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));

Body:
You can access FormData like this:

handleSubmit(event) {
    // Prevent default behavior
    event.preventDefault();

    const data = new FormData(event.target);
    // Access FormData fields with `data.get(fieldName)`
    // For example, converting to upper case
    data.set('username', data.get('username').toUpperCase());

    // Do your Axios stuff here
}

This is the code for the form:

render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />
        <button>Send data!</button>
      </form>
    );


问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答: If using Microsoft SQl Server, you should write a user defined function (UDF) to do this</p>

ContentLicense: CC BY-SA 2.5

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.


答:
You can try this,</p>

```<code>Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"Your String");
intent.putExtra(Intent.EXTRA_SUBJECT, "Share " + "From");
intent.setPackage(packageName);
ActivityName.startActivity(intent);
</code>```

Title: Android : How to send app invite message using whatsapp,facebook,gmail,etc from my app

Body:
I need to send app invitation message from my app to friends via whatsapp,facebook,hike,... with the message and playstore link.I have seen this kind of invitations in other apps like hike,whatscall,... like the attached image below.

I want to send exactly the same kind of message with the playstore link and app logo for my app also and it should be shared using all the available sharing option in users mobile.In my application i have included a inform friends menu and on clicking on that this function should work.I have seen firebase app invite examples but it needs google-services.json and i think it will only send text message from users email,I am not sure about that.

Body:
You can try this,

Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"Your String");
intent.putExtra(Intent.EXTRA_SUBJECT, "Share " + "From");
intent.setPackage(packageName);
ActivityName.startActivity(intent);


问:
angularjs How to escape “${variable}” in html?
I want to show a string like ${date} to the div element:

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

the content will be display like:

```<code>please use the ${date} as the substitute tag to the name.
</code>```

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

答:
in JS add $sce as DI

$scope.stringVar = $sce.trustAsHtml('please use the ${date} as the substitute tag to the name');

in HTML

```<code><div ng-bind-html="stringVar"></div>
</code>```

Body:
I want to show a string like ${date} to the div element:

please use the ${date} as the substitute tag to the name

the content will be display like:

please use the ${date} as the substitute tag to the name.

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

Body:
in JS add $sce as DI

$scope.stringVar = $sce.trustAsHtml('please use the ${date} as the substitute tag to the name');

in HTML

<div ng-bind-html="stringVar"></div>


问:
SED expression for turning Yeseva+One into --font-yeseva-one: "Yeseva One";
I have a series of font values like this (Command separated one line):

```<code>Yeseva+One, Yrsa, ...
</code>```

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

```<code>--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";
</code>```

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

答:
```<code>#!/bin/sh

variable="Abc, Def+Hola, Ghij"

IFS="[, ]"
for i in $variable
do
        a=`echo "$i" | sed 's/\+/ /g'`
        i=`echo "$i" | tr '[:upper:]' '[:lower:]' | sed 's/\+/\-/g'`
        echo "--font-$i: \"$a\";"
done
</code>```

Please check, I have checked it on my machine and it works fine!

Output:

```<code>--font-abc: "Abc";
--font-def-hola: "Def Hola";
--font-ghij: "Ghij";
</code>```

Body:
I have a series of font values like this (Command separated one line):

Yeseva+One, Yrsa, ...

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

Body:
#!/bin/sh

variable="Abc, Def+Hola, Ghij"

IFS="[, ]"
for i in $variable
do
        a=`echo "$i" | sed 's/\+/ /g'`
        i=`echo "$i" | tr '[:upper:]' '[:lower:]' | sed 's/\+/\-/g'`
        echo "--font-$i: \"$a\";"
done

Please check, I have checked it on my machine and it works fine!

Output:

--font-abc: "Abc";
--font-def-hola: "Def Hola";
--font-ghij: "Ghij";


问:
Sending a promise from one controller to another in Angular
In my web app, I would like to load all of the user data at the beginning, in the run method and pass the data to the other controllers to be shown to the user in the dashboard.

So lets say I have a data structure on the server

```<code>data = {
  x : 30,
  y: 20
}
</code>```

I would like to get it in one http requests (instead of creating multiple http requests and creating multiple promises)

The http request I run in the run method of the app

```<code>service.getDataFromServer = function(){
  return $http.get('/admin/data').then(function(response) {
    data = response.data;
  });
};
</code>```

This will create a promise.

I would like to take this promise and pass it to other controllers to be used.

My first question is how can I do it so the data from the promise will bind to the data I am about to show to the user.

The second question is, can I use the structure fields before the promise is even resolved?
for example

```<code>$scope.x = data.x
</code>```

And by data I mean the data which is about to be resolved

Thanks

答:
I would like to get it in one http requests (instead of creating multiple http requests and creating multiple promises)

After getting response from http call,save the data  in factory/services so,you can use is at another location like controller in your case by injecting it which is most recommended.

I would like to take this promise and pass it to other controllers to be used.
  how can I do it so the data from the promise will bind to the data I am about to show to the user.

make http call and save the promise.

```<code>service.getDataFromServer = function() {

      var promise = $http.get('test.json');

      service.savePromise(promise);
    }
</code>```

and

get saved promise.

```<code>.controller('testCtrl', function(service) {

      service.getSavedPromise().then(function(response){
          console.log(response.data)
      })
  })
</code>```

Plunker here

The second question is, can I use the structure fields before the promise is even resolved? for example

```<code>$scope.x = data.x
</code>```

// data is still undefined as promise is not resolved.so,you will get TypeError

What you can do best here,you can merge data to your existing data object/array,so,Angular two way binding can do rest of the things  for you.

Body:
In my web app, I would like to load all of the user data at the beginning, in the run method and pass the data to the other controllers to be shown to the user in the dashboard.

So lets say I have a data structure on the server

data = {
  x : 30,
  y: 20
}

I would like to get it in one http requests (instead of creating multiple http requests and creating multiple promises)

The http request I run in the run method of the app

service.getDataFromServer = function(){
  return $http.get('/admin/data').then(function(response) {
    data = response.data;
  });
};

This will create a promise.

I would like to take this promise and pass it to other controllers to be used.

My first question is how can I do it so the data from the promise will bind to the data I am about to show to the user.

The second question is, can I use the structure fields before the promise is even resolved?
for example

$scope.x = data.x

And by data I mean the data which is about to be resolved

Thanks

Body:
I would like to get it in one http requests (instead of creating multiple http requests and creating multiple promises)

After getting response from http call,save the data  in factory/services so,you can use is at another location like controller in your case by injecting it which is most recommended.

I would like to take this promise and pass it to other controllers to be used.
  how can I do it so the data from the promise will bind to the data I am about to show to the user.

make http call and save the promise.

service.getDataFromServer = function() {

      var promise = $http.get('test.json');

      service.savePromise(promise);
    }

and

get saved promise.

.controller('testCtrl', function(service) {

      service.getSavedPromise().then(function(response){
          console.log(response.data)
      })
  })

Plunker here

The second question is, can I use the structure fields before the promise is even resolved? for example

$scope.x = data.x

// data is still undefined as promise is not resolved.so,you will get TypeError

What you can do best here,you can merge data to your existing data object/array,so,Angular two way binding can do rest of the things  for you.


问:
Find email adresses in excel workbook
I have a excel sheet which containts an emails in exact one column(the order of the column is not exact and changing).

I used the find function looking like this.

```<code>Sub emialy()

Cells.Find ("@",,xlValues,xlPart,xlByRows,,,,) ActiveCell.Copy

End Sub
</code>```

but I am recieving an error...

Then if a program finds where the emails list are beginning i want to copy that very first email and open an email client (outlook), create an new email and paste the exact copied email to the "to:" row.

答:
The recommended way to use the Find function, is by setting a Range type variable to the result. This way you can trap the scenario Find was unable to find @ throughout your worksheet's Cells with If Not EmailRng Is Nothing Then.

Code

```<code>Sub emialy()

Dim EmailRng As Range

Set EmailRng = Cells.Find(What:="@", LookIn:=xlValues, Lookat:=xlPart, SearchOrder:=xlByRows)
If Not EmailRng Is Nothing Then ' succesful find
    EmailRng.Copy
Else
    MsgBox "Could not find the @ symbol"
End If

End Sub
</code>```

Title: Find email adresses in excel workbook

Body:
I have a excel sheet which containts an emails in exact one column(the order of the column is not exact and changing).

I used the find function looking like this.

Sub emialy()

Cells.Find ("@",,xlValues,xlPart,xlByRows,,,,) ActiveCell.Copy

End Sub

but I am recieving an error...

Then if a program finds where the emails list are beginning i want to copy that very first email and open an email client (outlook), create an new email and paste the exact copied email to the "to:" row.

Body:
The recommended way to use the Find function, is by setting a Range type variable to the result. This way you can trap the scenario Find was unable to find @ throughout your worksheet's Cells with If Not EmailRng Is Nothing Then.

Code

Sub emialy()

Dim EmailRng As Range

Set EmailRng = Cells.Find(What:="@", LookIn:=xlValues, Lookat:=xlPart, SearchOrder:=xlByRows)
If Not EmailRng Is Nothing Then ' succesful find
    EmailRng.Copy
Else
    MsgBox "Could not find the @ symbol"
End If

End Sub


问:
C# 7 tuples and lambdas
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

```<code>var list = new List<(int,int)>();
</code>```

normal way to use a tuple in lambda:

```<code>list.Select(value => value.Item1*2 + value.Item2/2);
</code>```

i expected some new sugar to avoid .Item1 .Item2, like:

```<code>list.Select((x,y) => x*2 + y/2);
</code>```

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

```<code>list.Add((1,2));
</code>```

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

```<code>void Foo((int,int)(x,y)) { x+y; }
</code>```

Instead of this:

```<code>void Foo((int x,int y) value) { value.x+value.y }
</code>```

答:
The problem you're running into is the inability of the compiler to infer the type in this expression:

```<code>list.Select(((int x, int y) t) => t.x * 2 + t.y / 2);
</code>```

But since (int, int) and (int x, int y) are the same CLR type (System.ValueType<int, int>), if you specify the type parameters:

```<code>list.Select<(int x, int y), int>(t => t.x * 2 + t.y / 2);
</code>```

It will work.

Title: C# 7 tuples and lambdas

Body:
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

var list = new List<(int,int)>();

normal way to use a tuple in lambda:

list.Select(value => value.Item1*2 + value.Item2/2);

i expected some new sugar to avoid .Item1 .Item2, like:

list.Select((x,y) => x*2 + y/2);

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

list.Add((1,2));

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

void Foo((int,int)(x,y)) { x+y; }

Instead of this:

void Foo((int x,int y) value) { value.x+value.y }

Body:
The problem you're running into is the inability of the compiler to infer the type in this expression:

list.Select(((int x, int y) t) => t.x * 2 + t.y / 2);

But since (int, int) and (int x, int y) are the same CLR type (System.ValueType<int, int>), if you specify the type parameters:

list.Select<(int x, int y), int>(t => t.x * 2 + t.y / 2);

It will work.


问:
Mvx does not exist in the current context
```<code>using MvvmCross.Platform.IoC;
using Acr.UserDialogs;

namespace YourMom.Core
{
    public class App : MvvmCross.Core.ViewModels.MvxApplication
    {
        public override void Initialize()
        {
            CreatableTypes()
                .EndingWith("Service")
                .AsInterfaces()
                .RegisterAsLazySingleton();

            Mvx.RegisterSingleton<IUserDialogs>(() => UserDialogs.Instance);

            RegisterAppStart<ViewModels.FirstViewModel>();
        }
    }
}
</code>```

I try to use use dialog plugin for Xamarin mvvmcross. It says to put the registerSingleton code in my PCL app.cs, but i have error saying Mvx is not recognized. I am pretty sure i need to "using" some package i just don't know what. Pls help.

答:
Guess I'm answering my own question yet again.

The one to "import" is MvvmCross.Platform;

So to solve this issue, just add

```<code>using MvvmCross.Platform;
</code>```

To the top of App.cs.

Body:
using MvvmCross.Platform.IoC;
using Acr.UserDialogs;

namespace YourMom.Core
{
    public class App : MvvmCross.Core.ViewModels.MvxApplication
    {
        public override void Initialize()
        {
            CreatableTypes()
                .EndingWith("Service")
                .AsInterfaces()
                .RegisterAsLazySingleton();

            Mvx.RegisterSingleton<IUserDialogs>(() => UserDialogs.Instance);

            RegisterAppStart<ViewModels.FirstViewModel>();
        }
    }
}

I try to use use dialog plugin for Xamarin mvvmcross. It says to put the registerSingleton code in my PCL app.cs, but i have error saying Mvx is not recognized. I am pretty sure i need to "using" some package i just don't know what. Pls help.

Body:
Guess I'm answering my own question yet again.

The one to "import" is MvvmCross.Platform;

So to solve this issue, just add

using MvvmCross.Platform;

To the top of App.cs.


答:
here is fix to your problem

```<code>old_d = {'A': {'a': {1: [('string1', 'string2')]}},
 'B': {'b': {}},
 'C': {}
}

new_d ={}

for k,v in old_d.iteritems():
print k
print v
if v:
    for a,b in v.iteritems():
        if b:
            new_d[k]=v
            new_d[k][a]=b
old_d = new_d
print "old_d", old_d
</code>```

output: old_d {'A': {'a': {1: [('string1', 'string2')]}}}

Title: Python iterate nested dictionary to remove keys

Body:
I want to remove nested keys in a dictionary whose values are empty.

Example:

d = {'A': {'a': {1: [('string1', 'string2')]}},
     'B': {'b': {}},
     'C': {}
    }

For each of the main keys, there is a sub key and a sub sub key.
If any of the key's values are empty, i want to remove the entire key.

However, i get the error :RuntimeError: dictionary changed size during iteration
when i loop through the dictionary to delete empty values.

for k,v in d.iteritems():
    if not v:
        del d[k]
    else:
        for a,b in v.iteritems():
        if not b:
            del d[k][a]

desired output:

d = {'A': {'a': {1: [('string1', 'string2')]}}}

Body:
here is fix to your problem

old_d = {'A': {'a': {1: [('string1', 'string2')]}},
 'B': {'b': {}},
 'C': {}
}

new_d ={}

for k,v in old_d.iteritems():
print k
print v
if v:
    for a,b in v.iteritems():
        if b:
            new_d[k]=v
            new_d[k][a]=b
old_d = new_d
print "old_d", old_d

output: old_d {'A': {'a': {1: [('string1', 'string2')]}}}


问:
How to show table in columns from to to bottom?
I have array:

```<code>$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];
</code>```

How can I show this data from array in table from top to bottom?

This should looks this:

```<code>category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423
</code>```

I tried:

```<code><table>
  <tr>
     <?php foreach ($array as $category): ?>
         <td><?php echo $category ?></td>
     <?php endforeach ?>
  </tr>
//????
</table>
</code>```

答:
I think your question is very similar to this

First calculate the $max_products. Then print header (category1, category2, etc). Then in nested loop print elements in rows to $max_products (you need to check if that category has element with index $i ofc).

```<code>$max_products = 0;

foreach($array as $category => $products){

    $current = count($products);

    if($current > $max_products){
        $max_products = $current;
    }
}?>

<table>
    <thead>
        <tr>
            <?php
                foreach( $array as $category => $products ){
                    echo "<th>$category</th>";
                }
            ?>
        </tr>
    </thead>
    <tbody>

        <?php for( $i = 0; $i < $max_products; $i++ ){ ?>
        <tr>

            <?php
                foreach( $array as $category => $products ){

                    if( $products[$i] ){
                        echo "<td>$products[$i]</td>";
                    } else {
                        echo "<td> </td>";
                    }

                }
            ?>

        </tr>
        <?php } ?>

    </tbody>
</table>
</code>```

Body:
I have array:

$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];

How can I show this data from array in table from top to bottom?

This should looks this:

category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423

I tried:

     <?php foreach ($array as $category): ?>
         <?php echo $category ?>
     <?php endforeach ?>

//????

Body:
I think your question is very similar to this

First calculate the $max_products. Then print header (category1, category2, etc). Then in nested loop print elements in rows to $max_products (you need to check if that category has element with index $i ofc).

$max_products = 0;

foreach($array as $category => $products){

    $current = count($products);

    if($current > $max_products){
        $max_products = $current;
    }
}?>

<table>
    <thead>
        <tr>
            <?php
                foreach( $array as $category => $products ){
                    echo "<th>$category</th>";
                }
            ?>
        </tr>
    </thead>
    <tbody>

        <?php for( $i = 0; $i < $max_products; $i++ ){ ?>
        <tr>

            <?php
                foreach( $array as $category => $products ){

                    if( $products[$i] ){
                        echo "<td>$products[$i]</td>";
                    } else {
                        echo "<td>&nbsp;</td>";
                    }

                }
            ?>

        </tr>
        <?php } ?>

    </tbody>
</table>


问:
adding facebook share button in gwt application
I have been working with gwt and gxt since around few months,

I am working on a web site which needs to interact with social media web site like facebook,

I am trying to add fcebook share button in  my web site , i tried below way -

I tried using HTML -

```<code>    HTML facebookButton = new HTML();
                    facebookButton.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

facebookButton.setHTML("<div class=\"fb-share-button\" data-href=\"https://developers.facebook.com/docs/plugins/\" data-layout=\"button\" data-size=\"small\" data-mobile-iframe=\"true\"><a class=\"fb-xfbml-parse-ignore\" target=\"_blank\" href=\"https://www.facebook.com/sharer/......src=sdkpreparse\"> <img src=\"img/social/facebook.png\"  > </a></div>");
</code>```

But it does nothing -

tab.getUrlHeader() - this what i want to share

i searched across , but could not find anything .

is it possible to create such button in gwt/gxt by any way ..?

any help is appreciated

答:
```<code>facebookButton.setHTML("<div class=\"fb-share-button\" data-href=\"https://developers.facebook.com/docs/plugins/\" data-layout=\"button\" data-size=\"small\" data-mobile-iframe=\"true\"><a class=\"fb-xfbml-parse-ignore\" target=\"_blank\" href=\"https://www.facebook.com/sharer/......src=sdkpreparse\"> <img src=\"img/social/facebook.png\"  > </a></div>");
</code>```

i think this what you copied from facebook share button -

This is correct , can't understand why this is not working for you.

You can try the iFrame approach. It is simple and easy.

I guess you have already created the facebook APP id from your developer account.

go to this page -

```<code>https://developers.facebook.com/docs/plugins/share-button
</code>```

then enter the url you want to share -

URL to share

also choose the layout and the button size -

Layout-
Button Size-

Then click on Get Code - You will get the pop up.

In this pop up go to iframe tab - and copy the iframe element.

Then you can set this in your Html Label in GWT like this.

```<code>facebookButton.setHTML("<iframe src=\"https://www.facebook.com/plugins/share_button.php?href=......");
</code>```

Let me know if it works

Body:
I have been working with gwt and gxt since around few months,

I am working on a web site which needs to interact with social media web site like facebook,

I am trying to add fcebook share button in  my web site , i tried below way -

I tried using HTML -

    HTML facebookButton = new HTML();
                    facebookButton.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

facebookButton.setHTML("

");

But it does nothing -

tab.getUrlHeader() - this what i want to share

i searched across , but could not find anything .

is it possible to create such button in gwt/gxt by any way ..?

any help is appreciated

Body:
facebookButton.setHTML("<div class=\"fb-share-button\" data-href=\"https://developers.facebook.com/docs/plugins/\" data-layout=\"button\" data-size=\"small\" data-mobile-iframe=\"true\"><a class=\"fb-xfbml-parse-ignore\" target=\"_blank\" href=\"https://www.facebook.com/sharer/......src=sdkpreparse\"> <img src=\"img/social/facebook.png\"  > </a></div>");

i think this what you copied from facebook share button -

This is correct , can't understand why this is not working for you.

You can try the iFrame approach. It is simple and easy.

I guess you have already created the facebook APP id from your developer account.

go to this page -

https://developers.facebook.com/docs/plugins/share-button

then enter the url you want to share -

URL to share

also choose the layout and the button size -

Layout-
Button Size-

Then click on Get Code - You will get the pop up.

In this pop up go to iframe tab - and copy the iframe element.

Then you can set this in your Html Label in GWT like this.

facebookButton.setHTML("<iframe src=\"https://www.facebook.com/plugins/share_button.php?href=......");

Let me know if it works


问:
How to add section header/footer view when using AsyncDisplayKit?
It seems that currently ASTableNode and ASTableView both lack the support of section header/footer view.

I cannot only find a protocol method:

```<code>- (nullable NSString *)tableNode:(ASTableNode *)tableNode titleForHeaderInSection:(NSInteger)section
</code>```

which shows nothing.

And the delegate/dataSource setter methods have been intercepted by AsyncDisplayKit, so that I cannot use the UIKit's way to do it.

So can I add section header/footer view when I'm using AsyncDisplayKit?

答:
Just find out that ASTableNode will call the UITableViewDelegate methods.

So just implement the methods

```<code>- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
</code>```

And it will work just like before.

Body:
It seems that currently ASTableNode and ASTableView both lack the support of section header/footer view.

I cannot only find a protocol method:

- (nullable NSString *)tableNode:(ASTableNode *)tableNode titleForHeaderInSection:(NSInteger)section

which shows nothing.

And the delegate/dataSource setter methods have been intercepted by AsyncDisplayKit, so that I cannot use the UIKit's way to do it.

So can I add section header/footer view when I'm using AsyncDisplayKit?

Body:
Just find out that ASTableNode will call the UITableViewDelegate methods.

So just implement the methods

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;

And it will work just like before.


问:
Find and replace in a loop using macro in Excel
I have two sheets. Sheet 1 contains the following data

Sheet 1:

```<code>Column 1  column 2
Hotel A   New York
Hotel B   Melbourne
</code>```

And I wish to replace the value in sheet 2 with this value

Sheet 2 is like that :

```<code>Column 1    Column 2   Column 3

Name        ....        .....
.....       ....        City
....        ....        ....
Name        ....        .....
....        .....       City
</code>```

My ideal output will be :

```<code>Column1     Column 2    Column 3

Hotel A     ....        .....
.....       ....        New York
....        ....        ....
Hotel B     ....        .....
....        ....        Melbourne
</code>```

So, I wish to go through a loop in sheet 1 and read the name and city of hotels and go to sheet 2 and find the words Name and City and replace them with what I read in sheet 1. I'm very new in VBA and started my code like that and it even goes to loop. Why is it so?

```<code>Sub testLoopPaste()
   Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 2

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

  Next i

 End Sub
</code>```

Any tips or guidance is appreciated.

答:
Cells.Replace will change all occurrences of What with Replacement.

You need to Find the cell you are looking for, and then replace the value in just that cell:

```<code>Sub testLoopPaste()
    'Note: existing code was declaring j, k and L as Variant
    Dim j As String, k As String, L As String, b As String
    Dim i As Long
    Dim wb As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim found As Range

    Set wb = ThisWorkbook
    Set sht1 = wb.Sheets("Sheet1")
    Set sht2 = wb.Sheets("Sheet2")

    j = "Name"
    b = "City"

    For i = 1 To 2
        ' always advisable to specify .Value rather than assuming it will be the default property
        k = sht1.Range("A" & i).Value
        L = sht1.Range("B" & i).Value

        Set found = sht2.Cells.Find(What:=j, _
                                    LookIn:=xlValues, _
                                    LookAt:=xlWhole, _
                                    After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=False, _
                                    SearchFormat:=False)
        If Not found Is Nothing Then
            found.Value = k
        End If

        Set found = sht2.Cells.Find(What:=b, _
                                    LookIn:=xlValues, _
                                    LookAt:=xlWhole, _
                                    After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=False, _
                                    SearchFormat:=False)
        If Not found Is Nothing Then
            found.Value = L
        End If
    Next i

End Sub
</code>```

Body:
I have two sheets. Sheet 1 contains the following data

Sheet 1:

Column 1  column 2
Hotel A   New York
Hotel B   Melbourne

And I wish to replace the value in sheet 2 with this value

Sheet 2 is like that :

Column 1    Column 2   Column 3

Name        ....        .....
.....       ....        City
....        ....        ....
Name        ....        .....
....        .....       City

My ideal output will be :

Column1     Column 2    Column 3

Hotel A     ....        .....
.....       ....        New York
....        ....        ....
Hotel B     ....        .....
....        ....        Melbourne

So, I wish to go through a loop in sheet 1 and read the name and city of hotels and go to sheet 2 and find the words Name and City and replace them with what I read in sheet 1. I'm very new in VBA and started my code like that and it even goes to loop. Why is it so?

Sub testLoopPaste()
   Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 2

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

  Next i

 End Sub

Any tips or guidance is appreciated.

Body:
Cells.Replace will change all occurrences of What with Replacement.

You need to Find the cell you are looking for, and then replace the value in just that cell:

Sub testLoopPaste()
    'Note: existing code was declaring j, k and L as Variant
    Dim j As String, k As String, L As String, b As String
    Dim i As Long
    Dim wb As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim found As Range

    Set wb = ThisWorkbook
    Set sht1 = wb.Sheets("Sheet1")
    Set sht2 = wb.Sheets("Sheet2")

    j = "Name"
    b = "City"

    For i = 1 To 2
        ' always advisable to specify .Value rather than assuming it will be the default property
        k = sht1.Range("A" & i).Value
        L = sht1.Range("B" & i).Value

        Set found = sht2.Cells.Find(What:=j, _
                                    LookIn:=xlValues, _
                                    LookAt:=xlWhole, _
                                    After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=False, _
                                    SearchFormat:=False)
        If Not found Is Nothing Then
            found.Value = k
        End If

        Set found = sht2.Cells.Find(What:=b, _
                                    LookIn:=xlValues, _
                                    LookAt:=xlWhole, _
                                    After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=False, _
                                    SearchFormat:=False)
        If Not found Is Nothing Then
            found.Value = L
        End If
    Next i

End Sub


问:
UITableView when cell scroll to top, the cell will fixed on the top
In TableView Middle that one "Popular | Latest | Top Sales | Price"
when scroll in tableview, the middle cell will fixed on the top.

So, How to use UITableView Do like this?

Below Sample photo

Photo Sample First

Photo Sample Second

答:
You want to add two sections,
1st header height = 0
2st header height = 44</p>


答:
```<code>val data = joinDataRdd.map(x=>(x._1,x._2._1._1.split(",")(3)))
</code>```

You are trying to split the tuple so that is why the error message. At the given position x._2._1 ,
(41234,((102921,249,2,109.94,54.97),(2014-04-04 00:00:00.0,3182,PENDING_PAYMENT))), the highlighted data is the result. So if you are looking to dig inside the tuple, then you need to advance one position.

Body:
Given is data by joining two tables.

joinDataRdd.take(5).foreach(println)
(41234,((102921,249,2,109.94,54.97),(2014-04-04 00:00:00.0,3182,PENDING_PAYMENT)))
(65722,((164249,365,2,119.98,59.99),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164250,730,5,400.0,80.0),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164251,1004,1,399.98,399.98),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164252,627,5,199.95,39.99),(2014-05-23 00:00:00.0,4077,COMPLETE)))

When I am trying to get following
 val data = joinDataRdd.map(x=>(x._1,x._2._1.split(",")(3)))

It's is throwing an error :
value split is not a member of (String, String, String, String, String)

Body:
val data = joinDataRdd.map(x=>(x._1,x._2._1._1.split(",")(3)))

You are trying to split the tuple so that is why the error message. At the given position x._2._1 ,
(41234,((102921,249,2,109.94,54.97),(2014-04-04 00:00:00.0,3182,PENDING_PAYMENT))), the highlighted data is the result. So if you are looking to dig inside the tuple, then you need to advance one position.


问:
How do I clone a job in Jenkins?
Jenkins has the Gerrit Plugin in place so that when we do check-ins to Gerrit, Jenkins performs a build and if it succeeds, then the modification in Gerrit is verified.  If the build fails then it is not.  My understanding is that this is accomplished through jobs set up in Jenkins.  We have now created a new branch (git) and I guess I need to clone the existing jobs pointing to the other branch so that this same workflow occurs and builds are performed on every commit.  Can somebody explain how I would clone these jobs? I don't seem to see a way to do it through the UI nor can I even see a way to list the jobs out through the UI.

答: You could use Jobcopy Builder plugin</p>

Title: How do I clone a job in Jenkins?

Body: You could use Jobcopy Builder plugin


问:
How can i set double height to Imageview programmatically?
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

```<code>//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);
</code>```

答:
You can try this code it's move layout height by pro-grammatically.</p>

```<code> private void moveOffScreen() {

        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int screenHeight = displaymetrics.heightPixels;

        int offset = (int) (screenHeight * 0.50); /* percent to move */

        LinearLayout.LayoutParams rlParams =
                (LinearLayout.LayoutParams) mChart.getLayoutParams();
        rlParams.setMargins(0, 0, 0, -offset);
        mChart.setLayoutParams(rlParams);
    }
</code>```

Body:
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);

Body:
You can try this code it's move layout height by pro-grammatically.

 private void moveOffScreen() {

        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int screenHeight = displaymetrics.heightPixels;

        int offset = (int) (screenHeight * 0.50); /* percent to move */

        LinearLayout.LayoutParams rlParams =
                (LinearLayout.LayoutParams) mChart.getLayoutParams();
        rlParams.setMargins(0, 0, 0, -offset);
        mChart.setLayoutParams(rlParams);
    }


问:
In excel, How to calculate cricket overs completed and overs left to bowl from a cricket table?
This image will give an idea what I exactly looking for. The completed cells calculated and return the overs completed value and the empty cells calculated the remaining overs value. Please help me.</p>

答:
Use these formula

Balls (B23) =120-COUNTBLANK(B2:G21)

Overs (B24) =INT(B23/6)+MOD(B23,10)/10

Overs left (B25) =20-B24

B2:G21 is the range marked as red boxes(combined) in your image


问:
What do you deploy to clients SVN branches or tags
Not long ago we were using Microsoft VSS as our version control tool, and used to create branch of our code after the end of every release and deploy that to our clients.

Now we have moved to SVN and lately there have been lot of discussion about tags/branches, should we tag/branch our code after development for a particular release?

SVN actually recommends "tags" for such a purpose, but also recommend not to make any changes to that further, so where will we make heinous bug fixes that comes up for this release?

Another thing that is doing round is to create both tag and branch, deploy tag to clients, and incase any bug(s) comes up, fix will be made to branch and then tagged again :-(

What do other people do?

答:
Create a tag on the specific revision of a code line (e.g. trunk) and ALWAYS do releases from your tags.  Tags in svn, while not enforced by svn itself, are meant to be snapshots and reference points.  Take advantage of that implicit notion and only release a build created from a tag that you, and others, know corresponds to a specific release.  </p>

<p>Use branches for committing maintenance patches to a specific release (e.g. create a branch from your tag if you need to patch your release) and follow the same for your patches by by tagging your branch when you release from it also.  </p>

OwnerDisplayName: JC

LastEditorDisplayName: Hank Gay

Body:
Create a tag on the specific revision of a code line (e.g. trunk) and ALWAYS do releases from your tags.  Tags in svn, while not enforced by svn itself, are meant to be snapshots and reference points.  Take advantage of that implicit notion and only release a build created from a tag that you, and others, know corresponds to a specific release.

Use branches for committing maintenance patches to a specific release (e.g. create a branch from your tag if you need to patch your release) and follow the same for your patches by by tagging your branch when you release from it also.

OwnerDisplayName: whaley


问:
Customize Liquibase Control tables (DATABASECHANGELOG & DATABAEECHANGELOGLOCK)
Following the inputs from the below forum, system properties were specified and customized names for DATABASECHANGELOG & DATABASECHANGELOGLOCK tables were used & setup (on liquibase update execution).
http://forum.liquibase.org/topic/configurable-databasechangelog-table-name

Liquibase version-3.5.1, Database-Oracle 12c, OS-Redhat Linux

But, on subsequent attempts to execute future liquibase updates (against same database schema), the execution fails as its trying to recreate the customized DATABASECHANGELOG table again - failing with Object Name already in use. This does not happen when trying to use the standard liquibase control tables names (i.e. DATABASECHANGELOG & DATABASECHANGELOGLOCK)

Is there an option to skip recreation of customized liquibase control tables OR another fix for this this issue?

答:
Why setting these as system properties?

You can  invoke liquibase like the following (or these arguments defined in the properties file):

```<code>liquibase <regular arguments > --liquibaseSchemaName=YOUR_SCHEMA \
     --databaseChangeLogTableName=YOUR_DBCHANGELOG \
     --databaseChangeLogLockTableName=YOUR_DBCHANGELOGLOCK ....
</code>```

It works fine for us (liquibase 3.5.1, Oracle 12c).

Thanks

Body:
Why setting these as system properties?

You can  invoke liquibase like the following (or these arguments defined in the properties file):

liquibase <regular arguments > --liquibaseSchemaName=YOUR_SCHEMA \
     --databaseChangeLogTableName=YOUR_DBCHANGELOG \
     --databaseChangeLogLockTableName=YOUR_DBCHANGELOGLOCK ....

It works fine for us (liquibase 3.5.1, Oracle 12c).

Thanks


问:
Different results using python chisquare and using table of Chi-squared values
I need to get p-value through Chi-square.
My programm is:

```<code>from scipy.stats import chisquare

c = chisquare([10,4,7,5],ddof=[0,1,2,3])

print(c)
</code>```

The result is:

```<code>Power_divergenceResult(statistic=3.2307692307692308, pvalue=array([ 0.35739509,  0.19881419,  0.07226674,         nan]))
</code>```

When I try to get p-value using table of Chi-squared values( for example from this site https://www.medcalc.org/manual/chi-square-table.php ), results are different.
In this example using python p-value with degrees of freedom = 1(ddof=0) is  0.35739509 but using table p-value is 0.01.
Could you please explain why results are different?

答:
The function chisquare performes the Chi-squared hypothesis test but the table is about the Chi-square distribution.

If you want to work with the distribution you need to use scipy.stats.chi2. In particular, to replicate values from the table:

```<code>import scipy as sp

p = 0.1
df = 5

x = sp.stats.chi2.ppf(1-p, df=df)
print(x)  # 9.23635689978
</code>```

And to get the p-value for a given x and degrees of freedom:

```<code>p = 1 - sp.stats.chi2.cdf([10,4,7,5], df=[0,1,2,3])
print(p)
# [        nan  0.04550026  0.03019738  0.17179714]
</code>```

Note that the table defines p as the integral over the probability density function from x to infinity. The cumulative density function in scipy is the integral from 0 to x. Therefore, p = 1 - cdf.

Body:
I need to get p-value through Chi-square.
My programm is:

from scipy.stats import chisquare

c = chisquare([10,4,7,5],ddof=[0,1,2,3])

print(c)

The result is:

Power_divergenceResult(statistic=3.2307692307692308, pvalue=array([ 0.35739509,  0.19881419,  0.07226674,         nan]))

When I try to get p-value using table of Chi-squared values( for example from this site https://www.medcalc.org/manual/chi-square-table.php ), results are different.
In this example using python p-value with degrees of freedom = 1(ddof=0) is  0.35739509 but using table p-value is 0.01.
Could you please explain why results are different?

Body:
The function chisquare performes the Chi-squared hypothesis test but the table is about the Chi-square distribution.

If you want to work with the distribution you need to use scipy.stats.chi2. In particular, to replicate values from the table:

import scipy as sp

p = 0.1
df = 5

x = sp.stats.chi2.ppf(1-p, df=df)
print(x)  # 9.23635689978

And to get the p-value for a given x and degrees of freedom:

p = 1 - sp.stats.chi2.cdf([10,4,7,5], df=[0,1,2,3])
print(p)
# [        nan  0.04550026  0.03019738  0.17179714]

Note that the table defines p as the integral over the probability density function from x to infinity. The cumulative density function in scipy is the integral from 0 to x. Therefore, p = 1 - cdf.


问:
swift 3 - play video in fullscreen when rotated to landscape
I have a container view that plays the video in it when device is portrait.
I want the video to play fullscreen automatically when device is rotated.
I've tried this code that detects when device is rotated but it doesn't change the container to full screen

```<code>override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    if (UIDevice.current.orientation.isLandscape) {

        videoContainerView.frame = self.view.frame
       // self.videoContainerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) // this didn't work to....
        print("Device is landscape")
    }
    else{
        print("Device is portrait")
    }

}
</code>```

The video is on an avplayer player.
thank's

答:
I found another and better way to solve this problem because on this way the controlls are visible. the main idea is to move the AVPlayerViewController object to A new subView and set It's frame to full screen.  here is my code..

```<code>override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    if (UIDevice.current.orientation.isLandscape) {

                    DispatchQueue.main.async {
                        self.playerController.player = self.player
                        self.addChildViewController(self.playerController)
                        self.view.addSubview(self.playerController.view)
                        self.playerController.view.frame = self.view.frame

        }
        print("Device is landscape")
    }
</code>```

When device is rotated back to portrait add this subView to the previous frame and set it's size again. here's my code.

```<code>else{
        print("Device is portrait")
        videoContainerView.addSubview(playerController.view)
        playerController.view.frame = videoContainerView.bounds
        controllsContainerView.frame = videoContainerView.bounds
    }
}
</code>```

Hope it helps. Good Luck!

Body:
I have a container view that plays the video in it when device is portrait.
I want the video to play fullscreen automatically when device is rotated.
I've tried this code that detects when device is rotated but it doesn't change the container to full screen

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    if (UIDevice.current.orientation.isLandscape) {

        videoContainerView.frame = self.view.frame
       // self.videoContainerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) // this didn't work to....
        print("Device is landscape")
    }
    else{
        print("Device is portrait")
    }

}

The video is on an avplayer player.
thank's

Body:
I found another and better way to solve this problem because on this way the controlls are visible. the main idea is to move the AVPlayerViewController object to A new subView and set It's frame to full screen.  here is my code..

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    if (UIDevice.current.orientation.isLandscape) {

                    DispatchQueue.main.async {
                        self.playerController.player = self.player
                        self.addChildViewController(self.playerController)
                        self.view.addSubview(self.playerController.view)
                        self.playerController.view.frame = self.view.frame

        }
        print("Device is landscape")
    }

When device is rotated back to portrait add this subView to the previous frame and set it's size again. here's my code.

else{
        print("Device is portrait")
        videoContainerView.addSubview(playerController.view)
        playerController.view.frame = videoContainerView.bounds
        controllsContainerView.frame = videoContainerView.bounds
    }
}

Hope it helps. Good Luck!


问:
MySQL said: Documentation #2014 - Commands out of sync; you can't run this command now
Mysql function getLastMediaId()

```<code>`BEGIN
DECLARE Lid INT;
select id into Lid FROM projectmedia order by id desc limit 1;
RETURN(Lid);
END`
</code>```

Mysql procedure

```<code>`BEGIN   DECLARE lid INT;
IF last_id=0 THEN SET lid=getLastMediaId();
ELSE SET lid=last_id;
END IF;
SELECT * FROM projectmedia WHERE id < last_id ORDER BY id DESC LIMIT 5;
END`
</code>```

答:
I replaced  WHERE id < last_id with  WHERE id < lid

```<code>SELECT * FROM projectmedia WHERE id < lid ORDER BY id DESC LIMIT 5;
</code>```

Body:
Mysql function getLastMediaId()

`BEGIN
DECLARE Lid INT;
select id into Lid FROM projectmedia order by id desc limit 1;
RETURN(Lid);
END`

Mysql procedure

`BEGIN   DECLARE lid INT;
IF last_id=0 THEN SET lid=getLastMediaId();
ELSE SET lid=last_id;
END IF;
SELECT * FROM projectmedia WHERE id < last_id ORDER BY id DESC LIMIT 5;
END`

Body:
I replaced  WHERE id < last_id with  WHERE id < lid

SELECT * FROM projectmedia WHERE id < lid ORDER BY id DESC LIMIT 5;


问:
Exporting files with PowerShell issue
I am trying to export files from a data dump and I am in dire need of some assistance. All of the files that I am trying to export are in pdf, doc, xlsx, jpg, and png format. Due to how the data dump was assembled, the files were renamed to f0.pdf, f0.doc, etc., In addition, the files are found in different subfolders (ex: Data\000\004\0000001212). Furthermore, within a subfolder, if there is a file in there it is accompanied by a m.xml file (for reference please see pic here). The m.xml file is important as it contains the original filename reflected by the "LDDOCUMENTNAME" field:

```<code>ex: <TextVar length="255" field="LDDOCUMENTNAME">ABC.pdf</TextVar>
</code>```

I attempted to rename and export the files using PowerShell however some of the pdf files did not go through (I searched for all the pdf files in the subfolders and compared it to the number of exported pdf files).

This is what my script looks like:

```<code>$fsoFiles = Get-ChildItem -Path C:\Files -Filter *m.xml* -Recurse
ForEach($fsoFile in $fsoFiles)
{
    $docM = Select-String $fsoFile -Pattern "LDDOCUMENTNAME"
    $txtNewFile = $docM.Line.Substring(0,($docM.Line.Length-10))
    $txtNewFile = $txtNewFile.Split(">")[-1]
    $txtExtension = $txtNewFile.Split(".")[-1]
    $txtOldFile = ([string]$fsoFile.Directory+"\"+"f0."+$txtExtension)
    Copy-Item $txtOldFile C:\Extracted\$txtNewFile
}
</code>```

Essentially I asked PowerShell to search through all the subfolders and filter out only the folders with a m.xml file. PowerShell is then supposed to rename the corresponding file back to its original filename using the value found in the "LDDOCUMENTNAME" field.

When I run my script I am presented with a bunch of these error messages:

```<code>You cannot call a method on a null-valued expression.
    At line:6 char:5
    +     $txtNewFile = $docM.Line.Substring(0,($docM.Line.Length-10))
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
</code>```

I'm assuming this is the reason why PowerShell could not export some of the pdf files? Maybe the "LDDOCUMENTNAME" field in the corresponding m.xml files are blank?

I tried adding a IF statement inside of my FOR loop to see if I could get a location of the files that could not be exported but I was met with the same error messages:

```<code>    If ($docM = $null)

     {
        Get-ChildItem -Path C:\Files -include !$docM -Recurse -Force -Name C:\Extracted\listofPaths.txt

        }

    else
</code>```

Does anybody here know of a way to accomplish this? I am literally pulling my hair out. Any help would be much appreciated. Thanks!

答:
As the XML file is not trivial, it should not be processed as text. Load it as an XML one and use XPath to pick relevant nodes. Like so,</p>

```<code># XML is 1st class citizen in Powershell
[xml]$doc = get-content c:\path\to\doc.xml
# Select all the TextVar nodes that have attribute field='LDDOCUMENTNAME'
$nl = $doc.selectnodes("//TextVar[@field='LDDOCUMENTNAME']")
# Did we find one?
if($nl.count -eq 1) {
    # Do something with the element's text data
    # Rename the data file would happen here, for now
    # print the results for further review
    Write-Host $nl[0].InnerText
}
# Todo: handle no elements found case
# Todo: handle multiple elements found case
</code>```

Title: Exporting files with PowerShell issue

Body:
I am trying to export files from a data dump and I am in dire need of some assistance. All of the files that I am trying to export are in pdf, doc, xlsx, jpg, and png format. Due to how the data dump was assembled, the files were renamed to f0.pdf, f0.doc, etc., In addition, the files are found in different subfolders (ex: Data\000\004\0000001212). Furthermore, within a subfolder, if there is a file in there it is accompanied by a m.xml file (for reference please see pic here). The m.xml file is important as it contains the original filename reflected by the "LDDOCUMENTNAME" field:

ex: <TextVar length="255" field="LDDOCUMENTNAME">ABC.pdf</TextVar>

I attempted to rename and export the files using PowerShell however some of the pdf files did not go through (I searched for all the pdf files in the subfolders and compared it to the number of exported pdf files).

This is what my script looks like:

$fsoFiles = Get-ChildItem -Path C:\Files -Filter *m.xml* -Recurse
ForEach($fsoFile in $fsoFiles)
{
    $docM = Select-String $fsoFile -Pattern "LDDOCUMENTNAME"
    $txtNewFile = $docM.Line.Substring(0,($docM.Line.Length-10))
    $txtNewFile = $txtNewFile.Split(">")[-1]
    $txtExtension = $txtNewFile.Split(".")[-1]
    $txtOldFile = ([string]$fsoFile.Directory+"\"+"f0."+$txtExtension)
    Copy-Item $txtOldFile C:\Extracted\$txtNewFile
}

Essentially I asked PowerShell to search through all the subfolders and filter out only the folders with a m.xml file. PowerShell is then supposed to rename the corresponding file back to its original filename using the value found in the "LDDOCUMENTNAME" field.

When I run my script I am presented with a bunch of these error messages:

You cannot call a method on a null-valued expression.
    At line:6 char:5
    +     $txtNewFile = $docM.Line.Substring(0,($docM.Line.Length-10))
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

I'm assuming this is the reason why PowerShell could not export some of the pdf files? Maybe the "LDDOCUMENTNAME" field in the corresponding m.xml files are blank?

I tried adding a IF statement inside of my FOR loop to see if I could get a location of the files that could not be exported but I was met with the same error messages:

    If ($docM = $null)

     {
        Get-ChildItem -Path C:\Files -include !$docM -Recurse -Force -Name C:\Extracted\listofPaths.txt

        }

    else

Does anybody here know of a way to accomplish this? I am literally pulling my hair out. Any help would be much appreciated. Thanks!

Body:
As the XML file is not trivial, it should not be processed as text. Load it as an XML one and use XPath to pick relevant nodes. Like so,

# XML is 1st class citizen in Powershell
[xml]$doc = get-content c:\path\to\doc.xml
# Select all the TextVar nodes that have attribute field='LDDOCUMENTNAME'
$nl = $doc.selectnodes("//TextVar[@field='LDDOCUMENTNAME']")
# Did we find one?
if($nl.count -eq 1) {
    # Do something with the element's text data
    # Rename the data file would happen here, for now
    # print the results for further review
    Write-Host $nl[0].InnerText
}
# Todo: handle no elements found case
# Todo: handle multiple elements found case


问:
Eclipse not able to select Hybrid Mobile Engine for Hybrid Cordova application?
I am using Eclipse Neon.3 and installed Thym plugin successfully. Now creating a new Project through New->Project->Hybrid Mobile(Cordova) Application project-> Project name as CordovaApp-> Next -> Select Hybrid Mobile Engine -> Here , unable to select any checkbox for Android, Windows tried download and search also. Here, wizard attached.

答:
Just click on Downloads Tab and select platform you preferred. If you have selected Android and selected android 6.3.0 cordova nightly download it and click on finish.
Now to see that is installed in your project. Right click on Project and select Properties, and click on Hybrid Mobile Engine you can able to view under the Platform selection.