问:
python-daemon installation fails when using --prefix
if I execute:

```<code>pip install --install-option="--prefix=/root/folder" airflow==1.8.0
</code>```

it will end so

```<code>    'dist_version': self.distribution.get_version(),
  File "version.py", line 656, in get_version
    version_info = self.get_version_info()
  File "version.py", line 651, in get_version_info
    changelog_path = get_changelog_path(self)
  File "version.py", line 552, in get_changelog_path
    setup_dirname = os.path.dirname(distribution.script_name)
  File "/usr/lib64/python2.7/posixpath.py", line 129, in dirname
    i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
</code>```

If I execute

```<code> pip install airflow==1.8.0
</code>```

it will complete the process with no errors.

```<code># pip freeze
airflow==1.8.0
alembic==0.8.10
backports.ssl-match-hostname==3.4.0.2
chardet==2.2.1
click==6.7
croniter==0.3.16
dill==0.2.6
docutils==0.13.1
Flask==0.11.1
Flask-Admin==1.4.1
Flask-Cache==0.13.1
Flask-Login==0.2.11
flask-swagger==0.2.13
Flask-WTF==0.12
funcsigs==1.0.0
future==0.15.2
gitdb2==2.0.0
GitPython==2.1.3
gunicorn==19.3.0
iniparse==0.4
itsdangerous==0.24
Jinja2==2.8.1
kitchen==1.1.1
lockfile==0.12.2
lxml==3.7.3
Mako==1.0.6
Markdown==2.6.8
MarkupSafe==1.0
numpy==1.12.1
ordereddict==1.1
pandas==0.19.2
psutil==4.4.2
pycurl==7.19.0
Pygments==2.2.0
pygobject==3.14.0
pygpgme==0.3
pyliblzma==0.5.3
python-daemon==2.1.2
python-dateutil==2.6.0
python-editor==1.0.3
python-nvd3==0.14.2
python-slugify==1.1.4
pytz==2017.2
pyxattr==0.5.1
PyYAML==3.12
requests==2.13.0
setproctitle==1.1.10
six==1.10.0
smmap2==2.0.1
SQLAlchemy==1.1.8
tabulate==0.7.7
thrift==0.9.3
Unidecode==0.4.20
urlgrabber==3.10
Werkzeug==0.12.1
WTForms==2.1
yum-metadata-parser==1.1.4
zope.deprecation==4.2.0
</code>```

Since this has to run into a jenkins build process, I can't omit the install option. Can any power python-user help me to understand where to see and how to fix it ?

I read that you need to install this library (python-daemon) before anything else, but still does not work using the install options:

```<code>pip install --install-option="--prefix=/root/folder" python-daemon

/usr/lib/python2.7/site-packages/pip/commands/install.py:188: UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options.
      File "/usr/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 230, in finalize_options
        'dist_version': self.distribution.get_version(),
      File "version.py", line 656, in get_version
        version_info = self.get_version_info()
      File "version.py", line 651, in get_version_info
        changelog_path = get_changelog_path(self)
      File "version.py", line 552, in get_changelog_path
        setup_dirname = os.path.dirname(distribution.script_name)
      File "/usr/lib64/python2.7/posixpath.py", line 129, in dirname
        i = p.rfind('/') + 1
    AttributeError: 'NoneType' object has no attribute 'rfind'
</code>```

thanks in advance.

答:
I found a way to get it working, not the best and not the final solution, but it's working:

```<code> pip install python-daemon
</code>```

when it completes you should be able to see it into the list of

```<code>[root@localhost ozw1z5rd]# pip freeze | grep daemon
python-daemon==2.1.2
</code>```

now uninstall it

```<code> pip uninstall python-daemon
</code>```

and of course it will not longer available into the list of

```<code>[root@localhost ozw1z5rd]# pip freeze | grep daemon
</code>```

now install again using the prefix

```<code> pip install --install-option="--prefix=/root/folder" python-daemon
</code>```

this installation, of course, it is not available into the pip freeze list, but it completes with no error and inside the new path the library does exist.

```<code>[root@localhost ozw1z5rd]# ls /root/folder/lib/python2.7/site-packages/
daemon/                             python_daemon-2.1.2-py2.7.egg-info/
</code>```

All this allowed me to install airflow using Jenkins.

I investigated also the setup.py script of python-daemon, attrs['script_name'] is correctly loaded in the early part of the code, but it get lost later.

In this screen the code shown is where the attrs['script_name'] get lost.

Body:
if I execute:

pip install --install-option="--prefix=/root/folder" airflow==1.8.0

it will end so

    'dist_version': self.distribution.get_version(),
  File "version.py", line 656, in get_version
    version_info = self.get_version_info()
  File "version.py", line 651, in get_version_info
    changelog_path = get_changelog_path(self)
  File "version.py", line 552, in get_changelog_path
    setup_dirname = os.path.dirname(distribution.script_name)
  File "/usr/lib64/python2.7/posixpath.py", line 129, in dirname
    i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'

If I execute

 pip install airflow==1.8.0

it will complete the process with no errors.

# pip freeze
airflow==1.8.0
alembic==0.8.10
backports.ssl-match-hostname==3.4.0.2
chardet==2.2.1
click==6.7
croniter==0.3.16
dill==0.2.6
docutils==0.13.1
Flask==0.11.1
Flask-Admin==1.4.1
Flask-Cache==0.13.1
Flask-Login==0.2.11
flask-swagger==0.2.13
Flask-WTF==0.12
funcsigs==1.0.0
future==0.15.2
gitdb2==2.0.0
GitPython==2.1.3
gunicorn==19.3.0
iniparse==0.4
itsdangerous==0.24
Jinja2==2.8.1
kitchen==1.1.1
lockfile==0.12.2
lxml==3.7.3
Mako==1.0.6
Markdown==2.6.8
MarkupSafe==1.0
numpy==1.12.1
ordereddict==1.1
pandas==0.19.2
psutil==4.4.2
pycurl==7.19.0
Pygments==2.2.0
pygobject==3.14.0
pygpgme==0.3
pyliblzma==0.5.3
python-daemon==2.1.2
python-dateutil==2.6.0
python-editor==1.0.3
python-nvd3==0.14.2
python-slugify==1.1.4
pytz==2017.2
pyxattr==0.5.1
PyYAML==3.12
requests==2.13.0
setproctitle==1.1.10
six==1.10.0
smmap2==2.0.1
SQLAlchemy==1.1.8
tabulate==0.7.7
thrift==0.9.3
Unidecode==0.4.20
urlgrabber==3.10
Werkzeug==0.12.1
WTForms==2.1
yum-metadata-parser==1.1.4
zope.deprecation==4.2.0

Since this has to run into a jenkins build process, I can't omit the install option. Can any power python-user help me to understand where to see and how to fix it ?

I read that you need to install this library (python-daemon) before anything else, but still does not work using the install options:

pip install --install-option="--prefix=/root/folder" python-daemon

/usr/lib/python2.7/site-packages/pip/commands/install.py:188: UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options.
      File "/usr/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 230, in finalize_options
        'dist_version': self.distribution.get_version(),
      File "version.py", line 656, in get_version
        version_info = self.get_version_info()
      File "version.py", line 651, in get_version_info
        changelog_path = get_changelog_path(self)
      File "version.py", line 552, in get_changelog_path
        setup_dirname = os.path.dirname(distribution.script_name)
      File "/usr/lib64/python2.7/posixpath.py", line 129, in dirname
        i = p.rfind('/') + 1
    AttributeError: 'NoneType' object has no attribute 'rfind'

thanks in advance.

Body:
I found a way to get it working, not the best and not the final solution, but it's working:

 pip install python-daemon

when it completes you should be able to see it into the list of

[root@localhost ozw1z5rd]# pip freeze | grep daemon
python-daemon==2.1.2

now uninstall it

 pip uninstall python-daemon

and of course it will not longer available into the list of

[root@localhost ozw1z5rd]# pip freeze | grep daemon

now install again using the prefix

 pip install --install-option="--prefix=/root/folder" python-daemon

this installation, of course, it is not available into the pip freeze list, but it completes with no error and inside the new path the library does exist.

[root@localhost ozw1z5rd]# ls /root/folder/lib/python2.7/site-packages/
daemon/                             python_daemon-2.1.2-py2.7.egg-info/

All this allowed me to install airflow using Jenkins.

I investigated also the setup.py script of python-daemon, attrs['script_name'] is correctly loaded in the early part of the code, but it get lost later.

In this screen the code shown is where the attrs['script_name'] get lost.


来源: stackexchange

问:
Where will Firebase onDataChange() run in this example?
I know the onDataChange() in Firebase for let say addListenerForSingleValueEvent is running on Android Main Ui thread.

I Wanted to understand what will happen if I run this code inside the ExecutorService:

```<code>runInBackground(new Runnable() {
@Override
public void run() {
    ref.child("SOME_KEY")
            .addListenerForSingleValueEvent
                    (new ValueEventListener() {
                         @Override
                         public void onDataChange(final DataSnapshot dataSnapshot) {
                             //.. do some work on Ui Thread or not??
                         }

                         @Override
                         public void onCancelled(DatabaseError databaseError) {
                             notificationRunning = false;
                         }
                     }
                    );
}
});
}
</code>```

