问:
Facebook Account SMS integration failed on Android
Facebook Account kit sms integration didn't work.
When I used code from github it works and send sms through already integrated account in this App.
https://github.com/fbsamples/account-kit-samples-for-android/tree/master/samples/AccountKitSimpleSample

But when i Create App at Facebook account kit, copy Client Token and App Id. then it didn't work.
"A system issue occurred. Please try again" error occurred
How can i resolve this problem?

答:
I guess you did not  enable Enable client access token flow in Facebook Developers panel.

Go to : Developer page

After login Select your app - > go to : Products-> Account Kit

Now enable the permission:


来源: stackexchange

问:
This program to convert infix to postfix in c is giving a runtime error.why?
```<code>#include <stdio.h>
#include <ctype.h>

char stack[50];
int top=-1;

void push(char x)
{
    stack[++top]=x;
}

char pop()
{
    if(top==-1)
        return -1;
    else
        return stack[top--];
}
</code>```

This function is used to prioritize operators:

```<code>int priority(char x)
{
    if(x=='+'|| x=='-') {
        return 1;
    } else if(x=='(') {
        return 0;
    } else if(x=='*'||x=='/') {
        return 2;
    } else {
        return 3;
    }
}

int main()
{
    char exp[50], *e, x;
    scanf("%s", exp);
    e = exp;
    while(*e != '\0') {
        if(isalnum(*e)) {
            printf("%c",*e);
        } else {
            while(priority(stack[top]) >= priority(*e)) {
                printf("%c",pop());
            }
            push(*e);
        }
        e++;
    }
    while(top!=-1) {
        printf("%c",pop());
    }
    return 0;
}
</code>```

I am getting a runtime error in this program. I have no idea why. Can u suggest to me any changes I can implement? In some compilers I get the output as some infinite loop.

答:
The first time this code is executed

```<code>while(priority(stack[top])>=priority(*e))
</code>```

the value of top is -1 so you access stack[-1]. That is not a legal access and your program may crash.

If the program doesn't crash, you'll get some "random" value that you pass to priority. Now you compare the priority of this "random" char to the priority of the first char of the input. Let's assume the comparison result in true. Then you execute:

```<code>printf("%c",pop());
</code>```

Since top is -1, the pop function will not change top so it stays at -1. Then you again do:

```<code>while(priority(stack[top])>=priority(*e))
</code>```

Since both top and *e hasn't changed, the comparison will again result in true. In other words - an endless loop.

ContentLicense: CC BY-SA 3.0

Body:
#include <stdio.h>
#include <ctype.h>

char stack[50];
int top=-1;

void push(char x)
{
    stack[++top]=x;
}

char pop()
{
    if(top==-1)
        return -1;
    else
        return stack[top--];
}

This function is used to prioritize operators:

int priority(char x)
{
    if(x=='+'|| x=='-') {
        return 1;
    } else if(x=='(') {
        return 0;
    } else if(x=='*'||x=='/') {
        return 2;
    } else {
        return 3;
    }
}

int main()
{
    char exp[50], *e, x;
    scanf("%s", exp);
    e = exp;
    while(*e != '\0') {
        if(isalnum(*e)) {
            printf("%c",*e);
        } else {
            while(priority(stack[top]) >= priority(*e)) {
                printf("%c",pop());
            }
            push(*e);
        }
        e++;
    }
    while(top!=-1) {
        printf("%c",pop());
    }
    return 0;
}

I am getting a runtime error in this program. I have no idea why. Can u suggest to me any changes I can implement? In some compilers I get the output as some infinite loop.

Body:
The first time this code is executed

while(priority(stack[top])>=priority(*e))

the value of top is -1 so you access stack[-1]. That is not a legal access and your program may crash.

If the program doesn't crash, you'll get some "random" value that you pass to priority. Now you compare the priority of this "random" char to the priority of the first char of the input. Let's assume the comparison result in true. Then you execute:

printf("%c",pop());

Since top is -1, the pop function will not change top so it stays at -1. Then you again do:

while(priority(stack[top])>=priority(*e))

Since both top and *e hasn't changed, the comparison will again result in true. In other words - an endless loop.


问:
Cells in UITableView overlapping. Many cells in one place
I'm trying to make table view with random numbers of labels in. Everything is working till I try too scroll it. Than many some of cells appear in one place. It looks like this:

Screen from simulation

To make random row height in viewDidLoad() I put this:

```<code>tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
</code>```

The code going to write randoms number of labels with random number of lines is here:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "HarvestPlan", for: indexPath) as! HarvestPlanCell
    let currentSpecies = harvestPlan[indexPath.row]

    var kindLabels = [UILabel]()
    cell.kindsNamesView.bounds.size.width = 100
    for kind in currentSpecies.kinds {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.text = kind.fullName
        label.bounds.size.width = 100
        label.sizeToFit()
        label.bounds.size.width = 100
        cell.kindsNamesView.addSubview(label)
        kindLabels.append(label)
    }

    var previous: UILabel!

    for label in kindLabels {
        label.widthAnchor.constraint(equalToConstant: 100).isActive = true
        label.heightAnchor.constraint(equalToConstant: label.bounds.height).isActive = true
        label.leadingAnchor.constraint(equalTo: cell.kindsNamesView.leadingAnchor).isActive = true

        if previous == nil {
            label.topAnchor.constraint(equalTo: cell.kindsNamesView.topAnchor).isActive = true
        }

        if previous != nil {
            label.topAnchor.constraint(equalTo: previous.bottomAnchor).isActive = true
        }

        if label == kindLabels.last {
            label.bottomAnchor.constraint(equalTo: cell.kindsNamesView.bottomAnchor).isActive = true
        }

        previous = label
    }

    return cell
