问:
Unsupported major.minor version 52.0 error while compiling and running in JDK 1.7
There's nothing much to say except that this error appears even after uninstalling JDK 8

Prologue:

I got the same error in my server, and I've looked it up, and it says version 52 error is because the compilation is done in different java version and you are executing this in another server (52 indicating : You need to use java 8)

So the solutions I found out from SO is

Run the program in java 8 (Cannot do because it's a corporate server running on java 7)

Compile the program in java 7 ( Did it, changed the environment variables to java 8, tomcat still points to java 7)

People said you need to uninstall a java because there should not be two jdk existing in 1 system

So since I cannot do anything in server, I did the following things in my localhost
 1. Uninstalled jdk 8, installed jdk 7
 2. Changed env variables to 7
 3. now tomcat server shows JVM to be java 7
 4. Recompiled in java 7
 5. When I execute this, it says the unsupported major.minor version 52

These are my settings

And when I start tomcat from XAMPP

Nothing is related to Java 8 and yet I get this error, Is this because JAVA 7 is old?

As suggested from the comments, here is the error file

And the console response

答: I had faced the same issue in gradle build after that i have removed my all java versions(1.7 and 1.8) and then reinstalled 1.7 version and gradle build was working fine.</p>


来源: stackexchange

问:
I'm new with angular.js, I just try to create a login form using angular.js

All working find when I try to login first time, but second time after logout submit button not working.

Can We do this code shorter and better way using anguler.js Please help

HTML

```<code><div ng-app="app">

    <div ng-controller="HttpGetController">
        <div ng-hide ="logedin">
            <p>User: <input type="text" name="firstName" ng-model="firstName" required /></p>
            <p>Password: <input type="text" name="lastName" ng-model="lastName" required /></p>
            <button ng-click="SendData()">Submit</button>
        </div>
        <div class="userDetail" ng-hide="userDetail">
                {{message.result[0].FIRST_NAME + " " + message.result[0].LAST_NAME}}
                <div class="logout"><a href="#" title="title" ng-click='logout()'>Logout</a></div>
        </div>
        </div>
</div>
</code>```

Javascript (angular)

```<code>var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
    $scope.userDetail = true;
    if(!localStorage.getItem('logedin')){
        $scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.example.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };
    } else {
        $scope.logedin = true;
        $scope.message = JSON.parse(localStorage.getItem('logedin'));
        $scope.userDetail = false;
    }
    $scope.logout = function(){
        window.localStorage.removeItem('logedin');
        $scope.logedin = false;
        $scope.userDetail = true;
    }
});
</code>```

答:
From what I can see your function might not be defined when controller is initialized in case of a refresh after login

```<code>$scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.bhugtankaro.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };
</code>```

Have this function definition outside the if condition

```<code>if(!localStorage.getItem('logedin')){
}
</code>```

And then you can have if condition inside the function defintion otherwise after login if you refresh the function will not initialized.

ContentLicense: CC BY-SA 3.0

Body:
All working find when I try to login first time, but second time after logout submit button not working.

Can We do this code shorter and better way using anguler.js Please help

HTML

User: <input type="text" name="firstName" ng-model="firstName" required />

Password: <input type="text" name="lastName" ng-model="lastName" required />

            <button ng-click="SendData()">Submit</button>

                {{message.result[0].FIRST_NAME + " " + message.result[0].LAST_NAME}}

Logout

Javascript (angular)

var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
    $scope.userDetail = true;
    if(!localStorage.getItem('logedin')){
        $scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.example.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };
    } else {
        $scope.logedin = true;
        $scope.message = JSON.parse(localStorage.getItem('logedin'));
        $scope.userDetail = false;
    }
    $scope.logout = function(){
        window.localStorage.removeItem('logedin');
        $scope.logedin = false;
        $scope.userDetail = true;
    }
});

Body:
From what I can see your function might not be defined when controller is initialized in case of a refresh after login

$scope.SendData = function () {
            var creds = 'username=' + $scope.firstName + '&password=' + $scope.lastName;
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var res = $http.post('http://api.bhugtankaro.com/beta/login.php', creds, config);
            res.success(function(data, status, headers, config) {
                if(data.success){
                    $scope.logedin = true;
                    $scope.message = data;
                    localStorage.setItem("logedin", angular.toJson(data));
                    $scope.userDetail = false;
                } else {
                    alert(data.description);
                }
            });
        };

Have this function definition outside the if condition

if(!localStorage.getItem('logedin')){
}

And then you can have if condition inside the function defintion otherwise after login if you refresh the function will not initialized.


问:
Input validation to only accept numbers
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

```<code>#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}
</code>```

Here's the error im receiving

答:
do while syntax should be like this:

```<code>do{

}while(x == 0);
</code>```

How you did it is like this:

```<code>do{

}while();
{ <--- //this

} <--- //and this
</code>```

Try removing those two parentheses {}. They are not necessary.

Title: Input validation to only accept numbers

Body:
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}

Here's the error im receiving

Body:
do while syntax should be like this:

do{

}while(x == 0);

How you did it is like this:

do{

}while();
{ <--- //this

} <--- //and this

Try removing those two parentheses {}. They are not necessary.


问:
set value from pickerview to textfield without declaring the textfield globally swift programatically
I am building the UI textfields dynamically using the schema, I have many textfields that require UIPickerView(). I am using the UIPickerViewDelegate and overriding its method to set the selected value to the textfields.
 but the problem is I have many textfields generated dynamically at the runtime, I don't want them to be declared globally or in class scope

How can can I set the value selected in picker to the textfield without globally declaring textfield

答:
When you generate the textfields, assign a unique tag to each of them. I assume you are already using a loop to do this, so getting a unique number should not be too hard:

```<code>for i in 0..<someNumber {
    // ...
    textField.tag = i
}
</code>```

To get a specific text field, you just do

```<code>view.viewByTag(someNumber) as! UITextField
</code>```

where view is the superview of the text field.

Body:
When you generate the textfields, assign a unique tag to each of them. I assume you are already using a loop to do this, so getting a unique number should not be too hard:

for i in 0..<someNumber {
    // ...
    textField.tag = i
}

To get a specific text field, you just do

view.viewByTag(someNumber) as! UITextField

where view is the superview of the text field.


问:
PyQt5 + QtWebEngine get html element?
everyone! I want port my project from Qt WebKit to Qt WebEngine! Currently I want to get the html elemnt.

I use PyQt5 + QT 5.8.

My get elment func:

```<code>def get_elment(self,selector,func):
    js = '''
        function r()
        {
            var button = document.querySelector("%s");
            return button;
        }
        r();
    '''%selector
    self.wp.runJavaScript(js,func)
</code>```

I use it :

```<code>def print_element(e):
    print "e:%s"%e
browser.get_elment('#u1 > a:nth-child(1)',print_element)
</code>```

I hope e should be a html element, but it is a dict.
the result:

I search on the web, but could not find the solution. Can anyone help me ? Thanks very much!

答:
Thanks for @ekhumoro.

There is no equivalent to QWebElement in Qt WebEngine. All DOM manipulations must be done in Javascript.

Title: PyQt5 + QtWebEngine get html element?

Body:
everyone! I want port my project from Qt WebKit to Qt WebEngine! Currently I want to get the html elemnt.

I use PyQt5 + QT 5.8.

My get elment func:

def get_elment(self,selector,func):
    js = '''
        function r()
        {
            var button = document.querySelector("%s");
            return button;
        }
        r();
    '''%selector
    self.wp.runJavaScript(js,func)

I use it :

def print_element(e):
    print "e:%s"%e
browser.get_elment('#u1 > a:nth-child(1)',print_element)

I hope e should be a html element, but it is a dict.
the result:

I search on the web, but could not find the solution. Can anyone help me ? Thanks very much!


问:
How can I know the line number of editfield of blackberry
I would like to know the line number in EditField while I am typing some text in this component.</p>

答:
Get the width of the edit field. (int returned) (e.g. 320 px)

Get the font width of your current text. Font class have getAdvance() method that accepts the string parameter (int returned) (e.g. 650 px)