Will the onDataChange() still run on the Main Ui Thread in Android?
And here´s the ExecutorService runner

```<code>/**
 * Submits request to be executed in background.
 * Threads submitted will be executed synchronously.
 *
 * @param runnable
 */
private void runInBackground(final Runnable runnable) {
    mBackgroundExecutor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                runnable.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
</code>```

And the ExecutorService

```<code>mBackgroundExecutor = Executors
        .newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable,
                        "Background executor service for OneSignal");
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.setDaemon(true);
                return thread;
            }
        });
</code>```

答:
The listener callbacks always run on the main/UI thread.  The thread that was used to add the listener does not affect the callback thread.  You can confirm this by adding a log statement to your callback that outputs the thread name:</p>

```<code>Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know the onDataChange() in Firebase for let say addListenerForSingleValueEvent is running on Android Main Ui thread.

I Wanted to understand what will happen if I run this code inside the ExecutorService:

runInBackground(new Runnable() {
@Override
public void run() {
    ref.child("SOME_KEY")
            .addListenerForSingleValueEvent
                    (new ValueEventListener() {
                         @Override
                         public void onDataChange(final DataSnapshot dataSnapshot) {
                             //.. do some work on Ui Thread or not??
                         }

                         @Override
                         public void onCancelled(DatabaseError databaseError) {
                             notificationRunning = false;
                         }
                     }
                    );
}
});
}

Will the onDataChange() still run on the Main Ui Thread in Android?
And here´s the ExecutorService runner

/**
 * Submits request to be executed in background.
 * Threads submitted will be executed synchronously.
 *
 * @param runnable
 */
private void runInBackground(final Runnable runnable) {
    mBackgroundExecutor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                runnable.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

And the ExecutorService

mBackgroundExecutor = Executors
        .newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable,
                        "Background executor service for OneSignal");
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.setDaemon(true);
                return thread;
            }
        });

Body:
The listener callbacks always run on the main/UI thread.  The thread that was used to add the listener does not affect the callback thread.  You can confirm this by adding a log statement to your callback that outputs the thread name:

Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName());


问:
How to rotate SpriteNode with touch?
How can I rotate a SpriteKit node on a fixed point with touch. So it turns as the user drags his finger. I also want to be able to get the rpm. (This question was asked before but I want to know how to do it using SpriteKit)
Swift 3 Playgrounds

I've got this so far which works but sometimes i get an error for var deltaAngle  = angle - startingAngle!   ERROR - "Unexpectedly found nil while unwrapping optional value"

```<code>class GameScene: SKScene {
var startingAngle:CGFloat?
var startingTime:TimeInterval?

override func didMove(to view: SKView) {
    let wheel = SKSpriteNode(imageNamed: "IMG_6797.PNG" )

    wheel.position = CGPoint(x: 200, y: 200)

    wheel.name = "wheel"
    wheel.setScale(0.5)
    wheel.physicsBody = SKPhysicsBody(circleOfRadius: wheel.size.width/2)
    // Change this property as needed (increase it to slow faster)
    wheel.physicsBody!.angularDamping = 4
    wheel.physicsBody?.pinned = true
    wheel.physicsBody?.affectedByGravity = false
    addChild(wheel)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in:self)
        let node = atPoint(location)
        if node.name == "wheel" {
            let dx = location.x - node.position.x
            let dy = location.y - node.position.y
            // Store angle and current time
            startingAngle = atan2(dy, dx)
            startingTime = touch.timestamp
            node.physicsBody?.angularVelocity = 0
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let location = touch.location(in:self)
        let node = atPoint(location)
        if node.name == "wheel" {
            let dx = location.x - node.position.x
            let dy = location.y - node.position.y

            let angle = atan2(dy, dx)
            // Calculate angular velocity; handle wrap at pi/-pi
            var deltaAngle = angle - startingAngle!
            if abs(deltaAngle) > CGFloat.pi {
                if (deltaAngle > 0) {
                    deltaAngle = deltaAngle - CGFloat.pi * 2
                }
                else {
                    deltaAngle = deltaAngle + CGFloat.pi * 2
                }
            }
            let dt = CGFloat(touch.timestamp - startingTime!)
            let velocity = deltaAngle / dt

            node.physicsBody?.angularVelocity = velocity

            startingAngle = angle
            startingTime = touch.timestamp
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    startingAngle = nil
    startingTime = nil
}
</code>```

}

答:
That error means exactly what it says.  Most likely, "wheel" is not getting touched in touchesBegan, but then registering in touchesMoved, causing startingAngle to not be set to anything and nil.

Since you probably don't want your wheel to spin if the user didn't start touching on the wheel, I would add a guard in touchedMoved

```<code>...
let angle = atan2(dy, dx)

guard startingAngle != nil else {return} //Exit the function if starting angle was never set

var deltaAngle = angle - startingAngle!
...
</code>```

Title: How to rotate SpriteNode with touch?

Body:
How can I rotate a SpriteKit node on a fixed point with touch. So it turns as the user drags his finger. I also want to be able to get the rpm. (This question was asked before but I want to know how to do it using SpriteKit)
Swift 3 Playgrounds

I've got this so far which works but sometimes i get an error for var deltaAngle  = angle - startingAngle!   ERROR - "Unexpectedly found nil while unwrapping optional value"

class GameScene: SKScene {
var startingAngle:CGFloat?
var startingTime:TimeInterval?

override func didMove(to view: SKView) {
    let wheel = SKSpriteNode(imageNamed: "IMG_6797.PNG" )

    wheel.position = CGPoint(x: 200, y: 200)

    wheel.name = "wheel"
    wheel.setScale(0.5)
    wheel.physicsBody = SKPhysicsBody(circleOfRadius: wheel.size.width/2)
    // Change this property as needed (increase it to slow faster)
    wheel.physicsBody!.angularDamping = 4
    wheel.physicsBody?.pinned = true
    wheel.physicsBody?.affectedByGravity = false
    addChild(wheel)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in:self)
        let node = atPoint(location)
        if node.name == "wheel" {
            let dx = location.x - node.position.x
            let dy = location.y - node.position.y
            // Store angle and current time
            startingAngle = atan2(dy, dx)
            startingTime = touch.timestamp
            node.physicsBody?.angularVelocity = 0
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let location = touch.location(in:self)
        let node = atPoint(location)
        if node.name == "wheel" {
            let dx = location.x - node.position.x
            let dy = location.y - node.position.y

            let angle = atan2(dy, dx)
            // Calculate angular velocity; handle wrap at pi/-pi
            var deltaAngle = angle - startingAngle!
            if abs(deltaAngle) > CGFloat.pi {
                if (deltaAngle > 0) {
                    deltaAngle = deltaAngle - CGFloat.pi * 2
                }
                else {
                    deltaAngle = deltaAngle + CGFloat.pi * 2
                }
            }
            let dt = CGFloat(touch.timestamp - startingTime!)
            let velocity = deltaAngle / dt

            node.physicsBody?.angularVelocity = velocity

            startingAngle = angle
            startingTime = touch.timestamp
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    startingAngle = nil
    startingTime = nil
}

}

Body:
That error means exactly what it says.  Most likely, "wheel" is not getting touched in touchesBegan, but then registering in touchesMoved, causing startingAngle to not be set to anything and nil.

Since you probably don't want your wheel to spin if the user didn't start touching on the wheel, I would add a guard in touchedMoved

...
let angle = atan2(dy, dx)

guard startingAngle != nil else {return} //Exit the function if starting angle was never set

var deltaAngle = angle - startingAngle!
...


问:
New Google reCaptcha: How to change text "I'm not a robot"
I've installed the latest Google reCaptcha tool on our yoga website. Now the users are confused about the text "I'm not a robot" that appears next to the checkbox.

Most of our users do not know what the word "robot" means in this context and they think the form is broken. They also feel less safe using our form as it is weird to see the word "robot" on a yoga website.

How do I change the text "I'm not a robot" to something else that the users understand?

The docs appear silent on this point...

Also, it seems like the contents of the reRecaptcha are completely locked down via remote JS and CSS. I've unsuccessfully tried using the following javascript to change the text for Googles recaptcha-anchor-label:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#recaptcha-anchor-label").text("Something different.");
    });
</script>
</code>```

答:
You cannot change that specific text because it belongs to a third party iframe, though there is a workaround that fulfils exactly what the OP is asking for.

You can append a new div on the parent div you can control, aligning and overlapping it on the label text, considering the Google Captcha has always a fixed size. Therefore, according to documentation, considering you may have the main Captcha div on your code with class="g-recaptcha", you simply do:

```<code>$('.g-recaptcha').append('<div id="new_label"></div>');
$('#new_label').text("My own text");
$('#new_label').css({"position":"absolute", "width":"160px", "top":"27px", "left":"53px", "background-color":"#f9f9f9"});
</code>```

it works :)

Body:
You cannot change that specific text because it belongs to a third party iframe, though there is a workaround that fulfils exactly what the OP is asking for.

You can append a new div on the parent div you can control, aligning and overlapping it on the label text, considering the Google Captcha has always a fixed size. Therefore, according to documentation, considering you may have the main Captcha div on your code with class="g-recaptcha", you simply do:

$('.g-recaptcha').append('<div id="new_label"></div>');
$('#new_label').text("My own text");
$('#new_label').css({"position":"absolute", "width":"160px", "top":"27px", "left":"53px", "background-color":"#f9f9f9"});

it works :)