</code>```

Someone have some idea how to repair it? I'm looking for answer since one week and I did't find anything about it...

答:
Thank you @Paulw11, prepareForReuse was this what I was looking for. If someone have similar problem, the answer is code below added to UITableViewCell:

```<code>override func prepareForReuse() {
    super.prepareForReuse()

    for view in kindsNames.subviews { //take all subviews from your view
        view.removeFromSuperview() //delete it from you view
    }
}
</code>```

Cheers

Body:
I'm trying to make table view with random numbers of labels in. Everything is working till I try too scroll it. Than many some of cells appear in one place. It looks like this:

Screen from simulation

To make random row height in viewDidLoad() I put this:

tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension

The code going to write randoms number of labels with random number of lines is here:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "HarvestPlan", for: indexPath) as! HarvestPlanCell
    let currentSpecies = harvestPlan[indexPath.row]

    var kindLabels = [UILabel]()
    cell.kindsNamesView.bounds.size.width = 100
    for kind in currentSpecies.kinds {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.text = kind.fullName
        label.bounds.size.width = 100
        label.sizeToFit()
        label.bounds.size.width = 100
        cell.kindsNamesView.addSubview(label)
        kindLabels.append(label)
    }

    var previous: UILabel!

    for label in kindLabels {
        label.widthAnchor.constraint(equalToConstant: 100).isActive = true
        label.heightAnchor.constraint(equalToConstant: label.bounds.height).isActive = true
        label.leadingAnchor.constraint(equalTo: cell.kindsNamesView.leadingAnchor).isActive = true

        if previous == nil {
            label.topAnchor.constraint(equalTo: cell.kindsNamesView.topAnchor).isActive = true
        }

        if previous != nil {
            label.topAnchor.constraint(equalTo: previous.bottomAnchor).isActive = true
        }

        if label == kindLabels.last {
            label.bottomAnchor.constraint(equalTo: cell.kindsNamesView.bottomAnchor).isActive = true
        }

        previous = label
    }

    return cell

Someone have some idea how to repair it? I'm looking for answer since one week and I did't find anything about it...

Body:
Thank you @Paulw11, prepareForReuse was this what I was looking for. If someone have similar problem, the answer is code below added to UITableViewCell:

override func prepareForReuse() {
    super.prepareForReuse()

    for view in kindsNames.subviews { //take all subviews from your view
        view.removeFromSuperview() //delete it from you view
    }
}

Cheers


问:
stl priority queue based on lower value first
I have a problem with stl priority queue.I want to have the priority queue in the increasing
order,which is decreasing by default.Is there any way to do this in priority queue.

And what is the complexity of building stl priority queue.If i use quick sort in an array which takes O(nlgn) is its complexity is similar to using priority queue???

Plz someone ans.Advanced thanx.

答: You can just push values multiplying them by -1 so it will be stored in reverse order unlike the actual default order...and multiply the value with -1 again while retrieving data to get it in its actual form.</p>

ContentLicense: CC BY-SA 2.5


问:
How to order a LIST in F#
Total F# n00b question.
How do I sort a LIST data structure?

Edit: Sorry, my data structure is actually a LIST.

maybe i should add my code since just using ".sort" hasn't worked:

```<code>let getDataFromDb (db: MyDB) Id =
Query.query <@ seq {
    big honking database/FLinq query
    yield  (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
} @> |> List.ofSeq
</code>```

when I change the last line of code to this:

            } @> |> List.ofSeq.sortBy fst

I get the following:

Error  1   The field, constructor or member 'sortBy' is not defined

ugh, what a pain. I'm trying this now:

```<code>|> List.ofSeq |> List.sortBy
</code>```

But I'm getting this:

Error  1   Type mismatch. Expecting a     (Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list -> 'a     but given a     ('b -> 'c) -> 'b list -> 'b list     The type '(Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list' does not match the type ''a -> 'b'

答:
Seq.sortBy would do that.

However sorting implies you know the key values of the full sequence at the time of sorting, so by definition you cannot use this on infinite sequences.

Edit:
The equivalent for lists has the same name:
List.sortBy

MSDN example:

```<code>let sortedList2 = List.sortBy (fun elem -> abs elem) [1; 4; 8; -2; 5]
printfn "%A" sortedList2
</code>```

Edit 2:

From your new example it seems like you have a list of tuples. Now it depends on what item in the tuple you want to search by.

Title: How to order a LIST in F#

Body:
Total F# n00b question.
How do I sort a LIST data structure?

Edit: Sorry, my data structure is actually a LIST.

maybe i should add my code since just using ".sort" hasn't worked:

let getDataFromDb (db: MyDB) Id =
Query.query <@ seq {
    big honking database/FLinq query
    yield  (sec, pm, sr, trade, tradeRec, i, pm_firm, files, lt)
} @> |> List.ofSeq

when I change the last line of code to this:

            } @> |> List.ofSeq.sortBy fst

I get the following:

Error  1   The field, constructor or member 'sortBy' is not defined

ugh, what a pain. I'm trying this now:

|> List.ofSeq |> List.sortBy

But I'm getting this:

Error  1   Type mismatch. Expecting a     (Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list -> 'a     but given a     ('b -> 'c) -> 'b list -> 'b list     The type '(Security * RoleContributor * RoleContributor * SuggestedTrade * SuggestedTradeRecommendation * Idea * RoleContributor * SupportingUploadedFile * LargeText) list' does not match the type ''a -> 'b'

Body:
Seq.sortBy would do that.

However sorting implies you know the key values of the full sequence at the time of sorting, so by definition you cannot use this on infinite sequences.

Edit:
The equivalent for lists has the same name:
List.sortBy

MSDN example:

let sortedList2 = List.sortBy (fun elem -> abs elem) [1; 4; 8; -2; 5]
printfn "%A" sortedList2

Edit 2:

From your new example it seems like you have a list of tuples. Now it depends on what item in the tuple you want to search by.


问:
How can I remove every listener from a page?
I know how to remove a listener from an element, but how can I remove every event listener from every element on the page?

A jQuery and pure JS solution would be nice.

答:
I would suggest to look into the .off function of jQuery.
Also, based on this stackoverflow question, I would try to remove all every listeners with the following code

```<code>$("body").find("*").off();
</code>```

Hope this could help you.

Body:
I would suggest to look into the .off function of jQuery.
Also, based on this stackoverflow question, I would try to remove all every listeners with the following code

$("body").find("*").off();

Hope this could help you.


问:
Extended Statistics with WEKA
I am using WEKA programmatically.
Is there an easy way to get the same statistic as provided by the WEKA-Gui? (Class-distribution etc.) or have one to generate it by hand (using jfree or similar)?</p>

答:
Use the Evaluation class to validate your classifier. Just check this link
Weka Evaluation

For example you have this Method:

```<code>toClassDetailsString()
</code>```

Generates a breakdown of the accuracy for each class (with default title), incorporating various information-retrieval statistics, such as true/false positive rate, precision/recall/F-Measure.

Also you can get everythink e.g. Area under ROC, Accuracy or NumFalsePositives as double values.

Title: Extended Statistics with WEKA

Body:
Use the Evaluation class to validate your classifier. Just check this link
Weka Evaluation

For example you have this Method:

toClassDetailsString()

Generates a breakdown of the accuracy for each class (with default title), incorporating various information-retrieval statistics, such as true/false positive rate, precision/recall/F-Measure.

Also you can get everythink e.g. Area under ROC, Accuracy or NumFalsePositives as double values.


问:
Neural network for letter recognition
I'm trying to add to the code for a single layer neural network which takes a bitmap as input and has 26 outputs for the likelihood of each letter in the alphabet.

The first question I have is regarding the single hidden layer that is being added. Am I correct in thinking that the hidden layer will have it's own set of output values and weights only? It doesn't need to have it's own bias'?

Can I also confirm that I'm thinking about the feedforward aspect correctly? Here's some pseudocode:

```<code>// input => hidden
for j in hiddenOutput.length:
    sum=inputs*hiddenWeights
    hiddenOutput[j] = activationFunction(sum)
// hidden => output
for j in output.length:
    sum=hiddenOutputs*weights
    output[j] = activationFunction(sum)
</code>```

Assuming that is correct, would the training be something like this?

```<code>def train(input[], desired[]):
    iterate through output and determine errors[]
    update weights & bias accordingly
    iterate through hiddenOutput and determine hiddenErrors[]
    update hiddenWeights & (same bias?) accordingly
</code>```

Thanks in advance for any help, I've read so many examples and tutorials and I'm still having trouble determining how to do everything correctly.

答:
Dylan, this is probably long after your homework assignment was due, but I do have a few thoughts about what you've posted.

Make the hidden layer much bigger than the size of the input bitmaps.

You should have different weights and biases from input -> hidden than from hidden -> output.

Spend a lot of time on your error function (discriminator).

Understand that neural nets have a tendency to get quickly locked in to a set of weights (usually incorrect). You'll need to start over and train in a different order.

The thing I learned about neural nets is that you never know why they're working (or not working). That alone is reason to keep it out of the realms of medicine and finance.

Title: Neural network for letter recognition

Body:
I'm trying to add to the code for a single layer neural network which takes a bitmap as input and has 26 outputs for the likelihood of each letter in the alphabet.

The first question I have is regarding the single hidden layer that is being added. Am I correct in thinking that the hidden layer will have it's own set of output values and weights only? It doesn't need to have it's own bias'?

Can I also confirm that I'm thinking about the feedforward aspect correctly? Here's some pseudocode:

// input => hidden
for j in hiddenOutput.length:
    sum=inputs*hiddenWeights
    hiddenOutput[j] = activationFunction(sum)
// hidden => output
for j in output.length:
    sum=hiddenOutputs*weights
    output[j] = activationFunction(sum)

Assuming that is correct, would the training be something like this?

def train(input[], desired[]):
    iterate through output and determine errors[]
    update weights & bias accordingly
    iterate through hiddenOutput and determine hiddenErrors[]
    update hiddenWeights & (same bias?) accordingly

Thanks in advance for any help, I've read so many examples and tutorials and I'm still having trouble determining how to do everything correctly.


问:
Search customer by last name in database
```<code>function search_customer($search) {
       global $db;
       $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

       $statement = $db->prepare($query);
       $statement->bindValue(':search', $search);
       $statement->execute();
       $results = $statement->fetchAll();
       $statement->closeCursor();
       return $results;
}
</code>```

<p>This code gives me a table of customers with the lastName that the user puts into the search field. But it obviously only works when you put in the full last name. Can anyone tell me how I have to change the code to get results too if I only enter for example the first letter of the last name ? </p>

答:
You can also update your function like as -

```<code>function SearchCustomer($search) {
   global $db;
   $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

   $statement = $db->prepare($query);
   $statement->bindValue(':search', '%'.$search.'%'); #Concatenate '%' sign with search String
   $statement->execute();
   $results = $statement->fetchAll();
   $statement->closeCursor();
   return $results;
}
</code>```

Note : Concatenate % sign with search string, when binding value

OR

Use MySQL CONCAT() to update your query

```<code>SELECT * FROM customers WHERE lastName LIKE CONCAT("%",:search,"%")
</code>```

Here is the details about MySQL CONCAT

Body:
function search_customer($search) {
       global $db;
       $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

       $statement = $db->prepare($query);
       $statement->bindValue(':search', $search);
       $statement->execute();
       $results = $statement->fetchAll();
       $statement->closeCursor();
       return $results;
}

This code gives me a table of customers with the lastName that the user puts into the search field. But it obviously only works when you put in the full last name. Can anyone tell me how I have to change the code to get results too if I only enter for example the first letter of the last name ?

Body:
You can also update your function like as -

function SearchCustomer($search) {
   global $db;
   $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

   $statement = $db->prepare($query);
   $statement->bindValue(':search', '%'.$search.'%'); #Concatenate '%' sign with search String
   $statement->execute();
   $results = $statement->fetchAll();
   $statement->closeCursor();
   return $results;
}

Note : Concatenate % sign with search string, when binding value

OR

Use MySQL CONCAT() to update your query

SELECT * FROM customers WHERE lastName LIKE CONCAT("%",:search,"%")

Here is the details about MySQL CONCAT


答:
It can be done by building a tally date table then join with your table data

```<code>;WITH data AS
(
    SELECT * FROM (VALUES
        ('A', '2017-02-03 08:00', '2017-02-04 17:00'),
        ('B', '2017-02-05 08:00', '2017-02-09 17:00')
    ) t(RecordId, date_from, date_to)
)
,tally AS
(
    -- It just build on the fly,
    -- actually you can prebuild the table somewhere with DateValue as a key
    SELECT MIN(CAST(date_from AS date)) AS DateValue, MAX(CAST(date_to AS date)) MaxDate FROM data
    UNION ALL SELECT DATEADD(DAY, 1, DateValue), MaxDate FROM tally WHERE DateValue < MaxDate
)
SELECT
    RecordId,
    CASE
        WHEN CAST(date_from AS date) = DateValue THEN date_from
        ELSE CAST(DateValue AS datetime)
    END AS date_from,
    CASE
        WHEN CAST(date_to AS date) = DateValue THEN date_to
        ELSE DATEADD(SECOND, -1, DATEADD(DAY, 1, CAST(DateValue AS datetime)))
    END AS date_to
FROM
    -- The joining condition creates the product effect for date range into separate dates
    data INNER JOIN tally ON DateValue BETWEEN data.date_from AND data.date_to
</code>```

https://data.stackexchange.com/stackoverflow/query/652790

Title: Split range of date and time become separate record

Body:
today i have some problem with splitting two date with their time who have range become separate record

in order to do that, for example i have this sample

----------------------------------------------------------------
| Record id | date_from               | date_to                |
----------------------------------------------------------------
|     A     | 2017-02-03 08:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------

then with script or procedure, i want get this result as expected below

----------------------------------------------------------------
| Record id | date_from               | date_to                |
----------------------------------------------------------------
|     A     | 2017-02-03 08:00:00.000 | 2017-02-03 23:59:59.000|
----------------------------------------------------------------
|     A     | 2017-02-04 00:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------

how to get this done by the way? and it's dynamic. thank you very much :)

Body:
It can be done by building a tally date table then join with your table data

;WITH data AS
(
    SELECT * FROM (VALUES
        ('A', '2017-02-03 08:00', '2017-02-04 17:00'),
        ('B', '2017-02-05 08:00', '2017-02-09 17:00')
    ) t(RecordId, date_from, date_to)
)
,tally AS
(
    -- It just build on the fly,
    -- actually you can prebuild the table somewhere with DateValue as a key
    SELECT MIN(CAST(date_from AS date)) AS DateValue, MAX(CAST(date_to AS date)) MaxDate FROM data
    UNION ALL SELECT DATEADD(DAY, 1, DateValue), MaxDate FROM tally WHERE DateValue < MaxDate
)
SELECT
    RecordId,
    CASE
        WHEN CAST(date_from AS date) = DateValue THEN date_from
        ELSE CAST(DateValue AS datetime)
    END AS date_from,
    CASE
        WHEN CAST(date_to AS date) = DateValue THEN date_to
        ELSE DATEADD(SECOND, -1, DATEADD(DAY, 1, CAST(DateValue AS datetime)))
    END AS date_to
FROM
    -- The joining condition creates the product effect for date range into separate dates
    data INNER JOIN tally ON DateValue BETWEEN data.date_from AND data.date_to

https://data.stackexchange.com/stackoverflow/query/652790


问:
call a soap webservice from ionic
i'm trying to call a soap webservice using this method : http://mcgivery.com/soap-web-services-angular-ionic/ however my screen only shows a blank page instead of the login screen. what could be the probleim?

here's my services.js code:

```<code>.factory('loginService', ['$soap', function($soap){
var base_url = 'http://localhost/UserService3/WebService1.asmx';

return {
    GetUser: function(uname){
        return $soap.post(base_url,"getUserbyUsername", {Username: uname});
    }
};
}])
</code>```

and here's my controller.js code:

```<code> .controller('loginCtrl', ['$scope', '$stateParams', '$location', '$state', 'sharedProperties2','ConnectivityMonitor', '$ionicLoading', 'loginService',
function ($scope, $stateParams, $location, $state, sharedProperties2,
ConnectivityMonitor, $ionicLoading, loginService) {

 $scope.show = function() {
    $ionicLoading.show({
      template: '<ion-spinner icon="android"></ion-spinner>',
      showBackdrop: false
    });
  };

$scope.hide = function(){
    $ionicLoading.hide();
  };

$scope.userdata = {}

$scope.enterlogin = function(usern,pass)
{
     userFactory.GetUser(usern).then(function(response) {
            alert('get = ' + JSON.stringify(response.data));
        })
}
}])
</code>```

答: apparently it could not see the previous location of the added scripts angular.soap.js and soapclient.js, so i put the 2 files inside a folder named angular-soap inside the lib folder.</p>

Title: call a soap webservice from ionic

Body:
i'm trying to call a soap webservice using this method : http://mcgivery.com/soap-web-services-angular-ionic/ however my screen only shows a blank page instead of the login screen. what could be the probleim?

here's my services.js code:

.factory('loginService', ['$soap', function($soap){
var base_url = 'http://localhost/UserService3/WebService1.asmx';

return {
    GetUser: function(uname){
        return $soap.post(base_url,"getUserbyUsername", {Username: uname});
    }
};
}])

and here's my controller.js code:

 .controller('loginCtrl', ['$scope', '$stateParams', '$location', '$state', 'sharedProperties2','ConnectivityMonitor', '$ionicLoading', 'loginService',
function ($scope, $stateParams, $location, $state, sharedProperties2,
ConnectivityMonitor, $ionicLoading, loginService) {

 $scope.show = function() {
    $ionicLoading.show({
      template: '<ion-spinner icon="android"></ion-spinner>',
      showBackdrop: false
    });
  };

$scope.hide = function(){
    $ionicLoading.hide();
  };

$scope.userdata = {}

$scope.enterlogin = function(usern,pass)
{
     userFactory.GetUser(usern).then(function(response) {
            alert('get = ' + JSON.stringify(response.data));
        })
}
}])


问:
jQuery is working with old version(1.3) not working with new version(1.11.3)

var country = {
  "Choose Country": [{
    "city": "Choose City"
  }],
  "Australia": [{
    "city": "Brisbane"
  }, {
    "city": "Melbourne"
  }, {
    "city": "Sydney"
  }],
  "Bahrain": [{
    "city": "Hamad Town"
  }, {
    "city": "Manama"
  }, {
    "city": "Muharraq"
  }, {
    "city": "Riffa"
  }],
  "Canada": [{
    "city": "Calgary"
  }, {
    "city": "Montreal"
  }, {
    "city": "Toronto"
  }, {
    "city": "Vancouver"
  }]
};

function populateuser_city() {
  var region_code1 = $('#region_code1').val();
  var select = $('#user_city');
  var options = select.attr('options');
  $('option', select).remove();
  $.each(country[region_code1], function(index, array) {
    options[options.length] = new Option(array['city']);
  });
}

populateuser_city();

$('#region_code1').change(function() {
  populateuser_city();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select></code>```

答:
Your issue is because var options = select.attr('options'); is returning undefined in the newer version of jQuery. You can fix this, and improve the logic, by just replacing the HTML of the select element instead of amending the existing option elements within it. Try this:

var country = {
  "Choose Country": [
    { "city": "Choose City" }
  ],
  "Australia": [
    { "city": "Brisbane" },
    { "city": "Melbourne" },
    { city": "Sydney" }
  ],
  "Bahrain": [
    { "city": "Hamad Town" },
    { "city": "Manama" },
    { "city": "Muharraq" },
    { "city": "Riffa" }
  ],
  "Canada": [
    { "city": "Calgary" },
    { "city": "Montreal" },
    { "city": "Toronto" },
    { "city": "Vancouver" }
  ]
};

$('#region_code1').change(function() {
  var region_code1 = $('#region_code1').val();
  var html = ''
  country[region_code1].forEach(function(country) {
    html += '<option>' + country.city + '</option>';
  })
  $('#user_city').empty().html(html);
}).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select></code>```

Body:
var country = {
  "Choose Country": [{
    "city": "Choose City"
  }],
  "Australia": [{
    "city": "Brisbane"
  }, {
    "city": "Melbourne"
  }, {
    "city": "Sydney"
  }],
  "Bahrain": [{
    "city": "Hamad Town"
  }, {
    "city": "Manama"
  }, {
    "city": "Muharraq"
  }, {
    "city": "Riffa"
  }],
  "Canada": [{
    "city": "Calgary"
  }, {
    "city": "Montreal"
  }, {
    "city": "Toronto"
  }, {
    "city": "Vancouver"
  }]
};

function populateuser_city() {
  var region_code1 = $('#region_code1').val();
  var select = $('#user_city');
  var options = select.attr('options');
  $('option', select).remove();
  $.each(country[region_code1], function(index, array) {
    options[options.length] = new Option(array['city']);
  });
}

populateuser_city();

$('#region_code1').change(function() {
  populateuser_city();
});

<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select>

Body:
Your issue is because var options = select.attr('options'); is returning undefined in the newer version of jQuery. You can fix this, and improve the logic, by just replacing the HTML of the select element instead of amending the existing option elements within it. Try this:

var country = {
  "Choose Country": [
    { "city": "Choose City" }
  ],
  "Australia": [
    { "city": "Brisbane" },
    { "city": "Melbourne" },
    { city": "Sydney" }
  ],
  "Bahrain": [
    { "city": "Hamad Town" },
    { "city": "Manama" },
    { "city": "Muharraq" },
    { "city": "Riffa" }
  ],
  "Canada": [
    { "city": "Calgary" },
    { "city": "Montreal" },
    { "city": "Toronto" },
    { "city": "Vancouver" }
  ]
};

$('#region_code1').change(function() {
  var region_code1 = $('#region_code1').val();
  var html = ''
  country[region_code1].forEach(function(country) {
    html += '<option>' + country.city + '</option>';
  })
  $('#user_city').empty().html(html);
}).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select>


问:
Restarting a Python Interpreter Quietly
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.

I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.

I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).

So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?

Thanks,

Dan

答:
Try this code from ActiveState recipes: http://code.activestate.com/recipes/572213/

It extends pickle so it supports pickling anything defined in the shell console.  Theoretically you should just be able to pickle the main module, according to their documentation:

```<code>import savestate, pickle, __main__
pickle.dump(__main__, open('savestate.pickle', 'wb'), 2)
</code>```

OwnerDisplayName: Dan

Title: Restarting a Python Interpreter Quietly

LastEditorDisplayName: Benoit

Body:
Try this code from ActiveState recipes: http://code.activestate.com/recipes/572213/

It extends pickle so it supports pickling anything defined in the shell console.  Theoretically you should just be able to pickle the main module, according to their documentation:

import savestate, pickle, __main__
pickle.dump(__main__, open('savestate.pickle', 'wb'), 2)

OwnerDisplayName: Daniel


问:
A vbscript to find windows version name and the service pack
What's the simplest way to find out which version of Windows, and which service pack, is running on a computer with VBScript?

For example I'd want to know Windows XP and Service Pack 3.

答:
An easy way of doing this is to use the WMI class Win32_OperatingSystem which has the properties ServicePackMajorVersion, ServicePackMinorVersion, Name and Version. You can find samples here: WMI Tasks: Operating Systems

The data you get back might not be in the exact format that you want though so you might need to have some kind of lookup table to make it look exactly right.


问:
Unable to connect via JDBC to local SQLExpress
I´ve just installed a SQLEXpress 2016 instance, but I cannot connect to it via a Java based SQL-Client (squirrel). It works fine through SSMS and .net code though.

It timesout

The connection string I´ve tried are:

```<code>jdbc:sqlserver://localhost:1433;databaseName=swdb;instanceName=SQLEXPRESS
jdbc:sqlserver://localhost:1433\SQLEXPRESS;databaseName=swdb;
jdbc:sqlserver://localhost:1433;databaseName=swdb;
</code>```

I am using the sqljdbc42.jar as the driver.

I am able to connect successfully to other SQL instances (though not SQLEXpress)

I´ve already enabled TCP/IP on the SQL Server configuration manager, as well as the local ip, removing dynamic port and setting the 1433 to it.

Am I missing anything?

Thanks

答:
I succeeded with:</p>

```<code>jdbc:sqlserver://localhost:1433;instance=sqlexpress;databaseName=swdb;
</code>```

Body:
I´ve just installed a SQLEXpress 2016 instance, but I cannot connect to it via a Java based SQL-Client (squirrel). It works fine through SSMS and .net code though.

It timesout

The connection string I´ve tried are:

jdbc:sqlserver://localhost:1433;databaseName=swdb;instanceName=SQLEXPRESS
jdbc:sqlserver://localhost:1433\SQLEXPRESS;databaseName=swdb;
jdbc:sqlserver://localhost:1433;databaseName=swdb;

I am using the sqljdbc42.jar as the driver.

I am able to connect successfully to other SQL instances (though not SQLEXpress)

I´ve already enabled TCP/IP on the SQL Server configuration manager, as well as the local ip, removing dynamic port and setting the 1433 to it.

Am I missing anything?

Thanks

Body:
I succeeded with:

jdbc:sqlserver://localhost:1433;instance=sqlexpress;databaseName=swdb;


问:
How can i pull single file (myfile.php) on server?
I make some changes in my locally file with php extension (myfile.php) and i want to pull my file into server. I already use this command :

git commit yourfile.js

but i have an error like this "error: pathspec 'function.php' did not match any file(s) known to git."

I'll be glad for any help. Thanks .

答:
use this command:

```<code>git add myfile.php
git commit -m"your message"
git push origin [branch to push]
</code>```

This is what I understood from your question. Is this what you want to achieve?

Body:
use this command:

git add myfile.php
git commit -m"your message"
git push origin [branch to push]

This is what I understood from your question. Is this what you want to achieve?


问:
Firebase retrieve child via $id in $routeParams
I am trying to use the URL to pass information from my list to detail view. My URL contains the Firebase id. I did manage to retrieve the id, but I can't find how to read the corresponding record in Firebase.

I am having a list of bottles, and when I click on a bottle, I want to display its name.

bouteilles.js

```<code>angular.module('myApp.bouteilles', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/bouteilles', {
    templateUrl: 'bouteilles/bouteilles.html',
    controller: 'BouteillesCtrl'
  });
}])