if string width > edit field width you can divide string width and edit width and on the other step get the modulo of it. (here you will get 2 as division and 10 will be yr modulo. That means you have filled two lines + in third line you are having characters that can be fit into 10 px.

I hope it will solve your problem, but be careful if you use any long words, the module had never been tested with long words but I fear about result's accuracy with long words.

ContentLicense: CC BY-SA 2.5


问:
Why does this *ptr NOT give the actual value stored at the memory address contained in ptr variable?
Here is a basic C program about pointers:

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

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}
</code>```

This produces the following output:

```<code>Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14
</code>```

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

答:
Your  formatting is hex (base 16) (%x) this line :

 printf("Address of variable: %x\n", *pointerToVariable);// output: 14

If you want the output in base 10, then you need to provide the right formatting :

```<code> printf("Address of variable: %d\n", *pointerToVariable); // output : 20

// 1*16 + 4 = 20
</code>```

Good luck

Body:
Here is a basic C program about pointers:

#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}

This produces the following output:

Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

Body:
Your  formatting is hex (base 16) (%x) this line :

 printf("Address of variable: %x\n", *pointerToVariable);// output: 14

If you want the output in base 10, then you need to provide the right formatting :

 printf("Address of variable: %d\n", *pointerToVariable); // output : 20

// 1*16 + 4 = 20

Good luck


问:
having trouble with mysql code keep getting error 1064
here is the code i have, i get an error with the SELECT *FROM judge;</p>

```<code>CREATE VIEW judge_vw AS(

  SELECT *FROM judge;
  WHERE suburb='adelaide';
  order by 'judge_id';`enter code here`
  with check option;

insert into judge_vw values(',judge_id 6','schofield','adelaide,')

update judge_vw set name='russell'where names='jones'

delete from judge_vw where judge_id=7;

drop view if exists judge_vw
);
</code>```

答:
your sintax is wrong  leave just the last ; at the end of command and remove all the others
don't use quote for column name (eg:  judge_id), remve unuseful ( and  with chcek </p>

```<code>CREATE VIEW judge_vw AS
SELECT * FROM judge
WHERE suburb='adelaide'
ORDER BY judge_id;
</code>```

<p>you insert seems contain wrong comma </p>

```<code>insert into judge_vw values('judge_id 6','schofield','adelaide');
</code>```

Body:
here is the code i have, i get an error with the SELECT *FROM judge;

CREATE VIEW judge_vw AS(

  SELECT *FROM judge;
  WHERE suburb='adelaide';
  order by 'judge_id';`enter code here`
  with check option;

insert into judge_vw values(',judge_id 6','schofield','adelaide,')

update judge_vw set name='russell'where names='jones'

delete from judge_vw where judge_id=7;

drop view if exists judge_vw
);

Body:
your sintax is wrong  leave just the last ; at the end of command and remove all the others
don't use quote for column name (eg:  judge_id), remve unuseful ( and  with chcek

CREATE VIEW judge_vw AS
SELECT * FROM judge
WHERE suburb='adelaide'
ORDER BY judge_id;

you insert seems contain wrong comma

insert into judge_vw values('judge_id 6','schofield','adelaide');


问:
Rails change ActiveJob adapter for a single job
I have some scheduled tasks that run jobs with a real queue service.

Now, I want to be able to run those tasks manually from a dashboard, wait for its execution, and read/process some of its outputs in a controller action. The typical case being when an admin wants to manually reload some statistics, and it's fine to stall the server for a couple secs.

Is there a way to change the ActiveJob adapter to "inline" in order to do that ? If possible I'd also like to read some artifacts generated by this job (could be instance variables, or the return value of the performaction).

Any way to do that ?

Sample Job

```<code>class TopLevelJob < ApplicationJob
  def perform
    some_iterator.each do
      SomeNestedJob.rand.perform_later
      # There are several types of sub-jobs that can be called
      # Passing a flag param (perform vs perform_later) would be kind of annoying
    end
end

module SomeNestedJob
  class A < ApplicationJob;
    def perform
       # May in turn spawn an other job with perform_later
    end
  end
  ...
  class Z < ApplicationJob; ...; end

  def self.rand
    [A..Z].sample
  end
end
</code>```

答:
I believe  "perform_now" is what you're looking for ... runs the task right away, without going in queue.

cf. ActiveJob on http://edgeapi.rubyonrails.org/classes/ActiveJob/Base.html

Other than that, really, just make your "perform" have a flag ("has_whatever_output_you_have_in_mind") and use it in your perform action to trigger an output.

Body:
I have some scheduled tasks that run jobs with a real queue service.

Now, I want to be able to run those tasks manually from a dashboard, wait for its execution, and read/process some of its outputs in a controller action. The typical case being when an admin wants to manually reload some statistics, and it's fine to stall the server for a couple secs.

Is there a way to change the ActiveJob adapter to "inline" in order to do that ? If possible I'd also like to read some artifacts generated by this job (could be instance variables, or the return value of the performaction).

Any way to do that ?

Sample Job

class TopLevelJob < ApplicationJob
  def perform
    some_iterator.each do
      SomeNestedJob.rand.perform_later
      # There are several types of sub-jobs that can be called
      # Passing a flag param (perform vs perform_later) would be kind of annoying
    end
end

module SomeNestedJob
  class A < ApplicationJob;
    def perform
       # May in turn spawn an other job with perform_later
    end
  end
  ...
  class Z < ApplicationJob; ...; end

  def self.rand
    [A..Z].sample
  end
end


问:
How to run Application with SQL Database on a machine that dosen't have SQL Server Installed
I have developed an application that have a slider that showing some data from a
SQL Database. I'm using Visual Studio 2010 and Microsoft SQL Server 2008.

In fact i don't face any problem with my application when i deploy it an run it on my Personal Computer.
The problem occurs when i try it on another machine, and the problem is that the application couldn't be connected the SQL database. I tried to figure out the reason of the problem, so i tried it after its deployment on two machines, one of them have a SQL server installed on it, and the other one don't have the SQL Server.
The Application worked perfectly on the machine that have the SQL Server installed on it, and it couldn't be connected to the database on the other machine.

This is the Connection String i have used in my application>>

connectionString="Data
  Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\KBank.mdf;Integrated
  Security=True;User Instance=True"

so if there is a way that could enable me to run the application without needing the machine to have a SQL Server installed, i would be grateful. Thanks

答:
If you using centerl database install in Server computer and other all client computer can access to that sever.

If it's you can doing the following way:

first you change your program to write File DSN to Hard disk at start up of program

Use the following code as sample

```<code> private void MakeDSN()
        {
            try
            {
                if (!System.IO.Directory.Exists(@"C:\OTPub"))
                {
                    System.IO.Directory.CreateDirectory(@"C:\OTPub");
                }

                if (File.Exists(@"C:\OTPub\Ot.dsn"))    //delete ErrorLogFile
                {
                    File.SetAttributes(@"C:\OTPub\Ot.dsn", FileAttributes.Temporary);
                    File.Delete(@"C:\OTPub\Ot.dsn");
                }
                string con = "[ODBC]";
                string driver = "DRIVER=SQL Server";
                string uid = "UID=sa";
                string DB = "DATABASE=OTData";
                string server = "SERVER=10.63.210.111";

                var tw = new StreamWriter(@"C:\OTPub\Ot.dsn", true); // make file in location
                using (tw)
                {
                    tw.WriteLine(con);   //write  dataline
                    tw.WriteLine(driver);
                    tw.WriteLine(uid);
                    tw.WriteLine(DB);
                    tw.WriteLine(server);
                }

                lbserver.Text="LOGIN "+server;
            }
            catch (Exception)
            {
                MessageBox.Show("File DSN Error!");
            }
        }
</code>```

Enter your server Ip as  string server

Now you can use connection in separate class

```<code>using System.Data.Odbc;

  class DataBaseConnection
    {
        private OdbcConnection conn1 = new OdbcConnection(@"FILEDSN=C:/OTPub/Ot.dsn;" + "Uid=sa;" + "Pwd=123;");

        //insert,update,delete
        public int SetData(string query)
        {
            try
           {
                conn1.Open();
                OdbcCommand command = new OdbcCommand(query, conn1);
                int rs = command.ExecuteNonQuery();
                conn1.Close();
                return rs;
            }
            catch (Exception ex)
            {
                conn1.Close();
                throw ex;
            }
        }

        //select
        public System.Data.DataTable GetData(string sql)
        {
            try
            {
                conn1.Open();
                OdbcDataAdapter adpt = new OdbcDataAdapter(sql, conn1);
                DataTable dt = new DataTable();
                adpt.Fill(dt);
                conn1.Close();
                return dt;
            }
            catch (Exception ex)
            {
                conn1.Close();
                throw ex;
            }
        }
    }