问:
Get visual graph of heap memory usage in Java over a span of time
I am currently using Visual VM to monitor the heap memory usage of my Java application. However I would like to somehow see the heap memory usage over a span of time like for example a day and not just get a snapshot.I would like to be able to leave Visual VM or a tool on and let it log the memory usage and then later after one day, I can go back and see a graph of it. Is there a way to do this using Visual VM? If yes, how? If not, what tool can I used to do this?</p>

答:
Run your Java program with the following Java options:

```<code>-Xloggc:log.out -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
</code>```

and download HPjmeter to visualize log.out.

Also see SUN's GC portal webpage for more options to run with.  Since the data is written to a file, you won't have any problems collecting days or weeks worth of data.  Of course, if you wish to visualize data with lots of information, you'll need to run HPjmeter with more memory.

Your other option is to use JConsole.

ContentLicense: CC BY-SA 2.5

Body:
Run your Java program with the following Java options:

-Xloggc:log.out -XX:+PrintGCDetails -XX:+PrintGCTimeStamps

and download HPjmeter to visualize log.out.

Also see SUN's GC portal webpage for more options to run with.  Since the data is written to a file, you won't have any problems collecting days or weeks worth of data.  Of course, if you wish to visualize data with lots of information, you'll need to run HPjmeter with more memory.

Your other option is to use JConsole.


问:
PHP Mysqli: Multi-key search form
I want to create a form which allows the user to type in a search with different field and have it pick up the right values from a database and display them. For some reasons, I can't figure out know how the search page will be define with Mysqli queries.

How can I create a search.php page that displays a record from a table according to search form and mysqli queries?

Here's what I've tried so far:

PHP Code:

```<code>$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "search";

$DBcon = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);

if ($DBcon->connect_errno) {
    die("ERROR : -> ".$DBcon->connect_error);
}

$output = '';
if(isset($_POST['search'])) {
    $query = mysqli_query($DBcon,"SELECT * FROM data WHERE name LIKE '%" .  $_POST['name'] . "%'
          OR address LIKE '%" . $_POST['address'] . "%'
          OR city LIKE '%" . $_POST['city'] . "%'
          OR state LIKE '%" . $_POST['state'] . "%'") or die ("Could not search");
}
</code>```

HTML Code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MySQL table search</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <style>
        BODY, TD {
            font-family:Arial, Helvetica, sans-serif;
            font-size:12px;
        }
    </style>
</head>

<body>
    <form action ="index.php" method = "post">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address" /></td>
            </tr>
            <tr>
                <td>City:</td>
                <td><input type="text" name="city" /></td>
            </tr>
            <tr>
                <td>State:</td>
                <td><input type="text" name="state" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input name="search" type="submit" value="Search"/></td>
            </tr>
        </table>
    </form>
    <?php echo ("$output");?>
</body>
</html>
</code>```

答:
As per my understanding of your question you who like to search through table in sql and echo the output. So here i have used mysqli with sql LIKE operator to search for pattern as per user.

NOTE : In sql query i have used LIKE tblname %$vars% , you can also use this way %$vars% but both have different meaning . To Know more visit this LINK

Output image is given below :

```<code> <?php

$link = new mysqli ('localhost','root','admin','demo');
if($link->connect_error){
    die("failed to connect".$link->connect_error);
}

?>
<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <form action ="" method = "post">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address" /></td>
            </tr>
            <tr>
                <td>City:</td>
                <td><input type="text" name="city" /></td>
            </tr>
            <tr>
                <td>State:</td>
                <td><input type="text" name="state" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input name="search" type="submit" value="Search"/></td>
            </tr>
        </table>
    </form>

    <?php
        if(isset($_POST['search'])){
            $output = '';
            $name = $_POST['name'];
            $address = $_POST['address'];
            $city = $_POST['city'];
            $state = $_POST['state'];

            $sql = "SELECT name,address,city,state FROM sql_like_operator WHERE name LIKE '%$name%' OR address LIKE '%$address%' OR  city LIKE '%$city%' OR state LIKE '%$state%'";

            $res= $link->query($sql);

            if($res->num_rows > 0){
                while($row = $res->fetch_assoc()){
                    $output .= $row['name']."<br>";
                    $output .= $row['address']."<br>";
                    $output .= $row['city']."<br>";
                    $output .= $row['state']."<br>";
                }
            }
            else
            {
                echo "0 results";
            }
        }
    ?>

    <h5><?php echo @$output;?></h5>
</body>
</html>
</code>```

Title: PHP Mysqli: Multi-key search form

Body:
I want to create a form which allows the user to type in a search with different field and have it pick up the right values from a database and display them. For some reasons, I can't figure out know how the search page will be define with Mysqli queries.

How can I create a search.php page that displays a record from a table according to search form and mysqli queries?

Here's what I've tried so far:

PHP Code:

$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "search";

$DBcon = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);

if ($DBcon->connect_errno) {
    die("ERROR : -> ".$DBcon->connect_error);
}

$output = '';
if(isset($_POST['search'])) {
    $query = mysqli_query($DBcon,"SELECT * FROM data WHERE name LIKE '%" .  $_POST['name'] . "%'
          OR address LIKE '%" . $_POST['address'] . "%'
          OR city LIKE '%" . $_POST['city'] . "%'
          OR state LIKE '%" . $_POST['state'] . "%'") or die ("Could not search");
}

HTML Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MySQL table search</title>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

    <form action ="index.php" method = "post">

                Name:
                <input type="text" name="name" />

                Address:
                <input type="text" name="address" />

                City:
                <input type="text" name="city" />

                State:
                <input type="text" name="state" />

                <input name="search" type="submit" value="Search"/>

    </form>
    <?php echo ("$output");?>

Body:
As per my understanding of your question you who like to search through table in sql and echo the output. So here i have used mysqli with sql LIKE operator to search for pattern as per user.

NOTE : In sql query i have used LIKE tblname %$vars% , you can also use this way %$vars% but both have different meaning . To Know more visit this LINK

Output image is given below :

 <?php

$link = new mysqli ('localhost','root','admin','demo');
if($link->connect_error){
    die("failed to connect".$link->connect_error);
}

?>
<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <form action ="" method = "post">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address" /></td>
            </tr>
            <tr>
                <td>City:</td>
                <td><input type="text" name="city" /></td>
            </tr>
            <tr>
                <td>State:</td>
                <td><input type="text" name="state" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input name="search" type="submit" value="Search"/></td>
            </tr>
        </table>
    </form>

    <?php
        if(isset($_POST['search'])){
            $output = '';
            $name = $_POST['name'];
            $address = $_POST['address'];
            $city = $_POST['city'];
            $state = $_POST['state'];

            $sql = "SELECT name,address,city,state FROM sql_like_operator WHERE name LIKE '%$name%' OR address LIKE '%$address%' OR  city LIKE '%$city%' OR state LIKE '%$state%'";

            $res= $link->query($sql);

            if($res->num_rows > 0){
                while($row = $res->fetch_assoc()){
                    $output .= $row['name']."<br>";
                    $output .= $row['address']."<br>";
                    $output .= $row['city']."<br>";
                    $output .= $row['state']."<br>";
                }
            }
            else
            {
                echo "0 results";
            }
        }
    ?>

    <h5><?php echo @$output;?></h5>
</body>
</html>


问:
Why For cycle, changes the tuple values (Python)
I have the following code:

meses=('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')
    for meses in meses:
        print("- ",meses)
    print (meses)

After the iteration, the tuple now only have one value: Diciembre
I have tried Enumerate, and works pretty well, but I'd like to know, what's happening with the For cycle, why changes the size of the tuple?.

答: You have the same name for looping variable and the list name. So basically meses is the looping variable holding the last value of the original list meses.


问:
Create array from text of selected elements
How do I create an array who's values are the text of selected elements?  For instance, the below HTML should result in array ["test1","test2"].

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Create array</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function(){
                var matched=$('#tbody td.sel');
                console.log(matched);
                console.log(matched.toArray());
                console.log(matched.text());
                //console.log(matched.toArray().text());
            });
        </script>
    </head>
    <body>
        <table>
            <thead>
                <tr><td>Name</td><td>GUID</td></tr>
            </thead>
            <tbody id="tbody">
                <tr><td>Client1</td><td class='sel'>test1</td></tr>
                <tr><td>Client2</td><td class='sel'>test2</td></tr>
            </tbody>
        </table>
    </body>
</html>
</code>```

答:
Here is a non jQuery solution. I had to use call on the result of getElementsByClassName() since it is only "array-like".