.controller('BouteillesCtrl', ['$scope','$firebaseArray', function($scope, $firebaseArray) {

  var ref = firebase.database().ref();
  $scope.bouteilles = $firebaseArray(ref);

}]);
</code>```

Then I have a list of "bouteilles" :
bouteilles.html

```<code><div class = "list" ng-repeat="bouteille in bouteilles>
  <a class="item item-avatar" href="#!/maBouteille/{{bouteille.$id}}">
    <h2>{{bouteille.name}} - {{bouteille.year}}</h2>
  </a>
</div>
</code>```

So that I have the bottle id in the URL. It is working OK since I can see in the log the id from maBouteille.js

```<code>angular.module('myApp.maBouteille', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/maBouteille/:id', {
    templateUrl: 'maBouteille/maBouteille.html',
    controller: 'MaBouteilleCtrl'
    });
}])

.controller('MaBouteilleCtrl', ['$routeParams','$scope','$firebaseArray', function($routeParams, $scope, $firebaseArray) {
  var ref = firebase.database().ref();
  console.log($routeParams.id);
}]);
</code>```

I can't figure out how I can use this $routeParams.id to retrieve the corresponding record in Firebase. Any idea?

答:
```<code>.controller('MaBouteilleCtrl', ['$routeParams','$scope','$firebaseArray',     function($routeParams, $scope, $firebaseArray) {
     var ref = firebase.database().ref('your Node or table name'); //that node ref
         ref.child($routeParams.id).on("value",function(snapshots){ //value of that id
         console.log(snapshots.val()); //printing object
      })
  console.log($routeParams.id);
}]);
</code>```

<p>here I am using angular js and firebase. </p>

Body:
I am trying to use the URL to pass information from my list to detail view. My URL contains the Firebase id. I did manage to retrieve the id, but I can't find how to read the corresponding record in Firebase.

I am having a list of bottles, and when I click on a bottle, I want to display its name.

bouteilles.js

angular.module('myApp.bouteilles', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/bouteilles', {
    templateUrl: 'bouteilles/bouteilles.html',
    controller: 'BouteillesCtrl'
  });
}])

.controller('BouteillesCtrl', ['$scope','$firebaseArray', function($scope, $firebaseArray) {

  var ref = firebase.database().ref();
  $scope.bouteilles = $firebaseArray(ref);

}]);

Then I have a list of "bouteilles" :
bouteilles.html

{{bouteille.name}} - {{bouteille.year}}

So that I have the bottle id in the URL. It is working OK since I can see in the log the id from maBouteille.js

angular.module('myApp.maBouteille', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/maBouteille/:id', {
    templateUrl: 'maBouteille/maBouteille.html',
    controller: 'MaBouteilleCtrl'
    });
}])

.controller('MaBouteilleCtrl', ['$routeParams','$scope','$firebaseArray', function($routeParams, $scope, $firebaseArray) {
  var ref = firebase.database().ref();
  console.log($routeParams.id);
}]);

I can't figure out how I can use this $routeParams.id to retrieve the corresponding record in Firebase. Any idea?

Body:
.controller('MaBouteilleCtrl', ['$routeParams','$scope','$firebaseArray',     function($routeParams, $scope, $firebaseArray) {
     var ref = firebase.database().ref('your Node or table name'); //that node ref
         ref.child($routeParams.id).on("value",function(snapshots){ //value of that id
         console.log(snapshots.val()); //printing object
      })
  console.log($routeParams.id);
}]);

here I am using angular js and firebase.


问:
Laravel how to sort multidimensional array
I'd like to sort 4 arrays that are enclosed within 1 array, but I have no clue how to do it.

```<code>    $poster = [];
    $character = [];
    $title = [];
    $date = [];

    foreach($person->getMovieCredits()->getCast() as $movie)
    {
        array_push($poster, $movie->getPosterPath());
        array_push($character, $movie->getCharacter());
        array_push($title, $movie->getTitle());
        array_push($date, $movie->getReleaseDate()->format('Y'));
    }

    $personArray = [
        'date' => $date,
        'title' => $title,
        'character' => $character,
        'poster' => $poster
    ];