</code>```

Now you can write following code your different required place for connect to database,

```<code> DataBaseConnection db = new DataBaseConnection();
</code>```

If you need SELECT query:

```<code>DataTable dt = db.GetData("SELECT * From TestTable");
</code>```

If you need Insert, Update, Delete query

```<code>int i=db.SetData("INSERT INTO TestTable(name,address,tel) VALUES (testname,Colombo,0777125896) ");
</code>```

This method can use connect to database without any configurations.

Important: keep remember delete DSN file when exit application for security purpose.

Hope this will help you!

Body:
If you using centerl database install in Server computer and other all client computer can access to that sever.

If it's you can doing the following way:

first you change your program to write File DSN to Hard disk at start up of program

Use the following code as sample

 private void MakeDSN()
        {
            try
            {
                if (!System.IO.Directory.Exists(@"C:\OTPub"))
                {
                    System.IO.Directory.CreateDirectory(@"C:\OTPub");
                }

                if (File.Exists(@"C:\OTPub\Ot.dsn"))    //delete ErrorLogFile
                {
                    File.SetAttributes(@"C:\OTPub\Ot.dsn", FileAttributes.Temporary);
                    File.Delete(@"C:\OTPub\Ot.dsn");
                }
                string con = "[ODBC]";
                string driver = "DRIVER=SQL Server";
                string uid = "UID=sa";
                string DB = "DATABASE=OTData";
                string server = "SERVER=10.63.210.111";

                var tw = new StreamWriter(@"C:\OTPub\Ot.dsn", true); // make file in location
                using (tw)
                {
                    tw.WriteLine(con);   //write  dataline
                    tw.WriteLine(driver);
                    tw.WriteLine(uid);
                    tw.WriteLine(DB);
                    tw.WriteLine(server);
                }

                lbserver.Text="LOGIN "+server;
            }
            catch (Exception)
            {
                MessageBox.Show("File DSN Error!");
            }
        }

Enter your server Ip as  string server

Now you can use connection in separate class

using System.Data.Odbc;

  class DataBaseConnection
    {
        private OdbcConnection conn1 = new OdbcConnection(@"FILEDSN=C:/OTPub/Ot.dsn;" + "Uid=sa;" + "Pwd=123;");

        //insert,update,delete
        public int SetData(string query)
        {
            try
           {
                conn1.Open();
                OdbcCommand command = new OdbcCommand(query, conn1);
                int rs = command.ExecuteNonQuery();
                conn1.Close();
                return rs;
            }
            catch (Exception ex)
            {
                conn1.Close();
                throw ex;
            }
        }

        //select
        public System.Data.DataTable GetData(string sql)
        {
            try
            {
                conn1.Open();
                OdbcDataAdapter adpt = new OdbcDataAdapter(sql, conn1);
                DataTable dt = new DataTable();
                adpt.Fill(dt);
                conn1.Close();
                return dt;
            }
            catch (Exception ex)
            {
                conn1.Close();
                throw ex;
            }
        }
    }

Now you can write following code your different required place for connect to database,

 DataBaseConnection db = new DataBaseConnection();

If you need SELECT query:

DataTable dt = db.GetData("SELECT * From TestTable");

If you need Insert, Update, Delete query

int i=db.SetData("INSERT INTO TestTable(name,address,tel) VALUES (testname,Colombo,0777125896) ");

This method can use connect to database without any configurations.

Important: keep remember delete DSN file when exit application for security purpose.

Hope this will help you!


问:
Steps to develop a multilingual web application
What are the steps to develop a multilingual web application?

Should i store the languages texts and resources in database or should i use property files or resource files?

I understand that I need to use CurrentCulture with C# alone with CultureFormat etc.

I wanted to know you opinions on steps to build a multilingual web application.

Doesn't have to be language specific. I'm just looking for steps to build this.

答: The first step is to internationalize. The second step is to localize. The third step is to translate.</p>

ContentLicense: CC BY-SA 4.0


问:
Right align labels and float text to the left to make them appear on the same line in bootstrap

<form  class="form-horizontal" action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >

  <fieldset>
  <legend>
Security Department User Registration
</legend>

   First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">

   Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input">

   Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input">

```

In my form I get label  at the top and next line field .Since I have used row three of them are in the same row but I want label then followed by field .

Right now I am not able to get the field in horizontal line First Name,Second Name,Dpt./Location.

LABEL AT TOP AND FIELD AT THE BOTTOM

I HAVE LABEL OF DIFFERENT LENGTH I WANT IT TO BE ARRANGED PROPERLY.

what changes I need to do

In my form I want both label and text field to be horizontal label to be at right side and followed by  text field
  I have many other fields  but they don`t align properly because of  label being lengthy .

I want all the label both long and short to be aligned properly immediately followed by text field.

I  pic u can see label (name and DOB) is followed by text field   are in the  same line
  This is what I want to do

答:
Please check the following link and I think you will find a solution for your question.

https://jsfiddle.net/wLxf6cnn/

Note: Make the viewport larger than 768px wide to see that all of the form elements are inline, left aligned, and the labels are alongside.

```<code><form action="addtodatabase.php" method="post" enctype="multipart/form-data">
      <div class="container-fluid">
        <legend>
          <h5>Security Department User Registration</h5>
        </legend>

        <div class="row form-inline">
          <div class="col-xs-4 form-group">
            <label class="control-label" for="Firstname">First Name
              <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">
              <br/>
            </label>
          </div>

          <div class="col-xs-4 form-group">
            <label class="control-label" for="Secondname">Second Name
              <input type="text" class="form-control input-sm" name="secondname" placeholder="Text input">
              <br/>
            </label>
          </div>

          <div class="col-xs-4 form-group">
            <label class="control-label" for="location">Dpt./Location
              <input type="text" class="form-control input-sm" name="location" placeholder="Text input">
            </label>
          </div>
        </div>
</code>```

Body:
<form  class="form-horizontal" action="addtodatabase.php" class="form-inline" method="post" enctype="multipart/form-data" >

  <fieldset>
  <legend>
Security Department User Registration
</legend>

   First Name

   <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">

   Second Name

   <input type="text" class="form-control input-sm"  name="secondname" placeholder="Text input">

   Dpt./Location

   <input type="text" class="form-control input-sm"  name="location"  placeholder="Text input">

In my form I get label  at the top and next line field .Since I have used row three of them are in the same row but I want label then followed by field .

Right now I am not able to get the field in horizontal line First Name,Second Name,Dpt./Location.

LABEL AT TOP AND FIELD AT THE BOTTOM

I HAVE LABEL OF DIFFERENT LENGTH I WANT IT TO BE ARRANGED PROPERLY.

what changes I need to do

In my form I want both label and text field to be horizontal label to be at right side and followed by  text field
  I have many other fields  but they don`t align properly because of  label being lengthy .

I want all the label both long and short to be aligned properly immediately followed by text field.

I  pic u can see label (name and DOB) is followed by text field   are in the  same line
  This is what I want to do

Body:
Please check the following link and I think you will find a solution for your question.

https://jsfiddle.net/wLxf6cnn/

Note: Make the viewport larger than 768px wide to see that all of the form elements are inline, left aligned, and the labels are alongside.

<form action="addtodatabase.php" method="post" enctype="multipart/form-data">
      <div class="container-fluid">
        <legend>
          <h5>Security Department User Registration</h5>
        </legend>

        <div class="row form-inline">
          <div class="col-xs-4 form-group">
            <label class="control-label" for="Firstname">First Name
              <input type="text" class="form-control input-sm" name="firstname" placeholder="Text input">
              <br/>
            </label>
          </div>

          <div class="col-xs-4 form-group">
            <label class="control-label" for="Secondname">Second Name
              <input type="text" class="form-control input-sm" name="secondname" placeholder="Text input">
              <br/>
            </label>
          </div>

          <div class="col-xs-4 form-group">
            <label class="control-label" for="location">Dpt./Location
              <input type="text" class="form-control input-sm" name="location" placeholder="Text input">
            </label>
          </div>
        </div>


问:
Confusion about front end framework
I have a question if we don't use any front end framework like angular or react so can we stick with node express or mongodb please answer my question i am very confused about it please help me</p>