a = document.getElementsByClassName('sel');
arr = [];
arr.forEach.call(a, elem => arr.push(elem.innerText));
console.log(arr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Create array</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td>Name</td>
        <td>GUID</td>
      </tr>
    </thead>
    <tbody id="tbody">
      <tr>
        <td>Client1</td>
        <td class='sel'>test1</td>
      </tr>
      <tr>
        <td>Client2</td>
        <td class='sel'>test2</td>
      </tr>
    </tbody>
  </table>
</body>

</html></code>```

Body:
How do I create an array who's values are the text of selected elements?  For instance, the below HTML should result in array ["test1","test2"].

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Create array</title>

Name	GUID

Client1	test1

Client2	test2

Body:
Here is a non jQuery solution. I had to use call on the result of getElementsByClassName() since it is only "array-like".

a = document.getElementsByClassName('sel');
arr = [];
arr.forEach.call(a, elem => arr.push(elem.innerText));
console.log(arr);

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Create array</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td>Name</td>
        <td>GUID</td>
      </tr>
    </thead>
    <tbody id="tbody">
      <tr>
        <td>Client1</td>
        <td class='sel'>test1</td>
      </tr>
      <tr>
        <td>Client2</td>
        <td class='sel'>test2</td>
      </tr>
    </tbody>
  </table>
</body>

</html>


问:
CSS Transition for Website Issue

.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
    }

    .learn-more:hover {
        color: #21C8FF;
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
        background-color: #fff;
        text-decoration: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Learn More</code>```

So I was working on my Website and I added a CSS transition so when you hover over something it fades into a color red. Very simple. I was just using...

transition: .3s ease-in-out;

-webkit-transition: .3s ease-in-out;

But when I unhover it just cuts out. I want to add a transition so it fades back to its original color. Anyone know how to do that?

Thanks!

TrifleTower

答:
Move the transition properties directly under .learn-more and away from the :hover state.

See a sample here:

.the-div {
  width: 200px;
  height: 200px;
  background: limegreen;
  -webkit-transition: 1s ease-in-out;
  -moz-transition: 1s ease-in-out;
  -ms-transition: 1s ease-in-out;
  -o-transition: 1s ease-in-out;
  transition: 1s ease-in-out;
}

.the-div:hover {
  background: #f50;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="the-div"></div></code>```

Title: CSS Transition for Website Issue

Body:
.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
    }

    .learn-more:hover {
        color: #21C8FF;
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
        background-color: #fff;
        text-decoration: none;
    }

Learn More

So I was working on my Website and I added a CSS transition so when you hover over something it fades into a color red. Very simple. I was just using...

transition: .3s ease-in-out;

-webkit-transition: .3s ease-in-out;

But when I unhover it just cuts out. I want to add a transition so it fades back to its original color. Anyone know how to do that?

Thanks!

TrifleTower

Body:
Move the transition properties directly under .learn-more and away from the :hover state.

See a sample here:

.the-div {
  width: 200px;
  height: 200px;
  background: limegreen;
  -webkit-transition: 1s ease-in-out;
  -moz-transition: 1s ease-in-out;
  -ms-transition: 1s ease-in-out;
  -o-transition: 1s ease-in-out;
  transition: 1s ease-in-out;
}

.the-div:hover {
  background: #f50;
}

<div class="the-div"></div>


问:
Arduino serial only works with PuTTY and not pySerial
I am trying to communicate with an Arduino Pro Micro over Serial. I am using pySerial in Python to send commands.

pySerial is not working, however this does work in PuTTY.

```<code># Import libraries
import serial
from time import sleep

# Global Variables
port = 'COM5'
baudrate = 9600

arduino = serial.Serial( port, baudrate, timeout=0 )

# Start Serial interface
try:
    print("Connecting to Arduino on: " + port + " (" + str(baudrate) + ")")
    sleep(3)
    arduino.write( b'cs 4' )
    arduino.write( b'dt 0 0 hi' )
    arduino.flushOutput()
finally:
    arduino.close()
</code>```

答:
Idiot that I am, I forgot to add carriage return and newline to the strings that I  was sending.

I have wasted two hours because I forgot to add \r\n to the end of the strings.
Thank you, @jasonharper for pointing out my stupidity.

I hope you will find amusement from the fact that it took me 2 hours to write 'hi' on a display.

Body:
I am trying to communicate with an Arduino Pro Micro over Serial. I am using pySerial in Python to send commands.

pySerial is not working, however this does work in PuTTY.

# Import libraries
import serial
from time import sleep

# Global Variables
port = 'COM5'
baudrate = 9600

arduino = serial.Serial( port, baudrate, timeout=0 )

# Start Serial interface
try:
    print("Connecting to Arduino on: " + port + " (" + str(baudrate) + ")")
    sleep(3)
    arduino.write( b'cs 4' )
    arduino.write( b'dt 0 0 hi' )
    arduino.flushOutput()
finally:
    arduino.close()


问:
How to sum in Clingo?
I have the following dataset:

```<code>food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
</code>```

I want to satisfy the following constraint: Given a total calorie count, I want to return the food items that satisfy that. For eg. total calorie count = 500, the program should return 'bagel+sandwich' as the solution. I coded he following clingo code:

```<code>food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
has(bagel, wheat).
has(sandwich, bread).
has(sandwich, tomatoes).
has(sandwich, onion).
has(sandwich, cheese).
%calories(food,amount):-food_a(food,amount).
%food(F):-food_a(F,C).
%limits(calories,200).

%sol(F) :- food_a(F,C1),food_a(F,C2), C1+C2<500.
%:- {food(F,C) : food_a(F,C1),food_a(F,C2)} , C1+C2 >500.

%food_diet(F) :- food(F,C), C<250.
%:- food(F1) ,food_a(F2,C2), C1+C2=445.

totals(P, S) :- S = #sum{ I : food_a(P,I)}, food(P), S<500.
</code>```

The output I'm getting is in the screenshot:

Apparently, the program is returning jsut single food items, and not considering the combinations of 2 or 3 of them at a time. Can anyone suggest the changes or steps I must follow to achieve the same.

答:
You are currently doing the sum for each food separately. If you had multiple values for the same food, e.g. food_a(bagel, 100) and food_a(bagel, 200) then the result would be total(bagel, 300). Essentially since you have only one food_a/2 for each food, your totals/2 definition is equivalent to

```<code>totals(P, S) :- food_a(P, S), food(P), S<500.
</code>```

What you want is something like

```<code>food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).

% allow any combination of foods to be selected
{ selected(P) } :- food(P).
% sum calories on selected foods
total(S) :- S = #sum{ I : food_a(P,I), selected(P) }.
% limit total calories
:- total(S), S>=500.

#show selected/1.
#show total/1.
</code>```

Which yields

```<code>> clingo how-to-sum-clingo.asp 0
clingo version 4.5.4
Reading from how-to-sum-clingo.asp
Solving...
Answer: 1
total(0)
Answer: 2
selected(sandwich) total(200)
Answer: 3
selected(bagel) total(245)
Answer: 4
selected(bagel) selected(sandwich) total(445)
Answer: 5
selected(salad) total(300)
SATISFIABLE

Models       : 5
Calls        : 1
Time         : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s
</code>```

Title: How to sum in Clingo?

Body:
I have the following dataset:

food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).

I want to satisfy the following constraint: Given a total calorie count, I want to return the food items that satisfy that. For eg. total calorie count = 500, the program should return 'bagel+sandwich' as the solution. I coded he following clingo code:

food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
has(bagel, wheat).
has(sandwich, bread).
has(sandwich, tomatoes).
has(sandwich, onion).
has(sandwich, cheese).
%calories(food,amount):-food_a(food,amount).
%food(F):-food_a(F,C).
%limits(calories,200).

%sol(F) :- food_a(F,C1),food_a(F,C2), C1+C2<500.
%:- {food(F,C) : food_a(F,C1),food_a(F,C2)} , C1+C2 >500.

%food_diet(F) :- food(F,C), C<250.
%:- food(F1) ,food_a(F2,C2), C1+C2=445.

totals(P, S) :- S = #sum{ I : food_a(P,I)}, food(P), S<500.

The output I'm getting is in the screenshot:

Apparently, the program is returning jsut single food items, and not considering the combinations of 2 or 3 of them at a time. Can anyone suggest the changes or steps I must follow to achieve the same.

Body:
You are currently doing the sum for each food separately. If you had multiple values for the same food, e.g. food_a(bagel, 100) and food_a(bagel, 200) then the result would be total(bagel, 300). Essentially since you have only one food_a/2 for each food, your totals/2 definition is equivalent to

totals(P, S) :- food_a(P, S), food(P), S<500.

What you want is something like

food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).

% allow any combination of foods to be selected
{ selected(P) } :- food(P).
% sum calories on selected foods
total(S) :- S = #sum{ I : food_a(P,I), selected(P) }.
% limit total calories
:- total(S), S>=500.

#show selected/1.
#show total/1.

Which yields

> clingo how-to-sum-clingo.asp 0
clingo version 4.5.4
Reading from how-to-sum-clingo.asp
Solving...
Answer: 1
total(0)
Answer: 2
selected(sandwich) total(200)
Answer: 3
selected(bagel) total(245)
Answer: 4
selected(bagel) selected(sandwich) total(445)
Answer: 5
selected(salad) total(300)
SATISFIABLE

Models       : 5
Calls        : 1
Time         : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s