</code>```

The thing is that I would like to sort them by date, but not losing data integrity with other arrays.

How should I do that?

答:
You can also play around with the Laravel helpers array_sort() and array_sort_recursive(). Inside the Closure you put a check if the element in the parent array also is an array and also sort the inner array.

https://laravel.com/docs/5.4/helpers

Body:
I'd like to sort 4 arrays that are enclosed within 1 array, but I have no clue how to do it.

    $poster = [];
    $character = [];
    $title = [];
    $date = [];

    foreach($person->getMovieCredits()->getCast() as $movie)
    {
        array_push($poster, $movie->getPosterPath());
        array_push($character, $movie->getCharacter());
        array_push($title, $movie->getTitle());
        array_push($date, $movie->getReleaseDate()->format('Y'));
    }

    $personArray = [
        'date' => $date,
        'title' => $title,
        'character' => $character,
        'poster' => $poster
    ];

The thing is that I would like to sort them by date, but not losing data integrity with other arrays.

How should I do that?


问:
Error Login In My HMVC Code Igniter
i have a problem with my login in application . in my login authentication a create a library name is "auth" and i also was call "auth" in autoload but when i call a function in "auth" the error say

```<code>Message: Undefined property: Auth::$session
</code>```

here is my library "auth"

```<code>class Auth {
    public function cek_auth()
    {
        $this->ci =& get_instance();
        $this->sesi  = $this->ci->session->userdata('isLogin');
        $this->hak = $this->ci->session->userdata('stat');
        if($this->sesi != TRUE){
            $this->session->set_flashdata("pesan", "Sesi Login anda telah habis");
            redirect('user/login');
            exit();
        }

    }
    public function hak_akses($kecuali="")
    {
        if($this->hak==$kecuali){
            echo "<script>alert('Anda tidak berhak mengakses halaman ini!');</script>";
            redirect('dashboard');
        }elseif ($this->hak=="") {
            echo "<script>alert('Silahkan Login!');</script>";
            redirect('c_login','refresh');
        }else{

        }
    }
}
</code>```

my controller :
class Dashboard extends CI_Controller{

```<code>function __construct()
{
    parent::__construct();
    $this->auth->cek_auth(); //ngambil auth dari library
}
function index()
{
    $hak_akses = $this->session->userdata('lvl');
    if($hak_akses==1) {

        $data['content'] = 'dashboard';
        return $this->load->view('theme/index', $data);
    }

}
</code>```

}

and my autoload :

```<code>$autoload['libraries'] = array('database','form_validation','session','auth','parser');
</code>```

please give me a best solution , thanks

答:
Try loading the session library inside</p>

```<code>public function __construct()
{
    $this->ci =& get_instance();
    $this->ci->load->library('session');
    $this->sesi  = $this->ci->session->userdata('isLogin');
}
</code>```

Title: Error Login In My HMVC Code Igniter

Body:
i have a problem with my login in application . in my login authentication a create a library name is "auth" and i also was call "auth" in autoload but when i call a function in "auth" the error say

Message: Undefined property: Auth::$session

here is my library "auth"

class Auth {
    public function cek_auth()
    {
        $this->ci =& get_instance();
        $this->sesi  = $this->ci->session->userdata('isLogin');
        $this->hak = $this->ci->session->userdata('stat');
        if($this->sesi != TRUE){
            $this->session->set_flashdata("pesan", "Sesi Login anda telah habis");
            redirect('user/login');
            exit();
        }

    }
    public function hak_akses($kecuali="")
    {
        if($this->hak==$kecuali){
            echo "";
            redirect('dashboard');
        }elseif ($this->hak=="") {
            echo "";
            redirect('c_login','refresh');
        }else{

        }
    }
}

my controller :
class Dashboard extends CI_Controller{

function __construct()
{
    parent::__construct();
    $this->auth->cek_auth(); //ngambil auth dari library
}
function index()
{
    $hak_akses = $this->session->userdata('lvl');
    if($hak_akses==1) {

        $data['content'] = 'dashboard';
        return $this->load->view('theme/index', $data);
    }

}

}

and my autoload :

$autoload['libraries'] = array('database','form_validation','session','auth','parser');

please give me a best solution , thanks

Body:
Try loading the session library inside

public function __construct()
{
    $this->ci =& get_instance();
    $this->ci->load->library('session');
    $this->sesi  = $this->ci->session->userdata('isLogin');
}


问:
click function after postback
Hello I am working on a simple project using javascript, and I am trying to have a click event fired after the page posts back from the server, and I cant seem to figure out how to do it.  Here is my code below

```<code><asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .SignUp
        {
            padding-right: 450px;
            padding-left: 25px;
            margin-top: 100px;
        }
        .auto-style1
        {
            color: #FFFFFF;
        }
        .auto-style2
        {
            text-align: left;
        }
        .auto-style3
        {
            color: #FFFFFF;
            width: 158px;
        }
        .Message
        {
            margin-left: 100px;
            margin-top: 75px;
        }
        </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <h1>Sign Up for an Account:</h1>
    <div class="SignUp">
        <table class="auto-style1">
            <tr>
                <td class="auto-style3">First Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="FirstName" Class="FirstName" runat="server" style="margin-left: 0px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Firstname" ErrorMessage="Please Enter First Name" ForeColor="Red">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Last Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="LastName" class="LastName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter Last Name" ForeColor="Red" ControlToValidate="LastName">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Password</td>
                <td class="auto-style2">
                    <asp:TextBox ID="Password" class="Password" runat="server" ></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please Create a Password" ForeColor="Red" ControlToValidate="Password">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Confirm Password</td>
                <td class="auto-style2">
                    <asp:TextBox ID="ConfirmPassword" class="ConfirmPassword" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please Confirm Password" ForeColor="Red" ControlToValidate="ConfirmPassword">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Passwords must Match" ForeColor="Red">*</asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Email</td>
                <td class="auto-style2">
                    <asp:TextBox ID="Email" class="Email" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="Email" ErrorMessage="Please enter an Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="Email" ErrorMessage="Please Enter a valid Email" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">ConfirmEmail</td>
                <td class="auto-style2">
                    <asp:TextBox ID="ConfirmEmail" class="ConfirmEmail" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="ConfirmEmail" ErrorMessage="Please confirm Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="Email" ControlToValidate="ConfirmEmail" ErrorMessage="Emails must Match" ForeColor="Red">*</asp:CompareValidator>
                </td>
            </tr>
        </table>
   </div>
    <br />

    <asp:Button ID="CreateAccount" Class="CreateAccount" runat="server" Text="Create Account" OnClick="SignUp_Click" />
    <br />
    <asp:Label  ID="Message" class="Message" runat="server" BackColor="Black" Font-Bold="True" Font-Size="30px" ForeColor="Red" Text="You have successfully created an Account" Height="30px" Visible="false"></asp:Label>
    <br />
    <br />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:portfoliobrownConnectionString2 %>" SelectCommand="SELECT [id], [FirstName], [LastName], [Password], [ConfirmPassword], [ConfirmEmail], [Email] FROM [SignUP]"></asp:SqlDataSource>
    <br />
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />
   <script type="text/javascript">
       $(".CreateAccount").click(function () {
           var first = document.getElementsByClassName("FirstName")
           var last = document.getElementsByClassName("LastName")
           var pass = document.getElementsByClassName("Password")
           var ConPass = document.getElementsByClassName("ConrirmPassword")
           var Email = document.getElementsByClassName("Email")
           var conEmail = document.getElementsByClassName("ConfirmEmail")
               if(first.length > 0 && last.length > 0 && pass.length > 0 && conPass.length > 0 &&
                   Email.length > 0 && conEnail.length > 0)
               {
                    alert("ehb");
               }

           });