答:
Nodejs is a server side framework .
If you stick with it for front end as well , you can use jade , ejs or other server side languages for serving front end or html as well.

But this will degrade site speed because you are going to server things from server which means you are going to refresh full page and you are not going to use the concept of Single Page App

Title: Confusion about front end framework


答:
remove unnecessary semicolumn's </p>

```<code>CREATE VIEW judge_vw AS
      SELECT *FROM judge
      WHERE suburb='adelaide'
      order by judge_id;

    insert into judge_vw values('judge_id 6','schofield','adelaide');

    update judge_vw set name='russell'where names='jones';

    delete from judge_vw where judge_id=7;

    drop view if exists judge_vw;
</code>```

Title: having trouble with mysql code keep getting error 1064

Body:
remove unnecessary semicolumn's

CREATE VIEW judge_vw AS
      SELECT *FROM judge
      WHERE suburb='adelaide'
      order by judge_id;

    insert into judge_vw values('judge_id 6','schofield','adelaide');

    update judge_vw set name='russell'where names='jones';

    delete from judge_vw where judge_id=7;

    drop view if exists judge_vw;


问:
Pycharm Error - No module named MySQLdb
I have installed MySqldb as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
</code>```

But still I am getting the error:-

```<code>python --version
Python 2.7.11
</code>```

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages
</code>```

Can someone let me know how can I get rid of this error?

答:
Your Pycharm was not using the right python environment.You can change the project interpreter by setting Pycharm.
Step:

File-> Settings

In Popup menu:  Project-> Project Interpreter-> add  or create virtualenv environment

After changing project interpreter, the Pycharm has many function to use

Title: Pycharm Error - No module named MySQLdb

Body:
I have installed MySqldb as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5

But still I am getting the error:-

python --version
Python 2.7.11

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages

Can someone let me know how can I get rid of this error?


问:
Adding GeometryModel3D to Model3DGroup
I am trying to create a wpf app that shows an animated 3D model. I have working code to create the model in BuildWave (I know this works as I have used it before). However, when I moved the code to a background worker in the class of the wpf window, I get the error "The calling thread cannot access this object because a different thread owns it."

```<code>    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = BuildWave();
    }

    private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        GeometryModel3D model = (GeometryModel3D)e.Result;
        mGeometry = model.Clone();    //mGeometry is a private member of the window
        if (group.Children.Contains(mGeometry))   //error is on this line
        {
            group.Children.Remove(mGeometry);    //group is a Model3DGroup added in xaml
        }
        group.Children.Add(mGeometry);
        System.Diagnostics.Debug.WriteLine("Added geometry to group");
    }
</code>```

I have searched for solutions to this and found a post that covers a problem with the same error (The calling thread cannot access this object because a different thread owns it), which suggests using Dispatcher.Invoke(). However, when I try that:

```<code>    private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        GeometryModel3D model = (GeometryModel3D)e.Result;
        mGeometry = model.Clone();

        group.Dispatcher.Invoke(() =>
        {
            if (group.Children.Contains(mGeometry))
            {
                group.Children.Remove(mGeometry);
            }
            group.Children.Add(mGeometry);    //error is now thrown on this line
        });

        System.Diagnostics.Debug.WriteLine("Added geometry to group");
    }
</code>```

This throws the error "Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.", and again there is a post covering a similar problem (Cannot use a DependencyObject that belongs to a different thread than its parent Freezable) which suggests freezing the model which I have done in BuildWave:

```<code>        GeometryModel3D model = new GeometryModel3D(WaveMesh, new DiffuseMaterial(Brushes.YellowGreen));
        model.Transform = new Transform3DGroup();

        model.Freeze();
        return model;
</code>```

What should I do to fix this?

thank you in advance.

答: For it works with no problem, prepare in your bgworker  all the data(lists of points, lists of a triangle vertices) for your geometry model and do not use the gui objects such as Point3DCollection or Int32Collection or geometries. Then, when you ready with it, create all your geometries etc. in your lambda method(you can gladly extract this creation to a method for more readability and call it in lambda), which you call on a dispatcher. This should work.

Title: Adding GeometryModel3D to Model3DGroup

Body:
I am trying to create a wpf app that shows an animated 3D model. I have working code to create the model in BuildWave (I know this works as I have used it before). However, when I moved the code to a background worker in the class of the wpf window, I get the error "The calling thread cannot access this object because a different thread owns it."

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = BuildWave();
    }

    private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        GeometryModel3D model = (GeometryModel3D)e.Result;
        mGeometry = model.Clone();    //mGeometry is a private member of the window
        if (group.Children.Contains(mGeometry))   //error is on this line
        {
            group.Children.Remove(mGeometry);    //group is a Model3DGroup added in xaml
        }
        group.Children.Add(mGeometry);
        System.Diagnostics.Debug.WriteLine("Added geometry to group");
    }

I have searched for solutions to this and found a post that covers a problem with the same error (The calling thread cannot access this object because a different thread owns it), which suggests using Dispatcher.Invoke(). However, when I try that:

    private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        GeometryModel3D model = (GeometryModel3D)e.Result;
        mGeometry = model.Clone();

        group.Dispatcher.Invoke(() =>
        {
            if (group.Children.Contains(mGeometry))
            {
                group.Children.Remove(mGeometry);
            }
            group.Children.Add(mGeometry);    //error is now thrown on this line
        });

        System.Diagnostics.Debug.WriteLine("Added geometry to group");
    }

This throws the error "Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.", and again there is a post covering a similar problem (Cannot use a DependencyObject that belongs to a different thread than its parent Freezable) which suggests freezing the model which I have done in BuildWave:

        GeometryModel3D model = new GeometryModel3D(WaveMesh, new DiffuseMaterial(Brushes.YellowGreen));
        model.Transform = new Transform3DGroup();

        model.Freeze();
        return model;

What should I do to fix this?

thank you in advance.


问:
Invalid date in safari
```<code> alert(new Date('2010-11-29'));
</code>```

chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?

edit : ok, as per the comments below, I used string parsing and tried this :

```<code>alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari
</code>```

edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.

答:
Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY format.

If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC().

Title: Invalid date in safari

Body:
 alert(new Date('2010-11-29'));

chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?

edit : ok, as per the comments below, I used string parsing and tried this :

alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari

edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.


问:
how to remove numeric characters before any alphabetic characters
I have one variable which has values like this

```<code>VAL1="59809_RH_EA_TEST_1_P1_Q"
</code>```

or

```<code>VAL1="89292-RH_EA_TEST_1_P1_Q"
</code>```

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

答:
Alternative approaches:

```<code>VAL1="59809_RH_EA_TEST_1_P1_Q"
</code>```

sed approach:

```<code>sed 's/^[^_-]*[_-]\(.*\)/\1/' <<< $VAL1
</code>```

cut approach:

```<code>cut -d'_' -f2- <<< $VAL1
</code>```

The output(for both approaches):

```<code>RH_EA_TEST_1_P1_Q
</code>```

Body:
I have one variable which has values like this

VAL1="59809_RH_EA_TEST_1_P1_Q"

or

VAL1="89292-RH_EA_TEST_1_P1_Q"

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

Body:
Alternative approaches:

VAL1="59809_RH_EA_TEST_1_P1_Q"

sed approach:

sed 's/^[^_-]*[_-]\(.*\)/\1/' <<< $VAL1

cut approach:

cut -d'_' -f2- <<< $VAL1

The output(for both approaches):

RH_EA_TEST_1_P1_Q