问:
how i can count the element who have the class "goo"
i want to check how much element have class "goo".

are i can check for specific element or all using jQuery. show me how i can do this task in jQuery

答: You can use the .length property. So something like var total = $('.goo').length; should do the trick.

OwnerDisplayName: Steven Spielberg


问:
How do I get an ISO 8601 date on iOS?
It's easy enough to get the ISO 8601 date string (for example, 2004-02-12T15:19:21+00:00) in PHP via date('c'), but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?

Here's the long way I found to do it:

```<code>NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);

// Output: ISO-8601 date: 2013-04-27T13:27:50-0700
</code>```

It seems an awful lot of rigmarole for something so central.

答:
Using Swift 3.0 and iOS 9.0</p>

```<code>extension Date {
    private static let jsonDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(identifier: "UTC")!
        return formatter
    }()

    var IOS8601String: String {
        get {
            return Date.jsonDateFormatter.string(from: self)
        }
    }

    init?(fromIOS8601 dateString: String) {
        if let d = Date.jsonDateFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since:d)
        } else {
            return nil
        }
    }
}
</code>```

Title: How do I get an ISO 8601 date on iOS?

Body:
It's easy enough to get the ISO 8601 date string (for example, 2004-02-12T15:19:21+00:00) in PHP via date('c'), but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?

Here's the long way I found to do it:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);

// Output: ISO-8601 date: 2013-04-27T13:27:50-0700

It seems an awful lot of rigmarole for something so central.

Body:
Using Swift 3.0 and iOS 9.0

extension Date {
    private static let jsonDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(identifier: "UTC")!
        return formatter
    }()

    var IOS8601String: String {
        get {
            return Date.jsonDateFormatter.string(from: self)
        }
    }

    init?(fromIOS8601 dateString: String) {
        if let d = Date.jsonDateFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since:d)
        } else {
            return nil
        }
    }
}


问:
Swagger UI Displays but I get an "ERROR" indicator
My swagger UI displays and it is showing all of my routes. Everything looks great except there is a big red ERROR indicator on the lower right. When I click it I get:

```<code>{
  "schemaValidationMessages":[
     {
       "level":"error",
       "message":"Can't read from file http://devxxxx.com:80/swagger/docs/v1"
     }
   ]
}
</code>```

How do I fix this error?

答:
That's the validator badge.  The error is most likely because the on-line validator can't reach the OpenAPI spec on your server (devxxxx.com).  I am assuming this server is behind a firewall.

Depending on the version of Swagger UI, you may be able to disable the validator badge.  In 2.x, you can simply add validatorUrl: null to the SwaggerUi constructor in index.html.  In 3.x, there have been problems disabling the validator badge.  For more details search for validatorUrl issues over on GitHub.

Body:
My swagger UI displays and it is showing all of my routes. Everything looks great except there is a big red ERROR indicator on the lower right. When I click it I get:

{
  "schemaValidationMessages":[
     {
       "level":"error",
       "message":"Can't read from file http://devxxxx.com:80/swagger/docs/v1"
     }
   ]
}

How do I fix this error?


问:
C typedef const argument
```<code>typedef float vec3[3];

void test(vec3 const vptr) {
    *vptr = 1.f; // error: assignment of read-only location
    vptr[0] = 1.f; // error: assignment of read-only location
    vptr++; // no error
}
</code>```

Is

```<code>vec3 const vptr
</code>```

the same as

```<code>const vec3 vptr
</code>```

for all typedefs? Is there any difference between last two? I thought

```<code>vec3 const vptr <==> float* const vptr // a constant pointer to an object
const vec3 vptr <==> const float* vptr // a pointer to a constant object
??? <==> const float* const vptr // a constant pointer to a constant object
</code>```

答:
This typedef

```<code>typedef float vec3[3];
</code>```

defines an alias for the array type float[3]

This declaration of the parameter

```<code>vec3 const vptr
</code>```

declares vptr as having array type const float[3].

Function parameters that are specified as having array types are adjusted to pointers to objects of the array element types.

So this declaration

```<code>vec3 const vptr
</code>```

is adjusted to the type const float *vptr. That is it is a non constant pointer to a constant object.

This relation

vec3 const vptr <==> float* const vptr // a constant pointer to an
  object

is wrong. And this statement

```<code>vptr++; // no error
</code>```

confirms that.

You can not get this declaration

```<code>const float* const vptr
</code>```

using this typedef

```<code>typedef float vec3[3];
</code>```

Title: C typedef const argument

Body:
typedef float vec3[3];

void test(vec3 const vptr) {
    *vptr = 1.f; // error: assignment of read-only location
    vptr[0] = 1.f; // error: assignment of read-only location
    vptr++; // no error
}

Is

vec3 const vptr

the same as

const vec3 vptr

for all typedefs? Is there any difference between last two? I thought

vec3 const vptr <==> float* const vptr // a constant pointer to an object
const vec3 vptr <==> const float* vptr // a pointer to a constant object
??? <==> const float* const vptr // a constant pointer to a constant object

Body:
This typedef

typedef float vec3[3];

defines an alias for the array type float[3]

This declaration of the parameter

vec3 const vptr

declares vptr as having array type const float[3].

Function parameters that are specified as having array types are adjusted to pointers to objects of the array element types.

So this declaration

vec3 const vptr

is adjusted to the type const float *vptr. That is it is a non constant pointer to a constant object.

This relation

vec3 const vptr <==> float* const vptr // a constant pointer to an
  object

is wrong. And this statement

vptr++; // no error

confirms that.

You can not get this declaration

const float* const vptr

using this typedef

typedef float vec3[3];


问:
Ajax error on retrieving values using ms mvc
I have these codes:

Contact Class

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace mvccrud
{
    [MetadataType(typeof(ContactMetaData))]
    public partial class Contact
    {
        public string CountryName { get; set; }
        public string StateName { get; set; }
    }

    public class ContactMetaData
    {
        [Required(ErrorMessage = "Contact Person required", AllowEmptyStrings = false)]
        [Display(Name = "Contact Person")]
        public string ContactPerson { get; set; }

        [Required(ErrorMessage = "Contact No required", AllowEmptyStrings = false)]
        [Display(Name = "Contact No")]
        public string ContactNo { get; set; }

        [Required(ErrorMessage = "Country required")]
        [Display(Name = "Country")]
        public int CountryID { get; set; }

        [Required(ErrorMessage = "State required")]
        [Display(Name = "State")]
        public int StateID { get; set; }
    }
}
</code>```

ContactsController

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace mvccrud.Controllers
{
    public class ContactsController : Controller
    {

        /// <summary>
        /// Get All Contacts
        /// </summary>
        /// <returns>Views/Contacts/Index</returns>
        public ActionResult Index()
        {
            List<Contact> allContacts = null;
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         select new
                         {
                             a,
                             b.CountryName,
                             c.StateName
                         });
                if (v != null)
                {
                    allContacts = new List<Contact>();
                    foreach (var i in v)
                    {
                        Contact c = i.a;
                        c.CountryName = i.CountryName;
                        c.StateName = i.StateName;
                        allContacts.Add(c);
                    }
                }
            }
            return View(allContacts);
        }

        /// <summary>
        /// Create and Update part of the CRUD
        /// Populate the Country List
        /// </summary>
        /// <returns>Countries in Descending Order</returns>
        private List<Country> GetCountry()
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                return dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
        }

        /// <summary>
        /// Populate the State List
        /// </summary>
        /// <param name="countryID"></param>
        /// <returns>State name based on the countryID</returns>
        private List<State> GetState(int countryID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateID).ToList();
            }
        }

        /// <summary>
        /// Gets the state list but in JSON Format
        /// </summary>
        /// <param name="countryID"></param>
        /// <returns>state list in Json format</returns>
        public JsonResult GetStateList(int countryID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {

                return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }

        /// <summary>
        /// Populate contacts information from database based on contactID
        /// </summary>
        /// <param name="contactID"></param>
        /// <returns>contact information</returns>
        public Contact GetContact(int contactID)
        {
            Contact contact = null;
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         where a.ContactID.Equals(contactID)
                         select new
                         {
                             a,
                             b.CountryName,
                             c.StateName
                         }).FirstOrDefault();
                if (v != null)
                {
                    contact = v.a;
                    contact.CountryName = v.CountryName;
                    contact.StateName = v.StateName;
                }
                return contact;
            }
        }

        /// <summary>
        /// updating contact information
        /// </summary>
        /// <param name="id"></param>
        /// <returns>View/Contacts/Save</returns>
        public ActionResult Save(int id = 0)
        {
            List<Country> country = GetCountry();
            List<State> states = new List<State>();
            if (id > 0)
            {
                //Update
                var c = GetContact(id);
                if (c != null)
                {
                    ViewBag.Countries = new SelectList(country, "CountryID", "CountryName", c.CountryID);
                    ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
                }
                else
                {
                    return HttpNotFound();
                }
                return View(c);
            }
            else
            {
                //Create
                ViewBag.Countries = new SelectList(country, "CountryID", "CountryName");
                ViewBag.States = new SelectList(states, "StateID", "StateName");
                return View();
            }
        }

        /// <summary>
        /// save created contact
        /// </summary>
        /// <param name="c"></param>
        /// <returns>View/Contacts/Save</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(Contact c)
        {
            string message = "";
            bool status = false;

            //Save
            if (ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    if (c.ContactID > 0)
                    {
                        //Update
                        var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
                        if (v != null)
                        {
                            v.ContactPerson = c.ContactPerson;
                            v.ContactNo = c.ContactNo;
                            v.CountryID = c.CountryID;
                            v.StateID = c.StateID;
                        }
                        else
                        {
                            return HttpNotFound();
                        }
                    }
                    else
                    {
                        //Add new
                        dc.Contacts.Add(c);
                    }
                    dc.SaveChanges();
                    status = true;
                    return RedirectToAction("Index");
                }
            }
            else
            {
                message = "Error! Please try again.";
                ViewBag.Countries = new SelectList(GetCountry(), "CountryID", "CountryName", c.CountryID);
                ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
            }
            ViewBag.Message = message;
            ViewBag.Status = status;
            return View(c);
        }
    }
}
</code>```