</code>```

So basically I want the alert method to fire after the button is clicked on to create the account, but only when the page posts back from the server.

Thanks, any help would be appreciated

答:
You can use RegisterStartupScript for that. Create a javascript function that handles the alert.

```<code><script type="text/javascript">
    function showAlert(msg) {
        alert(msg);
    }
</script>
</code>```

Then call that function from code behind.

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    string message = "Place message here";
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert('" + message + "')", true);
}
</code>```

Title: click function after postback

Body:
Hello I am working on a simple project using javascript, and I am trying to have a click event fired after the page posts back from the server, and I cant seem to figure out how to do it.  Here is my code below

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

Sign Up for an Account:

                First Name

                    <asp:TextBox ID="FirstName" Class="FirstName" runat="server" style="margin-left: 0px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Firstname" ErrorMessage="Please Enter First Name" ForeColor="Red">*</asp:RequiredFieldValidator>

                Last Name

                    <asp:TextBox ID="LastName" class="LastName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter Last Name" ForeColor="Red" ControlToValidate="LastName">*</asp:RequiredFieldValidator>

                Password

                    <asp:TextBox ID="Password" class="Password" runat="server" ></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please Create a Password" ForeColor="Red" ControlToValidate="Password">*</asp:RequiredFieldValidator>

                Confirm Password

                    <asp:TextBox ID="ConfirmPassword" class="ConfirmPassword" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please Confirm Password" ForeColor="Red" ControlToValidate="ConfirmPassword">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Passwords must Match" ForeColor="Red">*</asp:CompareValidator>

                Email

                    <asp:TextBox ID="Email" class="Email" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="Email" ErrorMessage="Please enter an Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="Email" ErrorMessage="Please Enter a valid Email" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>

                ConfirmEmail

                    <asp:TextBox ID="ConfirmEmail" class="ConfirmEmail" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="ConfirmEmail" ErrorMessage="Please confirm Email" ForeColor="Red">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="Email" ControlToValidate="ConfirmEmail" ErrorMessage="Emails must Match" ForeColor="Red">*</asp:CompareValidator>

    <asp:Button ID="CreateAccount" Class="CreateAccount" runat="server" Text="Create Account" OnClick="SignUp_Click" />

    <asp:Label  ID="Message" class="Message" runat="server" BackColor="Black" Font-Bold="True" Font-Size="30px" ForeColor="Red" Text="You have successfully created an Account" Height="30px" Visible="false"></asp:Label>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:portfoliobrownConnectionString2 %>" SelectCommand="SELECT [id], [FirstName], [LastName], [Password], [ConfirmPassword], [ConfirmEmail], [Email] FROM [SignUP]"></asp:SqlDataSource>

    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />

Body:
You can use RegisterStartupScript for that. Create a javascript function that handles the alert.

<script type="text/javascript">
    function showAlert(msg) {
        alert(msg);
    }
</script>

Then call that function from code behind.

protected void Button1_Click(object sender, EventArgs e)
{
    string message = "Place message here";
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert('" + message + "')", true);
}


问:
Functional permissions in Django
Is there a built in way to assign functional permissions to users in Django? From documentations looks like Dajngo permissions are bound to Models.

For example, what I want is to create is 4 types of user groups: Normal users, Managers, Admins and Superadmin.

By default users in different groups will have access to perform different kinds of actions. For example users in Admin group can perform Task1, Task2 and Task3, but users in Managers group can only perform Task1 and Task2(no matter in which app these Tasks are).

Further, user permissions can be modified for a user to revoke access from performing certain task. For example, by default all Admins can perform Task1, Task2 and Task3, but a particular admin's permission can be modified to perform only Task1 and Task3.

Can this be achieved by build in Django permissions and groups or will need to write own permission system(or is there third-party Django app to do this)?

If it will be better to write own permission and group system, any suggestion for design to follow.

Thanks!

答:
You can set the permissions in the admin page like foo.can_write or in your own view like

```<code>myuser.user_permissions.add(permission, permission, ...)
</code>```

In the view you can set the permissions needed for some action. From documentations:

```<code>from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):
</code>```

Title: Functional permissions in Django

Body:
You can set the permissions in the admin page like foo.can_write or in your own view like

myuser.user_permissions.add(permission, permission, ...)

In the view you can set the permissions needed for some action. From documentations:

from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):


问:
Column Show/Hide on Checkbox selection using jquery
I am working on column filter in .NET MVC project. my requirement is, in a dropdown control all table header column name will bind with the checkbox. By default, all option are selected. When I deselect from dropdown any option it reflects to table data and that column will not be shown.

I write some code but not able to implement checkbox functionality. Please help me. If jquery plugin is available that also helpful for me.

JsFiddle DEMO

Code

```<code>$("#myOptions").change(function() {
      selectedVal = $.trim($("#myOptions option:selected").text());
    var i = $("#myTable thead .headercell td:contains(" + selectedVal + ")").index() + 1;
    $('td:nth-child(' + i+ ')').toggle();
    });
</code>```

答:
I think you want to make multi select to easier: use select2:

$("#myOptions").select2({
  tags: true
}).change(function() {
  var test = $("#myOptions").val();
  $("td").show();
  for (var j = 0, len = test.length; j < len; j++) {
    $('td:nth-child(' + test[j] + ')').hide();
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{font-family:calibri;}
  table { padding: 0; border-collapse: collapse; }
  table thead td { background-color: #f2f2f2; font-weight:bold;}
  table td { border: 1px solid #d7d7d7; padding: 5px; }</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

<select id="myOptions" multiple="multiple" style="width:100%">
  <option value="1">Name</option>
  <option value="2">Address</option>
  <option value="3">City</option>
  <option value="4">Country</option>
</select>

      Name
      Address
      City
      Country

      Anand
      2404/71
      Mohali
      India

      Nilesh
      236/10
      Chandigarh
      India

      Rahul
      A 71 Radhepuri
      New Delhi
      India

      Pratius
      Trishna Apartment-740
      Hydrabad
      India

```

Body:
I am working on column filter in .NET MVC project. my requirement is, in a dropdown control all table header column name will bind with the checkbox. By default, all option are selected. When I deselect from dropdown any option it reflects to table data and that column will not be shown.

I write some code but not able to implement checkbox functionality. Please help me. If jquery plugin is available that also helpful for me.

JsFiddle DEMO

Code

$("#myOptions").change(function() {
      selectedVal = $.trim($("#myOptions option:selected").text());
    var i = $("#myTable thead .headercell td:contains(" + selectedVal + ")").index() + 1;
    $('td:nth-child(' + i+ ')').toggle();
    });

Body:
I think you want to make multi select to easier: use select2:

$("#myOptions").select2({
  tags: true
}).change(function() {
  var test = $("#myOptions").val();
  $("td").show();
  for (var j = 0, len = test.length; j < len; j++) {
    $('td:nth-child(' + test[j] + ')').hide();
  }

});

body{font-family:calibri;}
  table { padding: 0; border-collapse: collapse; }
  table thead td { background-color: #f2f2f2; font-weight:bold;}
  table td { border: 1px solid #d7d7d7; padding: 5px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="myOptions" multiple="multiple" style="width:100%">
  <option value="1">Name</option>
  <option value="2">Address</option>
  <option value="3">City</option>
  <option value="4">Country</option>
</select>
<table id="myTable" cellspacing="0" cellpadding="0">
  <thead>
    <tr class="headercell">
      <td>Name</td>
      <td>Address</td>
      <td>City</td>
      <td>Country</td>
    </tr>
  </thead>
  <tbody>
    <tr class="datacell">
      <td>Anand</td>
      <td>2404/71</td>
      <td>Mohali</td>
      <td>India</td>
    </tr>
    <tr class="datacell">
      <td>Nilesh</td>
      <td>236/10</td>
      <td>Chandigarh</td>
      <td>India</td>
    </tr>
    <tr class="datacell">
      <td>Rahul</td>
      <td>A 71 Radhepuri</td>
      <td>New Delhi</td>
      <td>India</td>
    </tr>
    <tr>
      <td>Pratius</td>
      <td>Trishna Apartment-740</td>
      <td>Hydrabad</td>
      <td>India</td>
    </tr>
  </tbody>
  </table>


问:
Foreign Key Constraint Problem
The tables in question are:

enquiry

id

accepted_quote_id

supplier_enquiry

id

enquiry_id

quote

id

enquiry_id

supplier_enquiry_id

The constraints are as follows:

CONSTRAINT supplier_enquiry_ibfk_1 FOREIGN KEY (enquiry_id) REFERENCES enquiry (id) ON DELETE CASCADE

CONSTRAINT quote_ibfk_1 FOREIGN KEY (supplier_enquiry_id) REFERENCES supplier_enquiry (id) ON DELETE CASCADE

CONSTRAINT enquiry_ibfk_9 FOREIGN KEY (accepted_quote_id) REFERENCES quote (id)

So the way I expect this to work is:

If you delete an 'enquiry' it deletes the child 'supplier_enquiry' records

If you delete a 'supplier_enquiry' it deletes the child 'quote' records

You cannnot delete a 'quote' if an 'enquiry' references that quote's ID

The problem I'm having is when deleting an 'enquiry' record. Because it needs to delete the child records first, i.e. 'supplier_enquiry' and 'quote', if 'accepted_quote_id' references a 'quote' then the 'enquiry' can't be deleted.

Any idea how I can overcome this issue?

答: Update the reference to NULL before deleting.</p>

Title: Foreign Key Constraint Problem


问:
How to pass value to another activity with id of the option clicked from dialog box
I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.

if this is possible then how? Thanks in advance for your help.

```<code>holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
    holder.textViewName.setText(category.getName());
    category_id = category.getId();
    language_id = category.getLanguage_id();
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            handleLanguageDialog();

            }

    });

}

private AlertDialog handleLanguageDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Select Language")
            .setItems(R.array.lang, new DialogInterface.OnClickListener()                 {
                public void onClick(DialogInterface dialog, int which) {
                    // The 'which' argument contains the index position
                    // of the selected item
                    switch(which)
                    {
                        case 0:// English

                            break;
                        case 1://Bengali

                            break;
                    }
                }
            });
    return builder.create().show();
}
</code>```

categ.java

```<code>    private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;

@Override
public String toString() {
    return "Categ{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", description='" + description + '\'' +
            ", image='" + image + '\'' +
            ", parent_id='" + parent_id + '\'' +
            ", language_id='" + language_id + '\'' +
            ", created='" + created + '\'' +
            ", modified='" + modified + '\'' +
            '}';
}

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}
public String getParent_id() {
    return parent_id;
}
public void setParent_id(String parent_id) {
    this.parent_id = parent_id;
}
public String getLanguage_id() {
    return language_id;
}
public void setLanguage_id(String language_id) {
    this.language_id = language_id;
}
public String getCreated() {
    return created;
}
public void setCreated(String created) {
    this.created = created;
}
public String getModified() {
    return modified;
}
public void setModified(String modified) {
    this.modified = modified;
}
</code>```

}

答:
In your first activity pass data like this

```<code>Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("CATEGORY_ID", category_id);
intent.putExtra("LANGUAGE_ID", language_id);
startActivity(intent);
</code>```

Now in your next activity recieve data like this

```<code>String cat_id = getIntent().getExtras().getString("CATEGORY_ID");
String cat_id = getIntent().getExtras().getString("LANGUAGE_ID");
</code>```

Body:
I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.

if this is possible then how? Thanks in advance for your help.

holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
    holder.textViewName.setText(category.getName());
    category_id = category.getId();
    language_id = category.getLanguage_id();
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            handleLanguageDialog();

            }

    });

}

private AlertDialog handleLanguageDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Select Language")
            .setItems(R.array.lang, new DialogInterface.OnClickListener()                 {
                public void onClick(DialogInterface dialog, int which) {
                    // The 'which' argument contains the index position
                    // of the selected item
                    switch(which)
                    {
                        case 0:// English

                            break;
                        case 1://Bengali

                            break;
                    }
                }
            });
    return builder.create().show();
}

categ.java

    private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;

@Override
public String toString() {
    return "Categ{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", description='" + description + '\'' +
            ", image='" + image + '\'' +
            ", parent_id='" + parent_id + '\'' +
            ", language_id='" + language_id + '\'' +
            ", created='" + created + '\'' +
            ", modified='" + modified + '\'' +
            '}';
}

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}
public String getParent_id() {
    return parent_id;
}
public void setParent_id(String parent_id) {
    this.parent_id = parent_id;
}
public String getLanguage_id() {
    return language_id;
}
public void setLanguage_id(String language_id) {
    this.language_id = language_id;
}
public String getCreated() {
    return created;
}
public void setCreated(String created) {
    this.created = created;
}
public String getModified() {
    return modified;
}
public void setModified(String modified) {
    this.modified = modified;
}

}

Body:
In your first activity pass data like this

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("CATEGORY_ID", category_id);
intent.putExtra("LANGUAGE_ID", language_id);
startActivity(intent);

Now in your next activity recieve data like this

String cat_id = getIntent().getExtras().getString("CATEGORY_ID");
String cat_id = getIntent().getExtras().getString("LANGUAGE_ID");


问:
How to enter special characters like "&" in oracle database?
I want to insert special character & in my insert statement. My insert is:

```<code>INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
</code>```

If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.

How can I enter special characters like & in the insert statement for oracle db?

答:
There are 3 ways to do so :

1) Simply do SET DEFINE OFF; and then execute the insert stmt.

2) Simply by concatenating reserved word within single quotes and concatenating it.
E.g. Select 'Java_22 ' || '& '|| ':' || ' Oracle_14' from dual --(:) is an optional.

3) By using CHR function along with concatenation.
E.g. Select 'Java_22 ' || chr(38)||' Oracle_14' from dual

Hope this help !!!

Body:
I want to insert special character & in my insert statement. My insert is:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');

If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.

How can I enter special characters like & in the insert statement for oracle db?


问:
How to Recovering mysql database from data folder backup from uninstalled xamp to newly installed xamp
I have uninstalled the old XAMPP and deleted all of the content of d:\xampp folder and installed the new one. When I copy my backup folder (with the name of my database, containing all .frm and .opt files) to the D:\xampp\mysql\data, the database shows in the list in phpmyadmin but it has no tables and data. What I've done wrong?

tables are show in the database but while clicking on table its saying file doesn't exist..

答:
When you restore old mysql\data\ to new installed xamp, your newly installed xamp version must be same as old xamp version.

Then only restore data will work. its worked on my xamp


问:
How to custom change the date format in excel from any format to dd-MM-yyyy
I need to change date from existing format to dd-MM-yyyy in excel .

EDIT : I have seen other formats , but they don't contain - dd-MM-yyyy format .

答:
click on the cell then click ctrl+1
choose date then choose the format from type list</p>


问:
How can I remove every listener from a page?
I know how to remove a listener from an element, but how can I remove every event listener from every element on the page?

A jQuery and pure JS solution would be nice.

答:
You can try this too.

http://jsfiddle.net/LkfLezgd/9/

```<code>$("#cloneButton").click(function() {
$('body').replaceWith($('body').clone().html());
});
</code>```

Body:
You can try this too.

http://jsfiddle.net/LkfLezgd/9/

$("#cloneButton").click(function() {
$('body').replaceWith($('body').clone().html());
});


问:
Detect full word match only from dictionary
I'm trying to detect city names from dictionaries But if there is any word without spaces it's also get detected.
For example:

Dictionary Start

New York
..

Dictionary End

Input Start

New York

NewYork

Input End

What i want to anotate New York as City not NewYork

I'm using below rule.

```<code>WORDLIST USCitiesList = 'en/ruta/dictionaries/USCities.txt';
DocumentAnnotation{-> MARKFAST(USCity, USCitiesList,true)};
</code>```

答:
The below script will help you.

```<code>PACKAGE uima.ruta.example;
DECLARE USCity;
DECLARE NoSpaceUSCity;
WORDLIST USCitiesList = 'USCities.txt';