问:
setonclicklistener effect every 4th position in recycler view
```<code>/**
 * Created by Prateek on 2/18/2017.
 */

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import newsee.novasyslabs.com.nodefetch.Others.CircularTransform;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    Context mContext;
    public static ArrayList <String> embed_html = new ArrayList<>();
    public static ArrayList <String>  channel_thumbnail = new ArrayList<>();
    public static ArrayList <String> channel_title = new ArrayList<>();
    public static ArrayList <String> video_title = new ArrayList<>();
    public static ArrayList <String> created_time = new ArrayList<>();
    public static ArrayList <Integer> android_likes = new ArrayList<>();
    public static ArrayList <Integer> pf_likes = new ArrayList<>();
    public static ArrayList <Integer> android_views = new ArrayList<>();
    public static ArrayList <Integer> pf_views = new ArrayList<>();

    public RecyclerAdapter(Context mContext){
        this.mContext = mContext;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        WebView webView;
        public ImageView chlogo;
        public TextView chtitle;
        public TextView vidtitle;
        public TextView upld_time;
        public TextView show_views;
        public TextView show_likes;
        public ImageView mLike;
        int j = 0;
        public ViewHolder(View itemView) {
            super(itemView);
            this.mLike = (ImageView)itemView.findViewById(R.id.video_like);
            this.show_views = (TextView) itemView.findViewById(R.id.video_views_count);
            this.show_likes = (TextView) itemView.findViewById(R.id.likes_count);
            this.webView = (WebView) itemView.findViewById(R.id.web);
            this.chlogo = (ImageView) itemView.findViewById(R.id.ch_logo);
            this.chtitle = (TextView) itemView.findViewById(R.id.ch_name);
            this.vidtitle = (TextView) itemView.findViewById(R.id.video_title);
            this.upld_time = (TextView)itemView.findViewById(R.id.ch_time);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.layout_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (holder.j==0) {
                    holder.mLike.setImageResource(R.drawable.liked);
                    CharSequence like = holder.show_likes.getText();
                    int new_like = Integer.parseInt((String) like) + 1;
                    Toast.makeText(mContext,"Liked" +new_like ,Toast.LENGTH_SHORT).show();
                    holder.j = 1;
                } else {
                    holder.mLike.setImageResource(R.drawable.unlike);
                    CharSequence like = holder.show_likes.getText();
                    int new_like = Integer.parseInt((String) like) - 1;
                    Toast.makeText(mContext,"Unliked" +new_like,Toast.LENGTH_SHORT).show();
                    holder.j = 0;
                }
            }
        });

            holder.webView.getSettings().setJavaScriptEnabled(true);
            holder.webView.loadData(embed_html.get(position), "text/html", "utf-8");
            Picasso.with(mContext).load(channel_thumbnail.get(position)).transform(new CircularTransform()).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(holder.chlogo);
            holder.chtitle.setText(channel_title.get(position));
            holder.vidtitle.setText(video_title.get(position));
            holder.upld_time.setText(created_time.get(position));
            int and_views = android_views.get(position);
            int views = pf_views.get(position);
            views += and_views;
            int and_likes = android_likes.get(position);
            int likes = pf_likes.get(position);
            likes += and_likes;
            holder.show_views.setText("" + views);
            holder.show_likes.setText("" + likes);

        }
    @Override
    public int getItemCount() {
        return embed_html.size();
    }
}
</code>```

when i am clicking then image change for 0th postion then 4,8,12.... why onclicklistener effect every 4 object in recyclerview i am changing the image resource onClick but the images changes for 4postion, 8position

答:
I would recommend doing it this way, first in your onBindViewHolder method add this code:

```<code>holder.mLike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            showImage(position);
            }
        }
    });
</code>```

Then create a new method in this class only:

```<code>public void showImage(int position){
if (position == 0) {
        holder.imageView.setImageResource(R.drawable.medal);
    }
...
}
</code>```

Body:
/**
 * Created by Prateek on 2/18/2017.
 */

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import newsee.novasyslabs.com.nodefetch.Others.CircularTransform;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    Context mContext;
    public static ArrayList <String> embed_html = new ArrayList<>();
    public static ArrayList <String>  channel_thumbnail = new ArrayList<>();
    public static ArrayList <String> channel_title = new ArrayList<>();
    public static ArrayList <String> video_title = new ArrayList<>();
    public static ArrayList <String> created_time = new ArrayList<>();
    public static ArrayList <Integer> android_likes = new ArrayList<>();
    public static ArrayList <Integer> pf_likes = new ArrayList<>();
    public static ArrayList <Integer> android_views = new ArrayList<>();
    public static ArrayList <Integer> pf_views = new ArrayList<>();

    public RecyclerAdapter(Context mContext){
        this.mContext = mContext;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        WebView webView;
        public ImageView chlogo;
        public TextView chtitle;
        public TextView vidtitle;
        public TextView upld_time;
        public TextView show_views;
        public TextView show_likes;
        public ImageView mLike;
        int j = 0;
        public ViewHolder(View itemView) {
            super(itemView);
            this.mLike = (ImageView)itemView.findViewById(R.id.video_like);
            this.show_views = (TextView) itemView.findViewById(R.id.video_views_count);
            this.show_likes = (TextView) itemView.findViewById(R.id.likes_count);
            this.webView = (WebView) itemView.findViewById(R.id.web);
            this.chlogo = (ImageView) itemView.findViewById(R.id.ch_logo);
            this.chtitle = (TextView) itemView.findViewById(R.id.ch_name);
            this.vidtitle = (TextView) itemView.findViewById(R.id.video_title);
            this.upld_time = (TextView)itemView.findViewById(R.id.ch_time);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.layout_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (holder.j==0) {
                    holder.mLike.setImageResource(R.drawable.liked);
                    CharSequence like = holder.show_likes.getText();
                    int new_like = Integer.parseInt((String) like) + 1;
                    Toast.makeText(mContext,"Liked" +new_like ,Toast.LENGTH_SHORT).show();
                    holder.j = 1;
                } else {
                    holder.mLike.setImageResource(R.drawable.unlike);
                    CharSequence like = holder.show_likes.getText();
                    int new_like = Integer.parseInt((String) like) - 1;
                    Toast.makeText(mContext,"Unliked" +new_like,Toast.LENGTH_SHORT).show();
                    holder.j = 0;
                }
            }
        });

            holder.webView.getSettings().setJavaScriptEnabled(true);
            holder.webView.loadData(embed_html.get(position), "text/html", "utf-8");
            Picasso.with(mContext).load(channel_thumbnail.get(position)).transform(new CircularTransform()).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(holder.chlogo);
            holder.chtitle.setText(channel_title.get(position));
            holder.vidtitle.setText(video_title.get(position));
            holder.upld_time.setText(created_time.get(position));
            int and_views = android_views.get(position);
            int views = pf_views.get(position);
            views += and_views;
            int and_likes = android_likes.get(position);
            int likes = pf_likes.get(position);
            likes += and_likes;
            holder.show_views.setText("" + views);
            holder.show_likes.setText("" + likes);

        }
    @Override
    public int getItemCount() {
        return embed_html.size();
    }
}

when i am clicking then image change for 0th postion then 4,8,12.... why onclicklistener effect every 4 object in recyclerview i am changing the image resource onClick but the images changes for 4postion, 8position

Body:
I would recommend doing it this way, first in your onBindViewHolder method add this code:

holder.mLike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            showImage(position);
            }
        }
    });

Then create a new method in this class only:

public void showImage(int position){
if (position == 0) {
        holder.imageView.setImageResource(R.drawable.medal);
    }
...
}


问:
How to deserialize multiple objects sequentially using jackson-databind
I am using msgpack to serialize data. I have some code works fine with serializing data.

```<code>public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}
</code>```

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

答:
@Japu_D_Cret Thank you for such a detailed answer!
Actually I want to use msgpack to transfer data, and I made it work by using msgpack, here is my code

```<code>    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    MessagePack packer = new MessagePack();

    packer.write(out, data1);
    packer.write(out, data2);
    packer.write(out, data3);

    // TODO: How to deserialize?

    BufferUnpacker unpacker = packer.createBufferUnpacker(out.toByteArray());
    System.out.println(unpacker.readString());
    System.out.println(unpacker.readInt());
    System.out.println(unpacker.read(Templates.tList(Templates.TString)));
</code>```

Then I found jackson-databind on msgpack website and it supports msgpack format also.
I do some tests on these two and found that jackson's serialize performance is better than msgpack, so I want to use jackson instead of msgpack.

Body:
I am using msgpack to serialize data. I have some code works fine with serializing data.

public void testJackson() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data1);
    mapper.writeValue(out, data2);
    mapper.writeValue(out, data3);

    // TODO: How to deserialize?

}

But now I don't know how to deserialize data.
I am not finding any solution anywhere. It will be good if anyone can help how to proceed.