Save.chstml

```<code>@model mvccrud.Contact

@{
    ViewBag.Title = "Save";
}

<h2>Save</h2>
@using (Html.BeginForm("Save", "Contacts", FormMethod.Post, new { role = "form" }))
{
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()

    <div class="form-group">
        @if (Model != null)
        {
            @Html.HiddenFor(a => a.ContactID)
        }

        @Html.LabelFor(a => a.ContactPerson)
        @Html.TextBoxFor(a => a.ContactPerson, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.ContactPerson)
    </div>
    <div class="form-group">
        @Html.LabelFor(a => a.ContactNo)
        @Html.TextBoxFor(a => a.ContactNo, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.ContactNo)
    </div>
    <div class="form-group">
        @Html.LabelFor(a => a.CountryID)
        @Html.DropDownListFor(a => a.CountryID, ViewBag.Countries as SelectList, "Select Country", new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.CountryID)
    </div>
    <div class="form-group">
        @Html.LabelFor(a => a.StateID)
        @Html.DropDownListFor(a => a.StateID, ViewBag.States as SelectList, "Select State", new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.StateID)
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    @Html.ActionLink("Back to List", "Index", null, new { @style = "padding-left:50px; font-weight:bold;" })
}

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(document).ready(function () {
            $('#CountryID').change(function () {
                var countryID = $(this).val();
                var $state = $('#StateID');
                $state.empty();
                $state.append($('<option></option>').val('').html('Please Wait...'));

                if (countryID =="") {
                    $state.empty();
                    $state.append($('<option></option>').val('').html('Select State'));
                    return;
                }

                $.ajax({
                    url: '/Contacts/GetStateList',
                    type: 'GET',
                    data: { 'countryID': countryID },
                    dataType: 'json',
                    success: function (d) {
                        $state.empty();
                        $state.append($('<option></option>').val('').html('Select State'));
                        $.each(d, function (i, val) {
                            $state.append($('<option></option>').val(val.StateID).html(val.StateName));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                    }
                });
            });
        });
    </script>
}
</code>```

When you select a country in the countries dropdown list, the states dropdownlist should populate with the states. This is not so with mine. I only get the 500 error when I get the ajax data.
When I inspect the element, this is what I get:

```<code>GET http://localhost:5826/Contacts/GetStateList?countryID=5 500 (Internal Server Error)
send @ jquery-3.1.1.js:9536
ajax @ jquery-3.1.1.js:9143
(anonymous) @ Save:108
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
ListPicker._handleMouseUp @ about:blank:557
browserLink:37 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ browserLink:37
ajax @ browserLink:37
ajaxAbort @ browserLink:62
abort @ browserLink:62
stop @ browserLink:62
(anonymous) @ browserLink:62
dispatch @ browserLink:37
h @ browserLink:37
Navigated to http://localhost:5826/Contacts/Save
jquery-3.1.1.js:3846 jQuery.Deferred exception: $(...).parents(...).andSelf is not a function TypeError: $(...).parents(...).andSelf is not a function
    at Object.parse (http://localhost:5826/Scripts/jquery.validate.unobtrusive.js:211:18)
    at HTMLDocument.<anonymous> (http://localhost:5826/Scripts/jquery.validate.unobtrusive.js:379:28)
    at mightThrow (http://localhost:5826/Scripts/jquery-3.1.1.js:3570:29)
    at process (http://localhost:5826/Scripts/jquery-3.1.1.js:3638:12) undefined
jQuery.Deferred.exceptionHook @ jquery-3.1.1.js:3846
process @ jquery-3.1.1.js:3642
jquery-3.1.1.js:3855 Uncaught TypeError: $(...).parents(...).andSelf is not a function
    at Object.parse (jquery.validate.unobtrusive.js:211)
    at HTMLDocument.<anonymous> (jquery.validate.unobtrusive.js:379)
    at mightThrow (jquery-3.1.1.js:3570)
    at process (jquery-3.1.1.js:3638)
parse @ jquery.validate.unobtrusive.js:211
(anonymous) @ jquery.validate.unobtrusive.js:379
mightThrow @ jquery-3.1.1.js:3570
process @ jquery-3.1.1.js:3638
jquery-3.1.1.js:9536 GET http://localhost:5826/Contacts/GetStateList?countryID=5 500 (Internal Server Error)
send @ jquery-3.1.1.js:9536
ajax @ jquery-3.1.1.js:9143
(anonymous) @ Save:108
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
ListPicker._handleMouseUp @ about:blank:557
</code>```

Thank you very much for the help.

答:
In your GetState method replace the return with:

```<code>return Json(new { Data = GetState(countryID) }, JsonRequestBehavior.AllowGet);
</code>```

On your success method you shoud have also d.Data:

```<code>$.ajax({
    url: '/Contacts/GetStateList',
    type: 'GET',
    data: { 'countryID': countryID },
    dataType: 'json',
    success: function (d) {
        $state.empty();
        $state.append($('<option></option>').val('').html('Select State'));
        $.each(d.Data, function (i, item) {
            $state.append($('<option></option>').val(item.StateID).html(item.StateName));
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
    }
});
</code>```

Body:
I have these codes:

Contact Class

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace mvccrud
{
    [MetadataType(typeof(ContactMetaData))]
    public partial class Contact
    {
        public string CountryName { get; set; }
        public string StateName { get; set; }
    }

    public class ContactMetaData
    {
        [Required(ErrorMessage = "Contact Person required", AllowEmptyStrings = false)]
        [Display(Name = "Contact Person")]
        public string ContactPerson { get; set; }

        [Required(ErrorMessage = "Contact No required", AllowEmptyStrings = false)]
        [Display(Name = "Contact No")]
        public string ContactNo { get; set; }

        [Required(ErrorMessage = "Country required")]
        [Display(Name = "Country")]
        public int CountryID { get; set; }

        [Required(ErrorMessage = "State required")]
        [Display(Name = "State")]
        public int StateID { get; set; }
    }
}

ContactsController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace mvccrud.Controllers
{
    public class ContactsController : Controller
    {

        ///
        /// Get All Contacts
        ///
        /// <returns>Views/Contacts/Index</returns>
        public ActionResult Index()
        {
            List<Contact> allContacts = null;
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         select new
                         {
                             a,
                             b.CountryName,
                             c.StateName
                         });
                if (v != null)
                {
                    allContacts = new List<Contact>();
                    foreach (var i in v)
                    {
                        Contact c = i.a;
                        c.CountryName = i.CountryName;
                        c.StateName = i.StateName;
                        allContacts.Add(c);
                    }
                }
            }
            return View(allContacts);
        }

        ///
        /// Create and Update part of the CRUD
        /// Populate the Country List
        ///
        /// <returns>Countries in Descending Order</returns>
        private List<Country> GetCountry()
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                return dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
        }

        ///
        /// Populate the State List
        ///
        /// <param name="countryID"></param>
        /// <returns>State name based on the countryID</returns>
        private List<State> GetState(int countryID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateID).ToList();
            }
        }

        ///
        /// Gets the state list but in JSON Format
        ///
        /// <param name="countryID"></param>
        /// <returns>state list in Json format</returns>
        public JsonResult GetStateList(int countryID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {

                return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }

        ///
        /// Populate contacts information from database based on contactID
        ///
        /// <param name="contactID"></param>
        /// <returns>contact information</returns>
        public Contact GetContact(int contactID)
        {
            Contact contact = null;
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         where a.ContactID.Equals(contactID)
                         select new
                         {
                             a,
                             b.CountryName,
                             c.StateName
                         }).FirstOrDefault();
                if (v != null)
                {
                    contact = v.a;
                    contact.CountryName = v.CountryName;
                    contact.StateName = v.StateName;
                }
                return contact;
            }
        }

        ///
        /// updating contact information
        ///
        /// <param name="id"></param>
        /// <returns>View/Contacts/Save</returns>
        public ActionResult Save(int id = 0)
        {
            List<Country> country = GetCountry();
            List<State> states = new List<State>();
            if (id > 0)
            {
                //Update
                var c = GetContact(id);
                if (c != null)
                {
                    ViewBag.Countries = new SelectList(country, "CountryID", "CountryName", c.CountryID);
                    ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
                }
                else
                {
                    return HttpNotFound();
                }
                return View(c);
            }
            else
            {
                //Create
                ViewBag.Countries = new SelectList(country, "CountryID", "CountryName");
                ViewBag.States = new SelectList(states, "StateID", "StateName");
                return View();
            }
        }

        ///
        /// save created contact
        ///
        /// <param name="c"></param>
        /// <returns>View/Contacts/Save</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(Contact c)
        {
            string message = "";
            bool status = false;

            //Save
            if (ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    if (c.ContactID > 0)
                    {
                        //Update
                        var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
                        if (v != null)
                        {
                            v.ContactPerson = c.ContactPerson;
                            v.ContactNo = c.ContactNo;
                            v.CountryID = c.CountryID;
                            v.StateID = c.StateID;
                        }
                        else
                        {
                            return HttpNotFound();
                        }
                    }
                    else
                    {
                        //Add new
                        dc.Contacts.Add(c);
                    }
                    dc.SaveChanges();
                    status = true;
                    return RedirectToAction("Index");
                }
            }
            else
            {
                message = "Error! Please try again.";
                ViewBag.Countries = new SelectList(GetCountry(), "CountryID", "CountryName", c.CountryID);
                ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
            }
            ViewBag.Message = message;
            ViewBag.Status = status;
            return View(c);
        }
    }
}