DocumentAnnotation{-> MARKFAST(USCity, USCitiesList,true)};

RETAINTYPE(SPACE);
DocumentAnnotation{-> MARKFAST(NoSpaceUSCity, USCitiesList,true)};
RETAINTYPE;

USCity{PARTOF(NoSpaceUSCity)->UNMARK(USCity)};
</code>```

Body:
I'm trying to detect city names from dictionaries But if there is any word without spaces it's also get detected.
For example:

Dictionary Start

New York
..

Dictionary End

Input Start

New York

NewYork

Input End

What i want to anotate New York as City not NewYork

I'm using below rule.

WORDLIST USCitiesList = 'en/ruta/dictionaries/USCities.txt';
DocumentAnnotation{-> MARKFAST(USCity, USCitiesList,true)};

Body:
The below script will help you.

PACKAGE uima.ruta.example;
DECLARE USCity;
DECLARE NoSpaceUSCity;
WORDLIST USCitiesList = 'USCities.txt';

DocumentAnnotation{-> MARKFAST(USCity, USCitiesList,true)};

RETAINTYPE(SPACE);
DocumentAnnotation{-> MARKFAST(NoSpaceUSCity, USCitiesList,true)};
RETAINTYPE;

USCity{PARTOF(NoSpaceUSCity)->UNMARK(USCity)};


问:
CSS Media Queries not working in Firefox and Chrome
One of my clients has a site with a responsive design (three based on ranges) with so many graphics they do have to reduce them for each range. We don't detect by device or anything silly though I do need to define with CSS profiles that I can later read with JavaScript as there are things we have to go out of our way and style with both JavaScript/CSS though because the background-image moves based on the "profile" the calculations have to be based off of which media query is in effect.

Unfortunately both Firefox and Chrome are acting a bit wonky when it comes to which profile is "active". The client considers 640 pixels or less to be a "phone" device, 641 ~ 991 a "tablet" device and 992 pixels and greater to be a "desktop" device. I've managed to improve a few things though I haven't figured out why "tablet" isn't working on Firefox and why both "phone" and "tablet" don't work on Chrome?

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Device Profiles</title>
<style type="text/css">
@media (min-width: 0) and (max-width: 640px) {
    h1::before {content: 'Phone ';}
}
@media (min-width: 641px) and (min-width: 991px) {
    h1::before {content: 'Tablet ';}
}
@media (min-width: 992px) {
    h1::before {content: 'Desktop ';}
}
</style>
</head>

<body>

<h1>Profile</h1>

</body>
</html>
</code>```

答:
```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Device Profiles</title>
<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
@media (min-width: 0) and (max-width: 640px) {
    h1::before {content: 'Phone ';}
}
@media (min-width: 641px) and (max-width: 991px) {
    h1::before {content: 'Tablet ';}
}
@media (min-width: 992px) {
    h1::before {content: 'Desktop ';}
}
</style>
</head>

<body>

<h1>Profile</h1>

</body>
</html>
</code>```

Body:
One of my clients has a site with a responsive design (three based on ranges) with so many graphics they do have to reduce them for each range. We don't detect by device or anything silly though I do need to define with CSS profiles that I can later read with JavaScript as there are things we have to go out of our way and style with both JavaScript/CSS though because the background-image moves based on the "profile" the calculations have to be based off of which media query is in effect.

Unfortunately both Firefox and Chrome are acting a bit wonky when it comes to which profile is "active". The client considers 640 pixels or less to be a "phone" device, 641 ~ 991 a "tablet" device and 992 pixels and greater to be a "desktop" device. I've managed to improve a few things though I haven't figured out why "tablet" isn't working on Firefox and why both "phone" and "tablet" don't work on Chrome?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

<title>Device Profiles</title>

Profile


问:
How to dynamically import `import x.y.z as z`in python
To do

```<code>import itertools
</code>```

dynamically, I can do the following

```<code>import importlib
importlib.import_module('itertools')
</code>```

But what should I do to do the following dynamically

```<code>import itertools as iters
</code>```

Problem Context:

I need to import a different version (0.10) of a module('pika' in my case), installed in a separate directory instead of default version(0.9).

```<code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python !!
>>> import importlib
>>> import pika
>>> pika.__version__
'0.9.14'
>>> import scale.lib.hypervisor.esx65.pika_3_5 as pika35
>>> pika35.__version__
'0.10.0'
>>> importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5')
<module 'scale.lib.hypervisor.esx65.pika_3_5' from 'scale/lib/hypervisor/esx65/pika_3_5/__init__.pyc'>
</code>```

As we can see regular imports are working fine. However when importing dynamically, importing relative to the location is causing issues. As per importlib.import_module documentaion , following should work but it doesn't.

```<code>>>> importlib.import_module('pika_3_5', 'scale.lib.hypervisor.esx65')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named pika_3_5
</code>```

And when trying to import 'pika' from a relative path, which should fail as there is no module pika under the relative path, it is still importing it from default module.

```<code>>>> importlib.import_module('pika', 'scale.lib.hypervisor.esx65.pika_3_5')
<module 'pika' from '/usr/local/lib/python2.7/dist-packages/pika/__init__.pyc'>
>>>
</code>```

What is it that I am missing ? I mainly want to do the following dynamically.

```<code>import scale.lib.hypervisor.esx65.pika_3_5 as pika
</code>```

答:
To do

```<code>import itertools
</code>```

dynamically, I can do the following

```<code>import importlib
importlib.import_module('itertools')
</code>```

No, you do the following:

```<code>import importlib
itertools = importlib.import_module('itertools')
</code>```

Similarly, to replicate import itertools as iters, you do

```<code>import importlib
iters = importlib.import_module('itertools')
</code>```

importlib.import_module doesn't care what you call the module. as is not and cannot be part of importlib.import_module's functionality. It just gives you the module object; what you call that object is up to you.

As for your context, you've misunderstood what a relative import is. The second argument to importlib.import_module has nothing to do with from imports, and importlib.import_module('thing', 'whatever') is not supposed to be equivalent to from whatever import thing.

If you want to do

```<code>import scale.lib.hypervisor.esx65.pika_3_5 as pika
</code>```

that's pika = importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5'). The second argument doesn't enter the picture. You seem to think this is somehow not dynamic, but it's as dynamic as any other importlib call.

Body:
To do

import itertools

dynamically, I can do the following

import importlib
importlib.import_module('itertools')

But what should I do to do the following dynamically

import itertools as iters

Problem Context:

I need to import a different version (0.10) of a module('pika' in my case), installed in a separate directory instead of default version(0.9).

Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python !!
>>> import importlib
>>> import pika
>>> pika.__version__
'0.9.14'
>>> import scale.lib.hypervisor.esx65.pika_3_5 as pika35
>>> pika35.__version__
'0.10.0'
>>> importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5')
<module 'scale.lib.hypervisor.esx65.pika_3_5' from 'scale/lib/hypervisor/esx65/pika_3_5/__init__.pyc'>

As we can see regular imports are working fine. However when importing dynamically, importing relative to the location is causing issues. As per importlib.import_module documentaion , following should work but it doesn't.

>>> importlib.import_module('pika_3_5', 'scale.lib.hypervisor.esx65')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named pika_3_5

And when trying to import 'pika' from a relative path, which should fail as there is no module pika under the relative path, it is still importing it from default module.

>>> importlib.import_module('pika', 'scale.lib.hypervisor.esx65.pika_3_5')
<module 'pika' from '/usr/local/lib/python2.7/dist-packages/pika/__init__.pyc'>
>>>

What is it that I am missing ? I mainly want to do the following dynamically.

import scale.lib.hypervisor.esx65.pika_3_5 as pika

Body:
To do

import itertools

dynamically, I can do the following

import importlib
importlib.import_module('itertools')

No, you do the following:

import importlib
itertools = importlib.import_module('itertools')

Similarly, to replicate import itertools as iters, you do

import importlib
iters = importlib.import_module('itertools')

importlib.import_module doesn't care what you call the module. as is not and cannot be part of importlib.import_module's functionality. It just gives you the module object; what you call that object is up to you.

As for your context, you've misunderstood what a relative import is. The second argument to importlib.import_module has nothing to do with from imports, and importlib.import_module('thing', 'whatever') is not supposed to be equivalent to from whatever import thing.

If you want to do

import scale.lib.hypervisor.esx65.pika_3_5 as pika

that's pika = importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5'). The second argument doesn't enter the picture. You seem to think this is somehow not dynamic, but it's as dynamic as any other importlib call.