Body:
@Japu_D_Cret Thank you for such a detailed answer!
Actually I want to use msgpack to transfer data, and I made it work by using msgpack, here is my code

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    String data1 = "test data";
    int data2 = 10;
    List<String> data3 = new ArrayList<String>();
    data3.add("list data1");
    data3.add("list data1");

    MessagePack packer = new MessagePack();

    packer.write(out, data1);
    packer.write(out, data2);
    packer.write(out, data3);

    // TODO: How to deserialize?

    BufferUnpacker unpacker = packer.createBufferUnpacker(out.toByteArray());
    System.out.println(unpacker.readString());
    System.out.println(unpacker.readInt());
    System.out.println(unpacker.read(Templates.tList(Templates.TString)));

Then I found jackson-databind on msgpack website and it supports msgpack format also.
I do some tests on these two and found that jackson's serialize performance is better than msgpack, so I want to use jackson instead of msgpack.


问:
Select - options and AngularJS - add glyphicon to options
I use this select - options in my AngularJS application:

```<code><select data-ng-model="userFilter" data-ng-options="c as c.firstname + ' ' + c.surname for c in vm.users">
    <option></option>
</select>
</code>```

and now I will add a glyphicon to each option value:

```<code><span class="glyphicon glyphicon-user"></span>
</code>```

is there a possibility to do it like this?

答:
I don't know a way with ng-options, though you could use ng-repeat:</p>

```<code><select data-ng-model="userFilterIndex" data-ng-change ="userFilter = vm.users[ userFilterIndex ]">

    <option data-ng-repeat="c in vm.users" value="{{ $index }}">
        <span class="glyphicon glyphicon-user"></span>
        {{ c.firstname + ' ' + c.surname }}
    </option>

</select>
</code>```

Body:
I use this select - options in my AngularJS application:

<select data-ng-model="userFilter" data-ng-options="c as c.firstname + ' ' + c.surname for c in vm.users">
    <option></option>
</select>

and now I will add a glyphicon to each option value:

is there a possibility to do it like this?

Body:
I don't know a way with ng-options, though you could use ng-repeat:

<select data-ng-model="userFilterIndex" data-ng-change ="userFilter = vm.users[ userFilterIndex ]">

    <option data-ng-repeat="c in vm.users" value="{{ $index }}">
        <span class="glyphicon glyphicon-user"></span>
        {{ c.firstname + ' ' + c.surname }}
    </option>

</select>


问:
Apply a list of functions to every item in a list?
I am making a program that works on chat files under the following general form:

Open file & import lines (via readlines)

Do an initial pass to turn the list of strings into better-formed data (currently dicts) by:

Throwing out out malformed lines

Separating out the usernames from the text of the message

Throwing out lines for ignored (typically bot) users

Marking which lines are /me commands

Do a second pass over the list of dicts to apply various manipulations on them, such as:

Replacing every mention of a nick with its alias

Applying special formatting to /me commands