Save.chstml

@model mvccrud.Contact

@{
    ViewBag.Title = "Save";
}

Save

@using (Html.BeginForm("Save", "Contacts", FormMethod.Post, new { role = "form" }))
{
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()

        @if (Model != null)
        {
            @Html.HiddenFor(a => a.ContactID)
        }

        @Html.LabelFor(a => a.ContactPerson)
        @Html.TextBoxFor(a => a.ContactPerson, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.ContactPerson)

        @Html.LabelFor(a => a.ContactNo)
        @Html.TextBoxFor(a => a.ContactNo, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.ContactNo)

        @Html.LabelFor(a => a.CountryID)
        @Html.DropDownListFor(a => a.CountryID, ViewBag.Countries as SelectList, "Select Country", new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.CountryID)

        @Html.LabelFor(a => a.StateID)
        @Html.DropDownListFor(a => a.StateID, ViewBag.States as SelectList, "Select State", new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.StateID)

    <button type="submit" class="btn btn-default">Submit</button>
    @Html.ActionLink("Back to List", "Index", null, new { @style = "padding-left:50px; font-weight:bold;" })
}

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")

}

When you select a country in the countries dropdown list, the states dropdownlist should populate with the states. This is not so with mine. I only get the 500 error when I get the ajax data.
When I inspect the element, this is what I get:

GET http://localhost:5826/Contacts/GetStateList?countryID=5 500 (Internal Server Error)
send @ jquery-3.1.1.js:9536
ajax @ jquery-3.1.1.js:9143
(anonymous) @ Save:108
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
ListPicker._handleMouseUp @ about:blank:557
browserLink:37 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ browserLink:37
ajax @ browserLink:37
ajaxAbort @ browserLink:62
abort @ browserLink:62
stop @ browserLink:62
(anonymous) @ browserLink:62
dispatch @ browserLink:37
h @ browserLink:37
Navigated to http://localhost:5826/Contacts/Save
jquery-3.1.1.js:3846 jQuery.Deferred exception: $(...).parents(...).andSelf is not a function TypeError: $(...).parents(...).andSelf is not a function
    at Object.parse (http://localhost:5826/Scripts/jquery.validate.unobtrusive.js:211:18)
    at HTMLDocument.<anonymous> (http://localhost:5826/Scripts/jquery.validate.unobtrusive.js:379:28)
    at mightThrow (http://localhost:5826/Scripts/jquery-3.1.1.js:3570:29)
    at process (http://localhost:5826/Scripts/jquery-3.1.1.js:3638:12) undefined
jQuery.Deferred.exceptionHook @ jquery-3.1.1.js:3846
process @ jquery-3.1.1.js:3642
jquery-3.1.1.js:3855 Uncaught TypeError: $(...).parents(...).andSelf is not a function
    at Object.parse (jquery.validate.unobtrusive.js:211)
    at HTMLDocument.<anonymous> (jquery.validate.unobtrusive.js:379)
    at mightThrow (jquery-3.1.1.js:3570)
    at process (jquery-3.1.1.js:3638)
parse @ jquery.validate.unobtrusive.js:211
(anonymous) @ jquery.validate.unobtrusive.js:379
mightThrow @ jquery-3.1.1.js:3570
process @ jquery-3.1.1.js:3638
jquery-3.1.1.js:9536 GET http://localhost:5826/Contacts/GetStateList?countryID=5 500 (Internal Server Error)
send @ jquery-3.1.1.js:9536
ajax @ jquery-3.1.1.js:9143
(anonymous) @ Save:108
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
ListPicker._handleMouseUp @ about:blank:557

Thank you very much for the help.

Body:
In your GetState method replace the return with:

return Json(new { Data = GetState(countryID) }, JsonRequestBehavior.AllowGet);

On your success method you shoud have also d.Data:

$.ajax({
    url: '/Contacts/GetStateList',
    type: 'GET',
    data: { 'countryID': countryID },
    dataType: 'json',
    success: function (d) {
        $state.empty();
        $state.append($('<option></option>').val('').html('Select State'));
        $.each(d.Data, function (i, item) {
            $state.append($('<option></option>').val(item.StateID).html(item.StateName));
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
    }
});


问:
Qt compiler error when trying to use QQmlListProperty
I'm trying to use QQmlListProperty to expose a QList from within a QQuickItem - and following the documentation at:

Properties with Object-List Types

QQmlListProperty Class

A simplified example:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QList>
#include <QQmlListProperty>

class GameEngine : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<QObject> vurms READ vurms)

public:
    explicit GameEngine(QQuickItem *parent = 0) :
        QQuickItem(parent)
    {
    }

    QQmlListProperty<QObject> vurms() const
    {
        return QQmlListProperty<QObject>(this, &m_vurms);
    }

protected:
    QList<QObject*> m_vurms;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    return app.exec();
}

#include "main.moc"
</code>```

But I'm getting a compiler error on return QQmlListProperty<QObject>(this, &m_vurms);:

```<code>main.cpp:20: error: C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'QQmlListProperty<QObject>'
</code>```

I've also tried replacing the QList of Vurm with a QList of int - the problem seems to be in whatever Qt is doing in QQmlListProperty<T>(this, &m_vurms);

I am writing/compiling using Qt 5.8 and C++11 is set in the .pro file. I'm compiling in Qt Creator 4.2.1 on Windows 10: using MSVC 2015 64-bit for compiling.

答:
I missed this earlier, but you need to pass a reference as the second argument to the constructor, not a pointer:

```<code>QQmlListProperty<Vurm> GameEngine::vurms()
{
    return QQmlListProperty<Vurm>(this, m_vurms);
}
</code>```

I also had to remove the const qualifier to get it to compile, which makes sense, given that the constructor of QQmlListProperty expects a non-const pointer. The error probably remained when you tried removing it because you were still passing a pointer.

Body:
I'm trying to use QQmlListProperty to expose a QList from within a QQuickItem - and following the documentation at:

Properties with Object-List Types

QQmlListProperty Class

A simplified example:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QList>
#include <QQmlListProperty>

class GameEngine : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<QObject> vurms READ vurms)

public:
    explicit GameEngine(QQuickItem *parent = 0) :
        QQuickItem(parent)
    {
    }

    QQmlListProperty<QObject> vurms() const
    {
        return QQmlListProperty<QObject>(this, &m_vurms);
    }

protected:
    QList<QObject*> m_vurms;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    return app.exec();
}

#include "main.moc"

But I'm getting a compiler error on return QQmlListProperty<QObject>(this, &m_vurms);:

main.cpp:20: error: C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'QQmlListProperty<QObject>'

I've also tried replacing the QList of Vurm with a QList of int - the problem seems to be in whatever Qt is doing in QQmlListProperty<T>(this, &m_vurms);

I am writing/compiling using Qt 5.8 and C++11 is set in the .pro file. I'm compiling in Qt Creator 4.2.1 on Windows 10: using MSVC 2015 64-bit for compiling.

Body:
I missed this earlier, but you need to pass a reference as the second argument to the constructor, not a pointer:

QQmlListProperty<Vurm> GameEngine::vurms()
{
    return QQmlListProperty<Vurm>(this, m_vurms);
}

I also had to remove the const qualifier to get it to compile, which makes sense, given that the constructor of QQmlListProperty expects a non-const pointer. The error probably remained when you tried removing it because you were still passing a pointer.


问:
Best way to replace part of array with another array
I'm looking for the most pythonic way of doing something like that:</p>

```<code>a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c = replace(a,b,2)

c is now [1,2,'a','b','c',6,7,8]
</code>```

答:
you can slice your list accordingly!

That is, with a and b being your initial list and the one that you want to replace from index s, a[:s] will get all elements before from 0 to s that is ([1,2]).

a[s+len(b):]  will get all items from index s to len(b), that is ([6,7,8])

so when you concatenate the first result along with b and then the second result you can get the desired output!

a[:s]+b+a[s+len(b):]

So,

```<code>>>> a = [1,2,3,4,5,6,7,8]
>>> b = ['a','b','c']
>>> replace=lambda a,b,s:a[:s]+b+a[s+len(b):]
>>> c = replace(a,b,2)
>>> print c
[1, 2, 'a', 'b', 'c', 6, 7, 8]
</code>```

Hope this helps!

Body:
I'm looking for the most pythonic way of doing something like that:

a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c = replace(a,b,2)

c is now [1,2,'a','b','c',6,7,8]

Body:
you can slice your list accordingly!

That is, with a and b being your initial list and the one that you want to replace from index s, a[:s] will get all elements before from 0 to s that is ([1,2]).

a[s+len(b):]  will get all items from index s to len(b), that is ([6,7,8])

so when you concatenate the first result along with b and then the second result you can get the desired output!

a[:s]+b+a[s+len(b):]

So,

>>> a = [1,2,3,4,5,6,7,8]
>>> b = ['a','b','c']
>>> replace=lambda a,b,s:a[:s]+b+a[s+len(b):]
>>> c = replace(a,b,2)
>>> print c
[1, 2, 'a', 'b', 'c', 6, 7, 8]

Hope this helps!


问:
Explicit cast reading .csv with case class Spark 2.1.0
I have the following case class:

```<code>case class OrderDetails(OrderID : String, ProductID : String, UnitPrice : Double,
                    Qty : Int, Discount : Double)
</code>```

I am trying read this csv: https://github.com/xsankar/fdps-v3/blob/master/data/NW-Order-Details.csv

This is my code:

```<code>val spark = SparkSession.builder.master(sparkMaster).appName(sparkAppName).getOrCreate()
import spark.implicits._
val orderDetails = spark.read.option("header","true").csv( inputFiles + "NW-Order-Details.csv").as[OrderDetails]
</code>```

And the error is:

```<code> Exception in thread "main" org.apache.spark.sql.AnalysisException:
 Cannot up cast `UnitPrice` from string to double as it may truncate
 The type path of the target object is:
  - field (class: "scala.Double", name: "UnitPrice")
  - root class: "es.own3dh2so4.OrderDetails"
 You can either add an explicit cast to the input data or choose a higher precision type of the field in the target object;
</code>```

Why can not it be transformed if all fields are "doubles" values? What do not I understand?

Spark version 2.1.0, Scala version 2.11.7

答:
You just need to explicitly cast your field to a Double:

```<code>val orderDetails = spark.read
   .option("header","true")
   .csv( inputFiles + "NW-Order-Details.csv")
   .withColumn("unitPrice", 'UnitPrice.cast(DoubleType))
   .as[OrderDetails]
</code>```

On a side note, by Scala (and Java) convention, your case class constructor parameters should be lower camel case:

```<code>case class OrderDetails(orderID: String,
                        productID: String,
                        unitPrice: Double,
                        qty: Int,
                        discount: Double)
</code>```

Body:
I have the following case class:

case class OrderDetails(OrderID : String, ProductID : String, UnitPrice : Double,
                    Qty : Int, Discount : Double)

I am trying read this csv: https://github.com/xsankar/fdps-v3/blob/master/data/NW-Order-Details.csv

This is my code:

val spark = SparkSession.builder.master(sparkMaster).appName(sparkAppName).getOrCreate()
import spark.implicits._
val orderDetails = spark.read.option("header","true").csv( inputFiles + "NW-Order-Details.csv").as[OrderDetails]

And the error is:

 Exception in thread "main" org.apache.spark.sql.AnalysisException:
 Cannot up cast `UnitPrice` from string to double as it may truncate
 The type path of the target object is:
  - field (class: "scala.Double", name: "UnitPrice")
  - root class: "es.own3dh2so4.OrderDetails"
 You can either add an explicit cast to the input data or choose a higher precision type of the field in the target object;

Why can not it be transformed if all fields are "doubles" values? What do not I understand?

Spark version 2.1.0, Scala version 2.11.7

Body:
You just need to explicitly cast your field to a Double:

val orderDetails = spark.read
   .option("header","true")
   .csv( inputFiles + "NW-Order-Details.csv")
   .withColumn("unitPrice", 'UnitPrice.cast(DoubleType))
   .as[OrderDetails]

On a side note, by Scala (and Java) convention, your case class constructor parameters should be lower camel case:

case class OrderDetails(orderID: String,
                        productID: String,
                        unitPrice: Double,
                        qty: Int,
                        discount: Double)


问:
How to encrypt connection string without app.config
Assume that app.config is, for whatever reason, not an option.

How is possible to store an encrypted connection string, either in the assembly itself or another app.config like XML file?

(I don't think it matters, but this is for an COM add-in for Excel 2003.)

答:
This can be good application of isolated storage.

http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx


问:
Install PHP Curl on Windows and Using it on Laravel 5.4
I am using Laravel 5.4 on Windows 10. How to install PHP Curl on Windows and using it on Laravel?</p>

答:
Use the following steps to install curl:

Open https://curl.haxx.se/dlwiz?type=bin in a browser.

Select your operating system in the dropdown box: either Windows /Win32 or Win 64. Click Select!

For Win 32, choose whether you will use curl in a Windows Command Prompt (Generic) or in a Cygwin terminal (cygwin).
For Win 64, choose whether you will use curl in a Windows Command Prompt (Generic) or MinGW (MinGW64). Click Select!

If required, choose your Windows operating system. Finish.

Click Download for the version which has SSL enabled or disabled

Open the downloaded zip file. Extract the files to an easy-to-find place, such as C:\Program Files.

Testing curl

Open up the Windows Command Prompt terminal. (From the Start menu, click Run, then type cmd.)

Set the path to include the directory where you put curl.exe. For example, if you put it in C:\Program Files\curl, then you would type the following command: set path=%path%;"c:\Program Files\curl"

NOTE: You can also directly copy the curl.exe file any existing path in your path

Type curl. You should see the following message: curl: try 'curl –help' or 'curl –message' for more information This means that curl is installed and the path is correct.


问:
Javascript / JQuery Toggle Active Class between 2 buttons on a button group
I am using bootstrap with btn-group. There is the html:

```<code><div class="btn-group btn-group-sm" role="group">
    <div type="button" class="btn btn-default btn-1">Button 1</div>
    <div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>
</code>```

Button 2 it already active.

Currently I'm doing this to remove the active class from one and add it to another.

```<code>$('.btn-2').removeClass('active');
$('.btn-1').addClass('active');
</code>```

Is this the cleanest way to do this or is there a better way so it can just toggle this active class between the two buttons?

答:
Use:

```<code>$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});
</code>```

I think the code is fairly self-explanatory? It simply removes any existing "active" classes from the siblings of the button you clicked, and adds that class to the clicked button.

Here's a working snippet:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="btn-group btn-group-sm" role="group">
  <div type="button" class="btn btn-default btn-1">Button 1</div>
  <div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using bootstrap with btn-group. There is the html:

Button 1

Button 2

Button 2 it already active.

Currently I'm doing this to remove the active class from one and add it to another.

$('.btn-2').removeClass('active');
$('.btn-1').addClass('active');

Is this the cleanest way to do this or is there a better way so it can just toggle this active class between the two buttons?

Body:
Use:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});

I think the code is fairly self-explanatory? It simply removes any existing "active" classes from the siblings of the button you clicked, and adds that class to the clicked button.

Here's a working snippet:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="btn-group btn-group-sm" role="group">
  <div type="button" class="btn btn-default btn-1">Button 1</div>
  <div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>


问:
Running string in Android
I'm not sure, if "running string" the right name.

I try to explain, what I mean.

I have a TextView in my Layout and want to have text there, which runs from rigth to left, again, and again, and again.

I thougt, I just should enable marquee for that, but the text stays instead of running :(

Here is my TextView-Code:

```<code><TextView
 android:id="@+id/text_ticker"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:background="@color/grey0"
 android:textColor="@color/black"
 android:layout_marginLeft="5dp"
 android:layout_marginRight="5dp"
 android:layout_marginTop="5dp"
 android:padding="10dp"
 android:ellipsize="marquee"
 android:marqueeRepeatLimit="marquee_forever"
 android:scrollHorizontally="true">
</TextView>
</code>```

Thank you,

Mur

答:
Ellipsize marquee scrolling will only scroll when the textView gains focus.

Edit:
Here is the solution

Title: Running string in Android

Body:
I'm not sure, if "running string" the right name.

I try to explain, what I mean.

I have a TextView in my Layout and want to have text there, which runs from rigth to left, again, and again, and again.

I thougt, I just should enable marquee for that, but the text stays instead of running :(

Here is my TextView-Code:

<TextView
 android:id="@+id/text_ticker"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:background="@color/grey0"
 android:textColor="@color/black"
 android:layout_marginLeft="5dp"
 android:layout_marginRight="5dp"
 android:layout_marginTop="5dp"
 android:padding="10dp"
 android:ellipsize="marquee"
 android:marqueeRepeatLimit="marquee_forever"
 android:scrollHorizontally="true">
</TextView>

Thank you,

Mur