Rather than have multiple switches in the config file and lots of if statement checks within the loops, I believe the program would be cleaner if I generated the list of functions elsewhere and then fed the program the list of dicts (or strings, depending on which part of the program I'm at) and a list of functions such that the list of functions gets applied to each of the items in the list of objects.

It seems that this probably would be a good case for list comprehensions if I were only applying a single function to each item, but I don't want to have to do a separate pass through the log for every function that I want to call.  However, this answer notes that list comprehension probably aren't what I want, since they return a completely new list, rather than modifying in place.

Is my best option to have two variants of the following?

```<code>for item in list:
    item = a(b(c(d(item, dparam1, dparam2), cparam)), aparams)
</code>```

(for readability, I'd put each function on its own line, like:

```<code>for item in list:
    item = d(item, dparam1, dparam2)
    item = c(item, cparam)
    item = b(item)
    item = a(item, aparams)
</code>```

However, the above doesn't eliminate the need for if checks on all the switches and wouldn't allow for applying function a at two different places unless I explicitly add a switch to do so.

答:
Based on your sample code, you may try this way,

```<code>func_list = [d, c, b, a]
for idx, item in enumerate(item_list):
    item_list[idx] = reduce(lambda v, func: func(v), func_list, item)
</code>```

Let each func handle the data, make the loop more like pipeline.

Body:
I am making a program that works on chat files under the following general form:

Open file & import lines (via readlines)

Do an initial pass to turn the list of strings into better-formed data (currently dicts) by:

Throwing out out malformed lines

Separating out the usernames from the text of the message

Throwing out lines for ignored (typically bot) users

Marking which lines are /me commands

Do a second pass over the list of dicts to apply various manipulations on them, such as:

Replacing every mention of a nick with its alias

Applying special formatting to /me commands

Rather than have multiple switches in the config file and lots of if statement checks within the loops, I believe the program would be cleaner if I generated the list of functions elsewhere and then fed the program the list of dicts (or strings, depending on which part of the program I'm at) and a list of functions such that the list of functions gets applied to each of the items in the list of objects.

It seems that this probably would be a good case for list comprehensions if I were only applying a single function to each item, but I don't want to have to do a separate pass through the log for every function that I want to call.  However, this answer notes that list comprehension probably aren't what I want, since they return a completely new list, rather than modifying in place.

Is my best option to have two variants of the following?

for item in list:
    item = a(b(c(d(item, dparam1, dparam2), cparam)), aparams)

(for readability, I'd put each function on its own line, like:

for item in list:
    item = d(item, dparam1, dparam2)
    item = c(item, cparam)
    item = b(item)
    item = a(item, aparams)

However, the above doesn't eliminate the need for if checks on all the switches and wouldn't allow for applying function a at two different places unless I explicitly add a switch to do so.

Body:
Based on your sample code, you may try this way,

func_list = [d, c, b, a]
for idx, item in enumerate(item_list):
    item_list[idx] = reduce(lambda v, func: func(v), func_list, item)

Let each func handle the data, make the loop more like pipeline.


问:
Using Python multiprocessing in Slurm, and which combination of ntasks or ncpus I need
I'm trying to run a python script on a slurm cluster, and I'm using python's built-in multiprocessing module.

I'm using quite a simple set up, where for testing purpose, the example is:

```<code>len(arg_list)
Out[2]: 5

threads = multiprocessing.Pool(5)
output = threads.map(func, arg_list)
</code>```

So func is applied 5 times in parallel on 5 arguments in arg_list. What I want to know is how to allocate the correct amount of cpu's/tasks in slurm for this to work as expected. This is what the relevant part of my slurm batch script looks like:

```<code>#!/bin/bash

# Runtime and memory
#SBATCH --time=90:00:00
#SBATCH --mem-per-cpu=2G

# For parallel jobs
#SBATCH --cpus-per-task=10
##SBATCH --nodes=2
#SBATCH --ntasks=1
##SBATCH --ntasks-per-node=4

#### Your shell commands below this line ####

srun ./script_wrapper.py 'test'
</code>```

As you can see, at the moment I have ntasks=1 and cpus-per-task=10. Note that the main bulk of func contains a scipy routine which tends to run on two cores (i.e uses 200% cpu usage, which is why I want 10 cpus and not 5).

Is this the correct way to allocate resources for my purposes, because at the moment the job takes a lot longer than expected (more like it's running in a single thread).

Do I need to set ntasks=5 instead? Because my impression from online documentation was that ntasks=5 would instead call srun ./script_wrapper.py 'test' five times instead, which is not what I want. Am I right in that assumption?

Also, is there a way to easily check stuff like CPU usage and all the process id's of the python tasks called by multiprocessing.Pool? At the moment I'm trying with sacct -u <user> --format=JobID,JobName,MaxRSS,Elapsed,AveCPU, but the AveCPU and MaxRSS fields always come up empty for some reason (?) and while I see the first script as a process, I don't see the 5 others that should be called by multiprocessing. Example:

```<code>       JobID    JobName     MaxRSS    Elapsed     AveCPU
------------ ---------- ---------- ---------- ----------
16260892             GP              00:13:07
16260892.0   script_wr+              00:13:07
</code>```

答:
Your Slurm task allocation looks correct to me. Python's multiprocessing will only run on a single machine, and it looks to me like you're allocating the 10 CPUs on one node correctly. What might be causing the problem is that multiprocessing's Pool.map by default works on "chunks" of the input list rather than one element at a time. It does this to minimise overhead when tasks are short. To force multiprocessing to work on one element of the list at a time, set the chunksize parameter of the map to 1, e.g.

```<code>threads.map(func, arglist, 1)
</code>```

See the multiprocessing documentation for more information.

Because you say that you're using a multithreaded version of SciPy, you may also want to check the relevant threading level for the underlying library. For instance, if your SciPy has been built against Intel Math Kernel Library, try setting the OMP_NUM_THREADS andMKL_NUM_THREADS environment variables to make sure it's using no more than 2 threads per process and making full use (and not over-use) of your allocated SLURM resources.

EDIT: sacct is only going to give you running times for any processes that were launched directly by srun, and not for any subprocesses. Hence in your case you'll only have the one process from the single srun command. To monitor the subprocesses you may have to look into monitoring tools that operate at a system level rather than through Slurm.

Body:
I'm trying to run a python script on a slurm cluster, and I'm using python's built-in multiprocessing module.

I'm using quite a simple set up, where for testing purpose, the example is:

len(arg_list)
Out[2]: 5

threads = multiprocessing.Pool(5)
output = threads.map(func, arg_list)

So func is applied 5 times in parallel on 5 arguments in arg_list. What I want to know is how to allocate the correct amount of cpu's/tasks in slurm for this to work as expected. This is what the relevant part of my slurm batch script looks like:

#!/bin/bash

# Runtime and memory
#SBATCH --time=90:00:00
#SBATCH --mem-per-cpu=2G

# For parallel jobs
#SBATCH --cpus-per-task=10
##SBATCH --nodes=2
#SBATCH --ntasks=1
##SBATCH --ntasks-per-node=4

#### Your shell commands below this line ####

srun ./script_wrapper.py 'test'

As you can see, at the moment I have ntasks=1 and cpus-per-task=10. Note that the main bulk of func contains a scipy routine which tends to run on two cores (i.e uses 200% cpu usage, which is why I want 10 cpus and not 5).

Is this the correct way to allocate resources for my purposes, because at the moment the job takes a lot longer than expected (more like it's running in a single thread).

Do I need to set ntasks=5 instead? Because my impression from online documentation was that ntasks=5 would instead call srun ./script_wrapper.py 'test' five times instead, which is not what I want. Am I right in that assumption?

Also, is there a way to easily check stuff like CPU usage and all the process id's of the python tasks called by multiprocessing.Pool? At the moment I'm trying with sacct -u <user> --format=JobID,JobName,MaxRSS,Elapsed,AveCPU, but the AveCPU and MaxRSS fields always come up empty for some reason (?) and while I see the first script as a process, I don't see the 5 others that should be called by multiprocessing. Example:

       JobID    JobName     MaxRSS    Elapsed     AveCPU
------------ ---------- ---------- ---------- ----------
16260892             GP              00:13:07
16260892.0   script_wr+              00:13:07

Body:
Your Slurm task allocation looks correct to me. Python's multiprocessing will only run on a single machine, and it looks to me like you're allocating the 10 CPUs on one node correctly. What might be causing the problem is that multiprocessing's Pool.map by default works on "chunks" of the input list rather than one element at a time. It does this to minimise overhead when tasks are short. To force multiprocessing to work on one element of the list at a time, set the chunksize parameter of the map to 1, e.g.

threads.map(func, arglist, 1)

See the multiprocessing documentation for more information.

Because you say that you're using a multithreaded version of SciPy, you may also want to check the relevant threading level for the underlying library. For instance, if your SciPy has been built against Intel Math Kernel Library, try setting the OMP_NUM_THREADS andMKL_NUM_THREADS environment variables to make sure it's using no more than 2 threads per process and making full use (and not over-use) of your allocated SLURM resources.

EDIT: sacct is only going to give you running times for any processes that were launched directly by srun, and not for any subprocesses. Hence in your case you'll only have the one process from the single srun command. To monitor the subprocesses you may have to look into monitoring tools that operate at a system level rather than through Slurm.


问:
Converting XML to C# object
I need to get the OrderID from these xml data:

```<code><?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>
</code>```

I have tried this one but does not work.

```<code>var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}
</code>```

Please advice.

答:
You can get it using XmlDocument and XmlNodeList also - if you are saving the xml data in file

```<code>        XmlDocument doc = new XmlDocument();
        doc.Load("your XML File Name with extension");
        XmlNodeList elemList = doc.GetElementsByTagName("OrderID");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerText);
        }
</code>```

Title: Converting XML to C# object

Body:
I need to get the OrderID from these xml data:

<?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>

I have tried this one but does not work.

var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}

Please advice.

Body:
You can get it using XmlDocument and XmlNodeList also - if you are saving the xml data in file

        XmlDocument doc = new XmlDocument();
        doc.Load("your XML File Name with extension");
        XmlNodeList elemList = doc.GetElementsByTagName("OrderID");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerText);
        }


问:
Change the url based on current_user - ROR
Say for instance I have a posts controller that currently has a method user_posts which shows all of the posts that are associated with the user with the associated id as so:

```<code>def user_posts
    @user = User.find(params[:id])
    @posts = @user.posts.all
end
</code>```

I want the url to be: foo.com/my_posts when the posts have the same ID as my current_user; How would I do this? currently my routes are set up as so:

```<code>get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
</code>```

I know that I could create an entirely new controller action for my_posts but I want to know if there is a way to do it in the config/routes.

If for example I am browsing throughout the site and tap on a link that says "user posts" I would expect to go the the users posts and if that user happens to be me I would like the url to show website.com/my_posts

答:
As I know - no. It's possible to create in routes redirect route and check some conditions (example from documantation):

```<code>get 'jokes/:number', to: redirect { |params, request|
  path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
  "http://#{request.host_with_port}/#{path}"
}
</code>```

But it's impossible to check current user in routes. Redirect can be implemented in the controller with two separate actions as mentioned.

Also available a little trick - generate from the beginning 'right' routes if you use html.erb (slim/haml). For current user posts link can be generated not as usual user/posts/:id but /my_posts (it's possible to check current user id without any problems) and define two routes:

```<code>get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
get 'my_posts', to: 'posts#user_posts', as: 'my_posts'
</code>```

In controller check request.path to find user:

```<code>user = request.path == '/my_posts' ? current_user : User.find(params[:id])
</code>```

Hope it helps.

Body:
Say for instance I have a posts controller that currently has a method user_posts which shows all of the posts that are associated with the user with the associated id as so:

def user_posts
    @user = User.find(params[:id])
    @posts = @user.posts.all
end

I want the url to be: foo.com/my_posts when the posts have the same ID as my current_user; How would I do this? currently my routes are set up as so:

get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'

I know that I could create an entirely new controller action for my_posts but I want to know if there is a way to do it in the config/routes.

If for example I am browsing throughout the site and tap on a link that says "user posts" I would expect to go the the users posts and if that user happens to be me I would like the url to show website.com/my_posts

Body:
As I know - no. It's possible to create in routes redirect route and check some conditions (example from documantation):

get 'jokes/:number', to: redirect { |params, request|
  path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
  "http://#{request.host_with_port}/#{path}"
}

But it's impossible to check current user in routes. Redirect can be implemented in the controller with two separate actions as mentioned.

Also available a little trick - generate from the beginning 'right' routes if you use html.erb (slim/haml). For current user posts link can be generated not as usual user/posts/:id but /my_posts (it's possible to check current user id without any problems) and define two routes:

get 'user/posts/:id', to: 'posts#user_posts', as: 'user/posts'
get 'my_posts', to: 'posts#user_posts', as: 'my_posts'

In controller check request.path to find user:

user = request.path == '/my_posts' ? current_user : User.find(params[:id])

Hope it helps.


问:
Android library seems not to include it's dependencies (forcing me to add those dependencies in the app module)
I'm developing an Android library and a demo app that uses it. up until now I compiled both the app and the lib via source code and now that Iv'e built the lib and want to use the AAR file instead of the lib's source code - I get error about missing classes during runtime.

It looks like the dependencies of the library are not included in the AAR file.
Exception description:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/log4j/Logger;
....<clinit>(....java:57) at ...onCreate(...java:65) at android.app.Activity.performCreate(Activity.java:5961) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129) ...
</code>```

Here is the application's build.gradle :

```<code>apply plugin: 'com.android.application'

def APP_VERSION = 1.0

android {
    compileSdkVersion 25
    buildToolsVersion "25"
    defaultConfig {
        applicationId "..."
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName APP_VERSION + "(" + appVersionCode + ")"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    packagingOptions {
        //pickFirst  'META-INF/license.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/*'
        exclude 'META-INF/maven'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile(name:'library_filename', ext:'aar')

    <HERE IV'E ADDED THE LIB'S DEPENDENCIES IN ORDER FOR THE APP TO WORK>

    //Other dependencies needed by the application
    compile 'com.google.android.gms:play-services-base:9.4.0'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.android.support:design:25.2.0'

}
</code>```

In this example it happened with Log4J. When I added the dependency of Log4J from the library's build.gradle to the application's build.gradle - the error did not happen.

The library is a simple one. We are using flavors and multiDexEnabled is set to true.

Any ideas why the lib's dependencies are not found when building with the AAR file? any remedies?

Thanks!

答:
The aar file doens't contain the transitive dependencies.

The alternative is to publish the library in a maven repository (public or private). Gradle in this case with the pom file is able to download also the dependencies.

Body:
I'm developing an Android library and a demo app that uses it. up until now I compiled both the app and the lib via source code and now that Iv'e built the lib and want to use the AAR file instead of the lib's source code - I get error about missing classes during runtime.

It looks like the dependencies of the library are not included in the AAR file.
Exception description:

java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/log4j/Logger;
....<clinit>(....java:57) at ...onCreate(...java:65) at android.app.Activity.performCreate(Activity.java:5961) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129) ...

Here is the application's build.gradle :

apply plugin: 'com.android.application'

def APP_VERSION = 1.0

android {
    compileSdkVersion 25
    buildToolsVersion "25"
    defaultConfig {
        applicationId "..."
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName APP_VERSION + "(" + appVersionCode + ")"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    packagingOptions {
        //pickFirst  'META-INF/license.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/*'
        exclude 'META-INF/maven'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile(name:'library_filename', ext:'aar')

    <HERE IV'E ADDED THE LIB'S DEPENDENCIES IN ORDER FOR THE APP TO WORK>

    //Other dependencies needed by the application
    compile 'com.google.android.gms:play-services-base:9.4.0'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.android.support:design:25.2.0'

}

In this example it happened with Log4J. When I added the dependency of Log4J from the library's build.gradle to the application's build.gradle - the error did not happen.

The library is a simple one. We are using flavors and multiDexEnabled is set to true.

Any ideas why the lib's dependencies are not found when building with the AAR file? any remedies?

Thanks!


问:
Submit form with selected concert seats with JavaScript and HTML
I have a form with input field

```<code><select name="tickets" multiple>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  ...
</select>
</code>```

With this select, I can choose which ticket ids I want to submit with the form.

But now I want to create a seat selector, so I need all the tickets as div elements. The seats will look something like

```<code><div class="seats">
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
</div>
</code>```

How can I make these div elements selectable? I know that I with simple javascript can listen for clicks and then change the class of the div element.

So a solution could be

```<code>$('.seat').click(function () {
  $(this).toggleClass('.selected-seat');
});
</code>```

and then something like

```<code>$('form').submit(function () {
  event.preventDefault();

  // submit array of ids of all those div elements with class 'selected-seat'
});
</code>```

However, this approach seems a bit wrong to me. Could another solution be to make the elements into something like

```<code><div class="seats">
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
</div>
</code>```

and then submit my form exactly as I normally submit a form without any javascript?

How are these seat selectors normally done?

答:
So I made a small sample of code for how you should go about this problem. I would suggest you to use jQuery a bit so that you can get flexibility on creating the design you are looking to create.

In the code below I just created a hidden input box which will carry the value you press on. You didn't mention if you want multiple select or single seat selector. This code is for single selector.

jQuery(document).ready(function(){
  jQuery('.seat').click(function(){
    jQuery(this).css('background','#fff');
    var seatNumber = jQuery(this).find('span').text();
    jQuery(this).find('input').attr('value',seatNumber);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.seat{
background:#eee;
margin-top:5px;
cursor:pointer;
}
.value{
color:blue;
font-weight:800;
}</code>```

    Seat Number 1
    <input type='text' name='seatNumber' hidden>

    Seat Number 2
    <input type='text' name='seatNumber' hidden>

    Seat Number
    3
    <input type='text' name='seatNumber' hidden>

    Seat Number
    4
    <input type='text' name='seatNumber' hidden>

    Seat Number
    5
    <input type='text' name='seatNumber' hidden>

```

Body:
I have a form with input field

<select name="tickets" multiple>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  ...
</select>

With this select, I can choose which ticket ids I want to submit with the form.

But now I want to create a seat selector, so I need all the tickets as div elements. The seats will look something like

Seat Number

Seat Number

Seat Number

Seat Number

Seat Number

How can I make these div elements selectable? I know that I with simple javascript can listen for clicks and then change the class of the div element.

So a solution could be

$('.seat').click(function () {
  $(this).toggleClass('.selected-seat');
});

and then something like

$('form').submit(function () {
  event.preventDefault();

  // submit array of ids of all those div elements with class 'selected-seat'
});

However, this approach seems a bit wrong to me. Could another solution be to make the elements into something like

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

and then submit my form exactly as I normally submit a form without any javascript?

How are these seat selectors normally done?

Body:
So I made a small sample of code for how you should go about this problem. I would suggest you to use jQuery a bit so that you can get flexibility on creating the design you are looking to create.

In the code below I just created a hidden input box which will carry the value you press on. You didn't mention if you want multiple select or single seat selector. This code is for single selector.

jQuery(document).ready(function(){
  jQuery('.seat').click(function(){
    jQuery(this).css('background','#fff');
    var seatNumber = jQuery(this).find('span').text();
    jQuery(this).find('input').attr('value',seatNumber);
  });
});

.seat{
background:#eee;
margin-top:5px;
cursor:pointer;
}
.value{
color:blue;
font-weight:800;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="seats">
  <div class="seat">
    Seat Number <span class='value'>1</span>
    <input type='text' name='seatNumber' hidden>
  </div>
  <div class="seat">
    Seat Number <span class='value'>2 </span>
    <input type='text' name='seatNumber' hidden>
  </div>
  <div class="seat">
    Seat Number
    <span class='value'>3</span>
    <input type='text' name='seatNumber' hidden>
  </div>
  <div class="seat">
    Seat Number
    <span class='value'>4</span>
    <input type='text' name='seatNumber' hidden>
  </div>
  <div class="seat">
    Seat Number
    <span class='value'>5</span>
    <input type='text' name='seatNumber' hidden>
  </div>

</div>


问:
python list all combiniations without itertools

I just want to make all combination of list(two size)

for example: input= [1, 2, 3] => output = [[1,2], [1,3], [2,3]]

how can i make this code more concise and simple?(one-liner?)

it doesn't mean list compreshension.

my code

```<code>def all_combinations(input_lst):
    return_lst=[]
    for i in range(0, len(input_lst)-1):
        for j in range(i+1, len(input_lst)):
            return_lst.append([input_lst[i], input_lst[j]])
    return return_lst
</code>```

答:
```<code>[(input_lst[i], input_lst[j]) for i in xrange(len(input_lst) - 1) for j in xrange(i + 1, len(input_lst))]
</code>```

Body:
I just want to make all combination of list(two size)

for example: input= [1, 2, 3] => output = [[1,2], [1,3], [2,3]]

how can i make this code more concise and simple?(one-liner?)

it doesn't mean list compreshension.

my code

def all_combinations(input_lst):
    return_lst=[]
    for i in range(0, len(input_lst)-1):
        for j in range(i+1, len(input_lst)):
            return_lst.append([input_lst[i], input_lst[j]])
    return return_lst


问:
Redirecting non-existing paths to a specific page
I am trying to redirect users who browse paths that doesn't exist to another page I set.
Example:
site.com/dhdhshs will redirect users to a specitic page because the path is not available.
How can I do this, also what kind of file should I create or edit on the webserver?
Thanks</p>

答:
404 redirects must be handled at the server-side. Following are the steps to do it.

Create a .htaccess file.

Add ErrorDocument 404 http://www.yourdomain.com/404.html to it.

Place it in the root directory of your project.


问:
Autocomplete textbox in Windows Phone 7
I'm creating my first Windows Phone 7 application, and I'm struggling to find an autocomplete textbox. Is there an easy way to add one to the toolbox? Or do I need to create my own control?</p>

答: AutoCompleteBox is in the Silverlight Tookit so you have to add a reference to that in your project.</p>

Title: Autocomplete textbox in Windows Phone 7