问:
Custom Url Rewriting in php
I am implementing a basic URL rewriting in a php application. Below is the approach I am following:

```<code>table 1: rewrite_table (fields as below)

id | original_url | custom_url
</code>```

This table I am using to store original URL and custom url.

I am checking in starting whether requested url is matched with any custom_url and if yes then I am calling controller and action which is being saved in original_url field

which is working fine. Now, point is if I change the custom url again then I want to keep the old url in a url log table and in case any user browse the webpage with that old url then (s)he will be redirect to new url with 301 redirect.

I have created a new table as

```<code>Table2: rewrite_table (fields as below)

log_original_url | current_url_id (this belongs to first table id filed)
</code>```

This table I am using to store old URL which is publically accessible to all before updating the url again which was already in 1st table.

I am confusing and unable to find any solution to implement the second approach.

Anyone can help me to find out a solution

Thanks

答:
By your question,it seems that you are using original_url  in all cases.

My approach for this will be.

select   T1.original_url from rewritetable1 T1 Left Join rewritetable2 T2 on T2.current_url_id=T1.id
     where   T1.custom_url='user input url' OR
             T2.log_original_url ='user input url'

So if user enter the old custom url or new custom url ,u will getting original_url which you are gonna redirect

Title: Custom Url Rewriting in php

Body:
I am implementing a basic URL rewriting in a php application. Below is the approach I am following:

table 1: rewrite_table (fields as below)

id | original_url | custom_url

This table I am using to store original URL and custom url.

I am checking in starting whether requested url is matched with any custom_url and if yes then I am calling controller and action which is being saved in original_url field

which is working fine. Now, point is if I change the custom url again then I want to keep the old url in a url log table and in case any user browse the webpage with that old url then (s)he will be redirect to new url with 301 redirect.

I have created a new table as

Table2: rewrite_table (fields as below)

log_original_url | current_url_id (this belongs to first table id filed)

This table I am using to store old URL which is publically accessible to all before updating the url again which was already in 1st table.

I am confusing and unable to find any solution to implement the second approach.

Anyone can help me to find out a solution

Thanks


来源: stackexchange

问:
Fastboot flash system.img error
When I try to flash via fastboot system.img (from my custom AOSP build) to Sony Xperia Z3 I get the following error:

```<code># fastboot flash system system.img
sending 'system' (584106 KB)...
OKAY [ 18.294s]
writing 'system'...
FAILED (remote: size too large)
finished. total time: 18.297s
</code>```

Z3 has about 2GB system partition and I have no idea why flashing fails.

答: Use newer fastboot version that allow sending packages sperated.</p>

ContentLicense: CC BY-SA 3.0

Title: Fastboot flash system.img error

Body:
When I try to flash via fastboot system.img (from my custom AOSP build) to Sony Xperia Z3 I get the following error:

# fastboot flash system system.img
sending 'system' (584106 KB)...
OKAY [ 18.294s]
writing 'system'...
FAILED (remote: size too large)
finished. total time: 18.297s

Z3 has about 2GB system partition and I have no idea why flashing fails.


问:
Unable to run App in Visual Studio 2015 emulator for Android
I have installed Xamarin SDK and VS2015. From "New Project" I have created "Android Blank Project" and now it builds successfully.

When I hit F5 to run using simulator it load simulator successfully but it does not run application inside.

It gets stuck after this line in output windows:

1>C:\Users\test\AppData\Local\Xamarin\MonoForAndroid\AndroidSDK\build-tools\23.0.2\zipalign.exe
4 "C:\Users\test\documents\visual studio
2015\Projects\App2\App2\bin\Debug\App2.App2-Signed-Unaligned.apk"
"bin\Debug\App2.App2-Signed.apk"

I tried all given solution like
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Android SDK Tools key, Path value, in the registry, pointing to the Android SDK root directory. But no luck.

Is it an issue of pre-configured virtual devices Android_Accelerated_x86 API23?

答:
There could be many solutions as listed in Other related question posts.

I resolved it using one below -

Open Android Emulator Manager

Start Android Virtual Device

```<code>Once emulator is ready then run your application.
</code>```

It works.

ContentLicense: CC BY-SA 4.0

Body:
There could be many solutions as listed in Other related question posts.

I resolved it using one below -

Open Android Emulator Manager

Start Android Virtual Device

Once emulator is ready then run your application.

It works.


问:
How do center an image within another image and have it responsive to mobile landscape?
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

```<code>.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}
</code>```

working, sort of. The HTML:

```<code><div class="parent">
<img class="image1" src="https://placehold.it/1"/ alt="1">
<img class="image2" src="https://placehold.it/2"/ alt="2">
</div>
</code>```

答:
I made your .image1 class a block element, centered the image and using transform property brought image2 in the center

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  margin: 0 auto;
  display: block;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  cursor: pointer;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="parent">
    <img class="image1" src="http://kingofwallpapers.com/image/image-025.jpg" alt="1" />
    <img class="image2" src="https://cdn1.iconfinder.com/data/icons/material-audio-video/20/play-circle-outline-128.png" alt="2" />
  </div>
</div></code>```

Body:
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}

working, sort of. The HTML:

Body:
I made your .image1 class a block element, centered the image and using transform property brought image2 in the center

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  margin: 0 auto;
  display: block;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  cursor: pointer;
  z-index: 2;
}

<div class="container">
  <div class="parent">
    <img class="image1" src="http://kingofwallpapers.com/image/image-025.jpg" alt="1" />
    <img class="image2" src="https://cdn1.iconfinder.com/data/icons/material-audio-video/20/play-circle-outline-128.png" alt="2" />
  </div>
</div>


问:
how to add start button in telegram bot with python-telegran-bot sdk?
I want to write a simple bot for telegram with python-telegram-bot SDK. I want to show a "START" keyboard button instead of typing "/start" command to work with my bot. How to do this with python-telegram-bot?</p>

答:
As I know when you start using a bot for the first time telegram shows that start button itself but after the first message is sent you won't see that keyboard button anymore all you need to do is clearing the bot's history to see that again.

On the other hand if you want to have a keyboard button that can be shown anytime you want, all you should do is implementing a custom keyboard. You can find useful information about keyboards here.


问:
How to skip case while using String replaceAll
Example my string have :

```<code>text = " Hi {fullname}, wellcome u join my group"
</code>```

this is my code:

```<code>text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");
</code>```

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

答:
Try using this</p>

```<code>    String ans="Hi {fullname}, wellcome u join my group";

    ans = ans.replaceAll("\\{[a-zA-Z]*\\}", "ANYTHING");

    System.out.println(ans);
</code>```

Body:
Example my string have :

text = " Hi {fullname}, wellcome u join my group"

this is my code:

text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

Body:
Try using this

    String ans="Hi {fullname}, wellcome u join my group";

    ans = ans.replaceAll("\\{[a-zA-Z]*\\}", "ANYTHING");

    System.out.println(ans);


问:
How to learn to write idiomatic c++ code
I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

答:
I'd (also) recommend:

Effective C++, Effective STL by Steve Myers. They are easy to digest, yet very valuable - sometimes even illuminating.

Code Complete (The 1993 edition is available cheaply and not that much different). It's lengthy, but it walks across the entire field from what it means to be a programmer to how a for loop should look. (It would be better if it was shorter - the way it is it covers so much ground it's hard to place it). I hold it dear because it illustrate two points very well:

code is compromise

There are know facts, (but we still manage to get by by gut feel)

C++ FAQ Lite / C++ FAQ.

I'd throw in Facts and Fallacies by Robert Glass - it doesn't fit your request very well, but go read it.

It's natural that you are unhappy with other people's code. That's typical for programming - heck, even my own code of five years ago was written by a total n00b. That might be more articulated for C++, since it caters for different styles, and often puts freedom ("you can") over guildelines ("that's the way").

Still, mulling over existing code - yours or others - and considering how it can be improved. Also, figuring out why it is the way it is sometimes helps.

(I remember a few TheDailyWTF's where everyone would chime in how stupid and unreasonable this is - yet somewhere, buried among the me too's, was someone with domain experience explaining convincingly under what circumstances this was better than the obvious solution).

ContentLicense: CC BY-SA 2.5


问:
Render Component in iframe using vuejs without src attribute
```<code><iframe id="frame" width="100%" height="100%">

</ifrme>
</code>```

I want to render component in this iframe. Is there any option of creating html element or rendering component in iframe?

```<code>new Vue({
   el:'#frame',
   store:store,
   router:router,
   render: component
})
</code>```

答:
```<code>new Vue({
el:'#frame',
store:store,
router:router,
render: component
})
</code>```

just try to give a name to your route view.
Hope it works

Body:
</ifrme>

I want to render component in this iframe. Is there any option of creating html element or rendering component in iframe?

new Vue({
   el:'#frame',
   store:store,
   router:router,
   render: component
})

Body:
new Vue({
el:'#frame',
store:store,
router:router,
render: component
})

just try to give a name to your route view.
Hope it works


问:
Predict different values from same inputs in a linear regressor model?
Let's suppose I have a noisy 2d data set where one person watching the data could easily draw a straight line in the data so that the mean squared error is minimized.

The model of the line has the form y = mx + b, where x is the input value, y is the predicted value of the model and m and b are trained variables to minimize the cost.

My question is that if we plug some input x1 to the model, it will always output the same number, not taking into account how sparse the data is. How can a model like this predict different values from same inputs?

Maybe this could be done taking all the errors from the model line to the points, making a distribution of them, taking an expected value of such distribution and then adding that value to y?

答:
If the data is 2d, and it can be perfectly modeled with a straight line then there is no data-based nor statistical-based reason not to claim that the process is fully deterministic, and you should output one value.

However, if you have many more dimensions, or your fit is not perfect (error is minimised but not 0) then what you are after is either predicting distribution of values or at least confidence bounds. There are many probabilistic models that can model distribution of the outputs rather than a singe value. In particular linear regression does that, it assumes that you have a Gaussian error around your predictions, thus effectively once you obtain MSE "A" you can draw predictions from N(mx+b, A) - which, as you can easily see degenerates to deterministic model when A=0. These predictions are optimal in expectation, and they are simply your way of "simulating observations" according to the model. There are also meta methods, if you treat your predictor as a black box - you can train multiple models on subsets of data, and treat their predictions as samples to fit a distribution (again for simplicity it could be a single Gaussian).


问:
How to create a spreadsheet with google api and set a proper permissions with PHP?
I have this

```<code>define('CLIENT_SECRET_PATH', __DIR__ . '/config_api.json');
define('ACCESS_TOKEN', '0b502651********c52b3');
</code>```

I can create a spreadsheet with this and get the id and url.

```<code>$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
print_r($response);
$new_spr_id = $response['spreadsheetId'];
</code>```

But this spreadsheet does not appears in the google sheets list as it is "protected" or something.
I am trying to set the permissions with this but get an error: Fatal error: Call to undefined method Google_Service_Drive_Permission::setValue()

```<code>insertPermission($service, $new_spr_id, '**@gmail.com' , 'user', 'owner');
function insertPermission($service, $fileId, $value, $type, $role) {
  $newPermission = new Google_Service_Drive_Permission();
  $newPermission->setValue($value);
  $newPermission->setType($type);
  $newPermission->setRole($role);
  try {
    return $service->permissions->insert($fileId, $newPermission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}
</code>```

I need an example of creating a new spreadsheet and setting the proper permissions to it so I can modify this spreadsheet from my account etc.

Many many thanks!

答:
I think you're on the wrong API. Setting permission for files are found in Drive API permissions.

But to answer your question, here's how to create a new spreadsheet using spreadsheets.create from the Sheets API:

```<code><?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet();

$response = $service->spreadsheets->create($requestBody);

// TODO: Change code below to process the `response` object:
echo '```', var_export($response, true), '```', "\n";

function getClient() {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/spreadsheets'
  return null;
}
?>
</code>```

When the files has been created and saved in your Google Drive, you can now try to set Permissions using the Drive REST API.

Body:
I have this

define('CLIENT_SECRET_PATH', __DIR__ . '/config_api.json');
define('ACCESS_TOKEN', '0b502651********c52b3');

I can create a spreadsheet with this and get the id and url.

$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
print_r($response);
$new_spr_id = $response['spreadsheetId'];

But this spreadsheet does not appears in the google sheets list as it is "protected" or something.
I am trying to set the permissions with this but get an error: Fatal error: Call to undefined method Google_Service_Drive_Permission::setValue()

insertPermission($service, $new_spr_id, '**@gmail.com' , 'user', 'owner');
function insertPermission($service, $fileId, $value, $type, $role) {
  $newPermission = new Google_Service_Drive_Permission();
  $newPermission->setValue($value);
  $newPermission->setType($type);
  $newPermission->setRole($role);
  try {
    return $service->permissions->insert($fileId, $newPermission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}

I need an example of creating a new spreadsheet and setting the proper permissions to it so I can modify this spreadsheet from my account etc.

Many many thanks!

Body:
I think you're on the wrong API. Setting permission for files are found in Drive API permissions.

But to answer your question, here's how to create a new spreadsheet using spreadsheets.create from the Sheets API:

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet();

$response = $service->spreadsheets->create($requestBody);

// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";

function getClient() {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/spreadsheets'
  return null;
}
?>

When the files has been created and saved in your Google Drive, you can now try to set Permissions using the Drive REST API.


问:
How to check if a string is 'float' or 'int'
I have a string, and I know that it only contains a number.

How can I check if this number is int or float?

答:
There are many ways to solve your problem. For example, you can use try{}catch(){}:

Solution 1

```<code>public static void main(String[] args) {
    String str = "5588";

    // Check if int
    try {
        Integer.parseInt(str);
    } catch(NumberFormatException e) {
        // Not int
    }

    // Check if float
    try {
        Float.parseFloat(str);
    } catch(NumberFormatException e) {
        // Not float
    }
}
</code>```

Solution 2

Or you can use regex [-+]?[0-9]*\.?[0-9]+:

```<code>boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");
</code>```

For more details, take a look at Matching Floating Point Numbers with a Regular Expression.

Body:
There are many ways to solve your problem. For example, you can use try{}catch(){}:

Solution 1

public static void main(String[] args) {
    String str = "5588";

    // Check if int
    try {
        Integer.parseInt(str);
    } catch(NumberFormatException e) {
        // Not int
    }

    // Check if float
    try {
        Float.parseFloat(str);
    } catch(NumberFormatException e) {
        // Not float
    }
}

Solution 2

Or you can use regex [-+]?[0-9]*\.?[0-9]+:

boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");

For more details, take a look at Matching Floating Point Numbers with a Regular Expression.


问:
Why do I need COUNT(DISTINCT ...) in this MySQL?
I have a system which allows users to create schedules of videos to watch. The following MySQL pulls active schedules and also info on the number of videos in the schedule, the number already watched, and the number due to be watched today. It does this via multiple joins to the same table that tracks schedules-to-videos associations.

```<code>SELECT
    schedules.*,
    COUNT(DISTINCT sv1.vid_id) AS total_vids, #<-- the problem
    GROUP_CONCAT(DISTINCT sv1.context_node_id) AS topics,
    COUNT(sv2.vid_id) AS vids_watched,
    COUNT(sv3.vid_id) AS today
FROM schedules
JOIN schedule_vids sv1 ON schedules.id = sv1.schedule_id
LEFT JOIN schedule_vids sv2 ON schedules.id = sv2.schedule_id && sv2.watched IS NOT NULL
LEFT JOIN schedule_vids sv3 ON schedules.id = sv3.schedule_id && sv3.date = CURDATE()
WHERE user_id = ? && schedules.id = ?
GROUP BY schedules.id
ORDER BY created DESC
</code>```

The problem: if I don't use COUNT (DISTINCT sv1.vid_id) (i.e. just COUNT(sv1.vid_id)) I get a number far in excess of the true number. I've verified this in the DB. Does anyone see where I'm going wrong?

Interestingly, if I remove the join to sv3 (and the corresponding part of the select statement, of course), the problem goes away.

[UPDATE]

Here's the table structure for the two tables involved:

```<code>CREATE TABLE `schedules` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `user_id` varchar(11) NOT NULL,
 `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `start` date NOT NULL,
 `end` date NOT NULL,
 `inc_weekends` enum('y') DEFAULT NULL,
 `type` enum('ls','c') NOT NULL DEFAULT 'ls' COMMENT 'ls = learning schedule; c = course',
 `subj_id` varchar(30) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=51 DEFAULT CHARSET=latin1
</code>```

and

```<code>CREATE TABLE `schedule_vids` (
 `schedule_id` int(11) NOT NULL,
 `vid_id` varchar(11) NOT NULL,
 `context_node_id` varchar(11) NOT NULL,
 `date` date NOT NULL,
 `watched` date DEFAULT NULL,
 PRIMARY KEY (`schedule_id`,`vid_id`,`context_node_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
</code>```

Sample output:

```<code>id              50
name            some-schedule
user_id         yd8i0i63bd8
created         2017-04-01 11:58:22
start           2017-04-01
end             2017-04-03
inc_weekends    y
type            ls
total_vids      91
topics          maths
vids_watched    0
today           91
</code>```

答:
In all likelihood, you don't need the distinct.  The problem is your joins.  Use conditional aggregation instead:

```<code>SELECT s.*,
       COUNT(*) AS total_vids, #<-- the problem
       GROUP_CONCAT(DISTINCT sv.context_node_id) AS topics,  -- distinct is probably still needed here
       COUNT(watched) AS vids_watched,
       SUM(sv.date = CURDATE()) AS today
FROM schedules s JOIN
     schedule_vids sv
     ON s.id = sv.schedule_id LEFT JOIN
     school_users su
     ON s.user_id = su.uid  -- I'm guessing `user_id` comes from s
WHERE s.user_id = ? AND s.id = ?
GROUP BY s.id
ORDER BY s.created DESC;
</code>```

If you run your query without the aggregation, you'll see what is happening.  You are getting a Cartesian product of videos, which is why the counts are off.

Body:
I have a system which allows users to create schedules of videos to watch. The following MySQL pulls active schedules and also info on the number of videos in the schedule, the number already watched, and the number due to be watched today. It does this via multiple joins to the same table that tracks schedules-to-videos associations.

SELECT
    schedules.*,
    COUNT(DISTINCT sv1.vid_id) AS total_vids, #<-- the problem
    GROUP_CONCAT(DISTINCT sv1.context_node_id) AS topics,
    COUNT(sv2.vid_id) AS vids_watched,
    COUNT(sv3.vid_id) AS today
FROM schedules
JOIN schedule_vids sv1 ON schedules.id = sv1.schedule_id
LEFT JOIN schedule_vids sv2 ON schedules.id = sv2.schedule_id && sv2.watched IS NOT NULL
LEFT JOIN schedule_vids sv3 ON schedules.id = sv3.schedule_id && sv3.date = CURDATE()
WHERE user_id = ? && schedules.id = ?
GROUP BY schedules.id
ORDER BY created DESC

The problem: if I don't use COUNT (DISTINCT sv1.vid_id) (i.e. just COUNT(sv1.vid_id)) I get a number far in excess of the true number. I've verified this in the DB. Does anyone see where I'm going wrong?

Interestingly, if I remove the join to sv3 (and the corresponding part of the select statement, of course), the problem goes away.

[UPDATE]

Here's the table structure for the two tables involved:

CREATE TABLE `schedules` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `user_id` varchar(11) NOT NULL,
 `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `start` date NOT NULL,
 `end` date NOT NULL,
 `inc_weekends` enum('y') DEFAULT NULL,
 `type` enum('ls','c') NOT NULL DEFAULT 'ls' COMMENT 'ls = learning schedule; c = course',
 `subj_id` varchar(30) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=51 DEFAULT CHARSET=latin1

and

CREATE TABLE `schedule_vids` (
 `schedule_id` int(11) NOT NULL,
 `vid_id` varchar(11) NOT NULL,
 `context_node_id` varchar(11) NOT NULL,
 `date` date NOT NULL,
 `watched` date DEFAULT NULL,
 PRIMARY KEY (`schedule_id`,`vid_id`,`context_node_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Sample output:

id              50
name            some-schedule
user_id         yd8i0i63bd8
created         2017-04-01 11:58:22
start           2017-04-01
end             2017-04-03
inc_weekends    y
type            ls
total_vids      91
topics          maths
vids_watched    0
today           91

Body:
In all likelihood, you don't need the distinct.  The problem is your joins.  Use conditional aggregation instead:

SELECT s.*,
       COUNT(*) AS total_vids, #<-- the problem
       GROUP_CONCAT(DISTINCT sv.context_node_id) AS topics,  -- distinct is probably still needed here
       COUNT(watched) AS vids_watched,
       SUM(sv.date = CURDATE()) AS today
FROM schedules s JOIN
     schedule_vids sv
     ON s.id = sv.schedule_id LEFT JOIN
     school_users su
     ON s.user_id = su.uid  -- I'm guessing `user_id` comes from s
WHERE s.user_id = ? AND s.id = ?
GROUP BY s.id
ORDER BY s.created DESC;

If you run your query without the aggregation, you'll see what is happening.  You are getting a Cartesian product of videos, which is why the counts are off.


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
Use

```<code>Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("of mice and men By CNN");
</code>```

to convert to proper case and then you can loop through the keywords as you have mentioned.

Title: Capitalizing words in a string using C#

Body:
Use

Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("of mice and men By CNN");

to convert to proper case and then you can loop through the keywords as you have mentioned.


问:
MVP, JavaFx and components references
I've studied all popular GUI patterns - MVP,MVC,MVVM and finally I decided to implement MVP (Supervising Controller). So I have the following OBJECTS(!). Stage<-View<->Model. It's important Stage!=View, it is another object. Between view and model data binding. Besides I have a presenter(controller) which handles all events and works with view and model, so View<-ViewInterface<-Controller->Model.
The problem is now how to get references to labels, textAreas etc in view. Javafx allows to use @FXML annotation to inject these components to controller. However, using MVP I need these components in View, as all logic for view is in View and I don't need them in controller. The only solution I know is:

```<code>public class MyView{
 private Button button;
 public MyView(){
  ...
  button=(Button) root.lookup("#myButton");
 }
}
</code>```

That is to get references by their ID. However I don't like it. Or I do something wrong or I understand something wrong but I think a better solution exist. Please, help me to find it.

答:
As an Android developer, I always use MVP pattern in my applications. MVC compared to MVP seems so old to me, so when I started working on a new Java app, I felt a little bit lost.

Here there is my solution:

Initial steps

In fxml files create the UI, without specifying a controller, because you don't need one.

Create the Java interfaces (IView, IPresenter and so on..)

Implement the IPresenter interface in the Presenter class, as you would do normally (do http requests, query a DB..)

Now the interesting part:

Adapting your view to MVP pattern

Let's see some code:

Create your GUI (for example a Main GUI) and implement your View interface

```<code>  public class MainGUI extends Application implements MainContract.View {

  public static void main(String... args) {
      launch(args);
  }

  @Override
  public void start(Stage primaryStage) throws IOException {
      //here we will load fxml or create the ui programmatically
  }

  //method from view interface
  @Override
  public void onServerResponse(String message) throws IOException {
      //update the view
  }
</code>```

Now the last step:

Communicating with the presenter

To do this, we first create an istance of our presenter:

```<code>private MainContract.Presenter presenter;

public MainGUI() {
    presenter = new MainPresenter(this);
}
</code>```

this is, of course, the MainContract.View implemented in the MainGUI class

Now we have to get a reference to the view components

```<code>private ComboBox<Double> mySimpleList;

@Override
public void start(Stage primaryStage) throws IOException {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("layout_main.fxml"));
    Parent root = loader.load();
    mySimpleList= (ComboBox<Double>) loader.getNamespace().get("mysimplelist_id");

...

    primaryStage.setScene(new Scene(root, -1, -1));
    primaryStage.show();
</code>```

I prefer using fxml files instead of creating the ui by code, but the logic behind is identical.

Set the items

```<code>...
mySimpleList.setItems(ValuesFactory.getMyValues());
</code>```

And the listener

```<code>...
mySimpleList.valueProperty().addListener(simpleListListener);
</code>```

What is simpleListListener?

A simple ChangeListener, where we finally call a presenter method

```<code>    simpleListListener = (ChangeListener<Double>)
    (observable, oldValue, newValue) -> presenter.doTheLogic(newValue);
</code>```

This is an easy scenario, but in principle this is how we can use MVP Pattern with JavaFX. I also understand that it isn't the definitive solution, so I hope that one day there will be more docs where I can learn more about this argument!

Let me know if I wasn't clear in some part of the code

Title: MVP, JavaFx and components references

Body:
I've studied all popular GUI patterns - MVP,MVC,MVVM and finally I decided to implement MVP (Supervising Controller). So I have the following OBJECTS(!). Stage<-View<->Model. It's important Stage!=View, it is another object. Between view and model data binding. Besides I have a presenter(controller) which handles all events and works with view and model, so View<-ViewInterface<-Controller->Model.
The problem is now how to get references to labels, textAreas etc in view. Javafx allows to use @FXML annotation to inject these components to controller. However, using MVP I need these components in View, as all logic for view is in View and I don't need them in controller. The only solution I know is:

public class MyView{
 private Button button;
 public MyView(){
  ...
  button=(Button) root.lookup("#myButton");
 }
}

That is to get references by their ID. However I don't like it. Or I do something wrong or I understand something wrong but I think a better solution exist. Please, help me to find it.

Body:
As an Android developer, I always use MVP pattern in my applications. MVC compared to MVP seems so old to me, so when I started working on a new Java app, I felt a little bit lost.

Here there is my solution:

Initial steps

In fxml files create the UI, without specifying a controller, because you don't need one.

Create the Java interfaces (IView, IPresenter and so on..)

Implement the IPresenter interface in the Presenter class, as you would do normally (do http requests, query a DB..)

Now the interesting part:

Adapting your view to MVP pattern

Let's see some code:

Create your GUI (for example a Main GUI) and implement your View interface

  public class MainGUI extends Application implements MainContract.View {

  public static void main(String... args) {
      launch(args);
  }

  @Override
  public void start(Stage primaryStage) throws IOException {
      //here we will load fxml or create the ui programmatically
  }

  //method from view interface
  @Override
  public void onServerResponse(String message) throws IOException {
      //update the view
  }

Now the last step:

Communicating with the presenter

To do this, we first create an istance of our presenter:

private MainContract.Presenter presenter;

public MainGUI() {
    presenter = new MainPresenter(this);
}

this is, of course, the MainContract.View implemented in the MainGUI class

Now we have to get a reference to the view components

private ComboBox<Double> mySimpleList;

@Override
public void start(Stage primaryStage) throws IOException {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("layout_main.fxml"));
    Parent root = loader.load();
    mySimpleList= (ComboBox<Double>) loader.getNamespace().get("mysimplelist_id");

...

    primaryStage.setScene(new Scene(root, -1, -1));
    primaryStage.show();

I prefer using fxml files instead of creating the ui by code, but the logic behind is identical.

Set the items

...
mySimpleList.setItems(ValuesFactory.getMyValues());

And the listener

...
mySimpleList.valueProperty().addListener(simpleListListener);

What is simpleListListener?

A simple ChangeListener, where we finally call a presenter method

    simpleListListener = (ChangeListener<Double>)
    (observable, oldValue, newValue) -> presenter.doTheLogic(newValue);

This is an easy scenario, but in principle this is how we can use MVP Pattern with JavaFX. I also understand that it isn't the definitive solution, so I hope that one day there will be more docs where I can learn more about this argument!

Let me know if I wasn't clear in some part of the code


问:
Cannot ssh into EC2 instance. Operation timed out
1The security group allows SSH at port 22 Inbound Rule

This is the first time I've had this problem. I logged in from a friend's AWS account to one of his instances and it connects. so the problem isn't at my end.

Here's the debug log:

```<code>OpenSSH_7.2p2, LibreSSL 2.4.1
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug2: resolving "ec2-54-215-233-245.us-west-1.compute.amazonaws.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ec2-54-215-233-245.us-west-1.compute.amazonaws.com [54.215.233.245] port 22.
</code>```

I followed AWS's troubleshooting guide and even that didn't work. Any idea what's wrong?

答:
The standard things to check when you can't SSH into an instance:

Confirm that the Security Group is permitting access on port 22 (SSH)

Confirm that the instance is in a Public Subnet (which has a Route Table for the Subnet that sends traffic for 0.0.0.0/0 to the Internet Gateway)

Confirm that the instance is running Linux or has an SSH service installed

Confirm the Public IP address (if you're not using a static Elastic IP address, it can change when the instance is Stopped and Started)

Confirm that the Network Access Control Lists (NACLs) in VPC permit all inbound and outbound traffic (this is the default setting)

Body:
1The security group allows SSH at port 22 Inbound Rule

This is the first time I've had this problem. I logged in from a friend's AWS account to one of his instances and it connects. so the problem isn't at my end.

Here's the debug log:

OpenSSH_7.2p2, LibreSSL 2.4.1
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug2: resolving "ec2-54-215-233-245.us-west-1.compute.amazonaws.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ec2-54-215-233-245.us-west-1.compute.amazonaws.com [54.215.233.245] port 22.

I followed AWS's troubleshooting guide and even that didn't work. Any idea what's wrong?


问:
Custom ASP.NET MVC Route In Nested Folders
I want sub-folders in my MVC application, so the current routes just don't cut it.

I've got a folder structure such as

```<code>Views/Accounts/ClientBalances/MyReport.aspx
</code>```

and I'm wanting a URL such as http://myapp/Accounts/ClientBalances/MyReport.  How do you achieve this with mapping routes?  I've had a bash but I'm not very savvy with them.  I thought it'd be along the lines of

```<code> routes.MapRoute( _
        "Accounts/ClientBalances", _
        "Accounts/ClientBalances/{controller}/{action}/{id}", _
        New With {.controller = "Home", .action = "Index", .id = ""} _
    )
</code>```

I've had no luck though.  Any ideas?

答:
Take a look at ASP.NET MVC 2's areas; they look like very similar to what you're trying to achieve. You can watch a quick, 3-minutes video introducing them here.

If you can't (or don't want to) use them, then check this answer about nested view folders. In summary:

You can just return the appropriate view like this (from the action method):

```<code>return View("~/Views/controllername/modulename/actionname.ascx", [optional model]);
</code>```

Body:
I want sub-folders in my MVC application, so the current routes just don't cut it.

I've got a folder structure such as

Views/Accounts/ClientBalances/MyReport.aspx

and I'm wanting a URL such as http://myapp/Accounts/ClientBalances/MyReport.  How do you achieve this with mapping routes?  I've had a bash but I'm not very savvy with them.  I thought it'd be along the lines of

 routes.MapRoute( _
        "Accounts/ClientBalances", _
        "Accounts/ClientBalances/{controller}/{action}/{id}", _
        New With {.controller = "Home", .action = "Index", .id = ""} _
    )

I've had no luck though.  Any ideas?

Body:
Take a look at ASP.NET MVC 2's areas; they look like very similar to what you're trying to achieve. You can watch a quick, 3-minutes video introducing them here.

If you can't (or don't want to) use them, then check this answer about nested view folders. In summary:

You can just return the appropriate view like this (from the action method):

return View("~/Views/controllername/modulename/actionname.ascx", [optional model]);


问:
Nitrogen wf:wire() does not work for dynamic content
I have 2 modules:

test2

Module create div element with a button id =  wf:temp_id()

wire #alert{} event to it.

return these HTML elements so they could be used by other modules.

test

Module create page content with a button myBtn and postback message {btn_clicked,myBtn}

#alert{"myBtn clicked"} event to it,

add empty div with id: id_insert_here - to be used as a placeholder for the dynamic element

call test2:get_content("Static"), to add content from the module test2.

Then in event function, it use #wf:insert_after to add content from the test2:get_content("Dynamic").

Expected behavior:

User click on myBtn,

Alert message "myBtn clicked" appeared

New element "Dynamic content" appeared
This part is working.

User click on button in "Static" section that was generated from the test2:get_content/1 function,

Message "Btn_TEMP1" clicked appeared.
So far everything is working as expected.

Now:
 6. User click on button in "Dynamic" secion that was generated using test2:get_content/1 function, and added to the page  using wf:insert_after()  call.

Expected behavior: Message "btn_TEMP2" clicked appeared.

Realized behavior - nothing happened.

wf:wire does not work.

Q: How to enure that wf:wire() works fo the elements that are added using wf:insert_XXX function?

```<code>%% -*- mode: nitrogen -*-
-module (test).
-compile(export_all).
-include_lib("../deps/nitrogen_core/include/wf.hrl").

main() ->
    #template { file="./priv/templates/bare.html",
       bindings=[{'PageTitle',<<"Test">>}]}.

title() ->
    #template{bindings = L} = main(),
    proplists:get_value('PageTitle',L).

body() ->
    Body = [
       #panel{class="w3-panel w3-green",
              body =
                    [#p{text = "some text"},
                     #button {
                        id=myBtn,
                        text="myBtn",
                        postback={btn_clicked,myBtn}
                    },
                    #panel{id = id_insert_here}
                    ]}
     ],
    wf:wire(myBtn, #event{ type= click, actions = [ #alert{text="MyBtn clicked"} ]}),
    Body,
    Content = test2:get_content("Pre-compiled"),
    Body2 = [Body,Content],
    Body2.

event({btn_clicked,myBtn} = Event) ->
    io:format("Event: ~p",[Event]),
    Content = test2:get_content("Dynamic"),
    wf:insert_after(id_insert_here,Content);

event(Event) ->
    io:format(" Unexpected Event: ~p ",[Event]),
    ok.
%% end of module test
</code>```

Module test2:

```<code>-module(test2).
-compile(export_all).
-include_lib("../deps/nitrogen_core/include/wf.hrl").

get_content(Title) ->
    MyId = wf:temp_id(),
    BtnText = io_lib:format("Btn_~p",[MyId]),
    Body = [
    #panel{class="w3-panel w3-yellow",
           body =
                [#p{text = Title},
                 #button {
                    id=MyId,
                    text=BtnText
                    }]
        }],
    Msg = io_lib:format("Btn: ~p clicked",[MyId]),
    wf:wire(MyId, #event{ type= click, actions = [ #alert{text= Msg} ]}),
    Body.
</code>```

答:
Great Question, and one that needs a proper answer in the nitrogen docs.

The short answer is that in test2:get_content, you should just replace wf:wire with wf:defer.

The reasoning for it is a little longer, but it goes like this:

In both situations (both static and dynamic), when test2:get_content is called it does the following in this order:

Build some Nitrogen elements and store them in variables.

Wire an action to one of the elements defined in (1)

Return the previously made elements.

In a static request (or rather, in nitrogen parlance, a first_request, since in Nitrogen, a "static request" refers to purely static content like requesting image files or whatever), this is perfectly fine. Static content is returned, placed into the page, and then any wired actions are inserted into the [[[script]]] section at the bottom of the template.

In a dynamic request, however, the order of operations becomes important.

The test2:get_content function you've defined does the same thing, but the function is evaluated and the content is getting returned to the wf:insert_after function, which then inserts the elements into the DOM.

The bug resides subtly in the above paragraph, but I'll fit in the overall context to make it more obvious.  With the dynamic request:

The call to wf:insert_after (or wf:insert_before, or wf:update, or wf:replace or any of those) needs to test2:get_content to be evaluated first. So evaluate test2:get_content()

Build some Nitrogen elements and store them in variables.

Wire an action to one of the elements defined in (2)

Return the previously made elements.

wf:insert_after takes those returned elements and wires them to the page.

What happens here is that because the wf:insert_after is effectively happening last, the wf:wire to the element goes nowhere.  That is, the element wf:wire is trying to be attached to doesn't exist in the DOM yet.

It's like this pseudocode:

```<code>$('#my_new_element').click(function(){do_something}));
$('#body').insert_bottom("<button id=my_new_element>click</button>");
</code>```

Using wf:defer in place of wf:wire ensures the wiring happens after the insert_XXX function evaluates.

Body:
I have 2 modules:

test2

Module create div element with a button id =  wf:temp_id()

wire #alert{} event to it.

return these HTML elements so they could be used by other modules.

test

Module create page content with a button myBtn and postback message {btn_clicked,myBtn}

#alert{"myBtn clicked"} event to it,

add empty div with id: id_insert_here - to be used as a placeholder for the dynamic element

call test2:get_content("Static"), to add content from the module test2.

Then in event function, it use #wf:insert_after to add content from the test2:get_content("Dynamic").

Expected behavior:

User click on myBtn,

Alert message "myBtn clicked" appeared

New element "Dynamic content" appeared
This part is working.

User click on button in "Static" section that was generated from the test2:get_content/1 function,

Message "Btn_TEMP1" clicked appeared.
So far everything is working as expected.

Now:
 6. User click on button in "Dynamic" secion that was generated using test2:get_content/1 function, and added to the page  using wf:insert_after()  call.

Expected behavior: Message "btn_TEMP2" clicked appeared.

Realized behavior - nothing happened.

wf:wire does not work.

Q: How to enure that wf:wire() works fo the elements that are added using wf:insert_XXX function?

%% -*- mode: nitrogen -*-
-module (test).
-compile(export_all).
-include_lib("../deps/nitrogen_core/include/wf.hrl").

main() ->
    #template { file="./priv/templates/bare.html",
       bindings=[{'PageTitle',<<"Test">>}]}.

title() ->
    #template{bindings = L} = main(),
    proplists:get_value('PageTitle',L).

body() ->
    Body = [
       #panel{class="w3-panel w3-green",
              body =
                    [#p{text = "some text"},
                     #button {
                        id=myBtn,
                        text="myBtn",
                        postback={btn_clicked,myBtn}
                    },
                    #panel{id = id_insert_here}
                    ]}
     ],
    wf:wire(myBtn, #event{ type= click, actions = [ #alert{text="MyBtn clicked"} ]}),
    Body,
    Content = test2:get_content("Pre-compiled"),
    Body2 = [Body,Content],
    Body2.

event({btn_clicked,myBtn} = Event) ->
    io:format("Event: ~p",[Event]),
    Content = test2:get_content("Dynamic"),
    wf:insert_after(id_insert_here,Content);

event(Event) ->
    io:format(" Unexpected Event: ~p ",[Event]),
    ok.
%% end of module test

Module test2:

-module(test2).
-compile(export_all).
-include_lib("../deps/nitrogen_core/include/wf.hrl").

get_content(Title) ->
    MyId = wf:temp_id(),
    BtnText = io_lib:format("Btn_~p",[MyId]),
    Body = [
    #panel{class="w3-panel w3-yellow",
           body =
                [#p{text = Title},
                 #button {
                    id=MyId,
                    text=BtnText
                    }]
        }],
    Msg = io_lib:format("Btn: ~p clicked",[MyId]),
    wf:wire(MyId, #event{ type= click, actions = [ #alert{text= Msg} ]}),
    Body.

Body:
Great Question, and one that needs a proper answer in the nitrogen docs.

The short answer is that in test2:get_content, you should just replace wf:wire with wf:defer.

The reasoning for it is a little longer, but it goes like this:

In both situations (both static and dynamic), when test2:get_content is called it does the following in this order:

Build some Nitrogen elements and store them in variables.

Wire an action to one of the elements defined in (1)

Return the previously made elements.

In a static request (or rather, in nitrogen parlance, a first_request, since in Nitrogen, a "static request" refers to purely static content like requesting image files or whatever), this is perfectly fine. Static content is returned, placed into the page, and then any wired actions are inserted into the [[[script]]] section at the bottom of the template.

In a dynamic request, however, the order of operations becomes important.

The test2:get_content function you've defined does the same thing, but the function is evaluated and the content is getting returned to the wf:insert_after function, which then inserts the elements into the DOM.

The bug resides subtly in the above paragraph, but I'll fit in the overall context to make it more obvious.  With the dynamic request:

The call to wf:insert_after (or wf:insert_before, or wf:update, or wf:replace or any of those) needs to test2:get_content to be evaluated first. So evaluate test2:get_content()

Build some Nitrogen elements and store them in variables.

Wire an action to one of the elements defined in (2)

Return the previously made elements.

wf:insert_after takes those returned elements and wires them to the page.

What happens here is that because the wf:insert_after is effectively happening last, the wf:wire to the element goes nowhere.  That is, the element wf:wire is trying to be attached to doesn't exist in the DOM yet.

It's like this pseudocode:

$('#my_new_element').click(function(){do_something}));
$('#body').insert_bottom("<button id=my_new_element>click</button>");

Using wf:defer in place of wf:wire ensures the wiring happens after the insert_XXX function evaluates.


问:
extending a class with namespace in PHP
I'm trying to write my first framework with namespaces.
I've got a problem with extending class Controller.
I get

Fatal error: Class 'Controller' not found in xxx/src/controllers/index.php on line 3

A Controller looks that:

```<code>namespace src\libs;
class Controller
{}
</code>```

And here is my Index class in src/controllers/

```<code>namespace src\controllers;
use src\libs as libs;
class Index extends libs\Controller
{}
</code>```

My autoload:

```<code>function autoLoader($class)
{
    $class = str_replace('\\', '/', $class);
    if (file_exists('./' . $class . '.php')) {
        require( './' . $class . '.php');
    } else {
        $class = explode('/', $class);
        if (file_exists( LIBS . end($class) . '.php')) {
            require( LIBS . end($class) . '.php');
        } else {
            echo 'Critical error!!';
            exit;
        }
    }
}
</code>```

LIBS = ./src/libs/

AutLoader works, because it includes file with class Controller, I don't get error. I have not idea why it isn't work.

答:
It is working fine for me

File: /var/www/html/PHP/Randoms/src/libs/Controller.php

```<code><?php
namespace src\libs;
class Controller
{

}
</code>```

File: /var/www/html/PHP/Randoms/src/controllers/Index.php

```<code>namespace src\controllers;
use src\libs as libs;
spl_autoload_register(function($classname){
    $classPath=str_replace("\\", "/", $classname);
    $filePath= dirname(__FILE__)."/../../".$classPath.".php";
    if(file_exists($filePath))
    {
        require_once $filePath;
    }
});
class Index extends libs\Controller
{}
</code>```

Title: extending a class with namespace in PHP

Body:
I'm trying to write my first framework with namespaces.
I've got a problem with extending class Controller.
I get

Fatal error: Class 'Controller' not found in xxx/src/controllers/index.php on line 3

A Controller looks that:

namespace src\libs;
class Controller
{}

And here is my Index class in src/controllers/

namespace src\controllers;
use src\libs as libs;
class Index extends libs\Controller
{}

My autoload:

function autoLoader($class)
{
    $class = str_replace('\\', '/', $class);
    if (file_exists('./' . $class . '.php')) {
        require( './' . $class . '.php');
    } else {
        $class = explode('/', $class);
        if (file_exists( LIBS . end($class) . '.php')) {
            require( LIBS . end($class) . '.php');
        } else {
            echo 'Critical error!!';
            exit;
        }
    }
}

LIBS = ./src/libs/

AutLoader works, because it includes file with class Controller, I don't get error. I have not idea why it isn't work.

Body:
It is working fine for me

File: /var/www/html/PHP/Randoms/src/libs/Controller.php

<?php
namespace src\libs;
class Controller
{

}

File: /var/www/html/PHP/Randoms/src/controllers/Index.php

namespace src\controllers;
use src\libs as libs;
spl_autoload_register(function($classname){
    $classPath=str_replace("\\", "/", $classname);
    $filePath= dirname(__FILE__)."/../../".$classPath.".php";
    if(file_exists($filePath))
    {
        require_once $filePath;
    }
});
class Index extends libs\Controller
{}


问:
How I can running GUI application on Docker for Mac?
How I can running GUI application on Docker for Mac?

I want to running wireshark GUI on Ubuntu 16.10

I found docker forum about it, But I can't run GUI app based on content of forum.

Maybe information that in forum is outdated.

How I can run GUI app on Docker for Mac?

Note that I'm using following softwares

Host OS: macOS 10.12.4

Guest OS: Ubuntu 16.10

Docker: 17.03.1-ce-rc1-mac3

答:
Containers themselves don't really have a notion of "GUI" apps; there's no window manager or anything inside the container. It is possible though to have a container connect to X11 running on your Mac, but requires some testing and experimenting to get it set up right.

This thread on GitHub may give you more information; https://github.com/docker/docker/issues/8710. If you have more questions on that, it may be best to open a new topic on https://forums.docker.com or ask in the Docker Community slack


问:
conditional compilation in F#: something like #elif
I'm trying to find a directive like #elif in C#. Does it exist? I can't find it anywhere. Sometimes there is need in several variants for the same symbol. </p>

答:
I'm trying to find a directive like #elif in C#. Does it exist?

No

What would be better would be to port the OCaml preprocessor Camlp5 to F#. It not only has the directives as macros but a whole lot more, see documentation.

OCaml was ported to Microsoft .NET then massaged into F#. So most any OCaml code translates almost line for line into F#. However there are some parts of OCaml, especially the meta stuff, that don't translate directly into F# and workarounds have to be done.


问:
Getting JSON from Contentful into Mustache
I'm trying to get my entries from Contentful (JSON) and putting them into a Mustache template.

The following code works, but is not applied to a template:

```<code>client.getEntries()
.then((response) => {
    $('.result').html(response.items.map((item) => ' Items: ' + item.sys.id).join('\n'));

})
.catch((error) => {
    console.log('\x1b[31merror occured')
    console.log(error)
})
</code>```

When I try the same procedure but putting it into a template it doesn't work:

```<code>client.getEntries()
  .then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.data);
    $('.result').html(html);

  })
  .catch((error) => {
    console.log('Error occured')
    console.log(error)
  })
</code>```

HTML

```<code><script id="myEntries" type="text/template">
    {{#items}} {{fields.customerName}} {{/items}}
</script>

<div class="result"></div>
</code>```

It seems the JSON string is not properly attached to the template?

The JSON file looks like this

```<code>  {
     "sys":{
        "type":"Array"
     },
     "total":3,
     "skip":0,
     "limit":100,
     "items":[
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"4moramDebKGsUwI2a6YOSe",
              "type":"Entry",
              "createdAt":"2017-03-31T17:31:25.994Z",
              "updatedAt":"2017-03-31T17:31:25.994Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"3",
              "customerUrl":"3"
           }
        },
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"5M6NPWMve0YgMcSUcoAusk",
              "type":"Entry",
              "createdAt":"2017-03-31T17:31:51.535Z",
              "updatedAt":"2017-03-31T17:31:51.535Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"4",
              "customerUrl":"4"
           }
        },
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"2ClsG24K5S6qiAYGi8gEQI",
              "type":"Entry",
              "createdAt":"2017-03-31T17:22:16.490Z",
              "updatedAt":"2017-03-31T17:22:16.490Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"5",
              "customerUrl":"5"
           }
        }
     ]
  }
</code>```

Would be awesome to get some help with this :)

/ Oskar

答:
From the code you showed, it looks like you are passing the wrong data to the template, the response object does not have any data property. and it is a good practice to call .toPlainObject() so all the appended helper methods will be removed and you will end up with just the raw data

Your code should be

```<code>client.getEntries()
  .then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

  })
  .catch((error) => {
    console.log('Error occured')
    console.log(error)
  })
</code>```

Body:
I'm trying to get my entries from Contentful (JSON) and putting them into a Mustache template.

The following code works, but is not applied to a template:

client.getEntries()
.then((response) => {
    $('.result').html(response.items.map((item) => ' Items: ' + item.sys.id).join('\n'));

})
.catch((error) => {
    console.log('\x1b[31merror occured')
    console.log(error)
})

When I try the same procedure but putting it into a template it doesn't work:

client.getEntries()
  .then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.data);
    $('.result').html(html);

  })
  .catch((error) => {
    console.log('Error occured')
    console.log(error)
  })

HTML

It seems the JSON string is not properly attached to the template?

The JSON file looks like this

  {
     "sys":{
        "type":"Array"
     },
     "total":3,
     "skip":0,
     "limit":100,
     "items":[
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"4moramDebKGsUwI2a6YOSe",
              "type":"Entry",
              "createdAt":"2017-03-31T17:31:25.994Z",
              "updatedAt":"2017-03-31T17:31:25.994Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"3",
              "customerUrl":"3"
           }
        },
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"5M6NPWMve0YgMcSUcoAusk",
              "type":"Entry",
              "createdAt":"2017-03-31T17:31:51.535Z",
              "updatedAt":"2017-03-31T17:31:51.535Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"4",
              "customerUrl":"4"
           }
        },
        {
           "sys":{
              "space":{
                 "sys":{
                    "type":"Link",
                    "linkType":"Space",
                    "id":"4eewqivb4aog"
                 }
              },
              "id":"2ClsG24K5S6qiAYGi8gEQI",
              "type":"Entry",
              "createdAt":"2017-03-31T17:22:16.490Z",
              "updatedAt":"2017-03-31T17:22:16.490Z",
              "revision":1,
              "contentType":{
                 "sys":{
                    "type":"Link",
                    "linkType":"ContentType",
                    "id":"customer"
                 }
              },
              "locale":"sv-SE"
           },
           "fields":{
              "customerName":"5",
              "customerUrl":"5"
           }
        }
     ]
  }

Would be awesome to get some help with this :)

/ Oskar

Body:
From the code you showed, it looks like you are passing the wrong data to the template, the response object does not have any data property. and it is a good practice to call .toPlainObject() so all the appended helper methods will be removed and you will end up with just the raw data

Your code should be

client.getEntries()
  .then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

  })
  .catch((error) => {
    console.log('Error occured')
    console.log(error)
  })


问:
AngularJs #how to pass scope variable in on change event in directive in input file
I am not able to pass data to controller's function through angular directive, directive has one change event. In which i want to pass my dynamic id.
In controller i have myArray

```<code>$scope.myArray = [1,2,3,4,5];
</code>```

I have following html.

```<code><div ng-repeat="data in myArray track by $index">
    <input type="file" ng-upload-change="uploadFile($event, $id)" my-id="$index">
<div>
</code>```

In Controller:

```<code>$scope.uploadFile = function($event, $id){
    var files = $event.target.files;
    console.log("id:"+$id);
};
</code>```

In directive:

```<code>app.directive('ngUploadChange', function() {
    return{
        scope:{
            ngUploadChange:"&",
            myId:"="
        },
        link:function($scope, $element, $attrs){
            $element.on("change",function(event){
                $scope.ngUploadChange({$event: event, $id : $scope.myId});
            })
            $scope.$on("$destroy",function(){
                $element.off();
            });
        }
    }
});
</code>```

As you can see that when i pass uploadFile function to ngUploadChange directive, it always pass first id (in this case it is 1) to controllers function.
I am not getting updated id every time.

Thanks in advance.

答:
It is better to write the directive without isolate scope.

```<code>app.directive('ngUploadChange', function() {
    return{
        /*
        scope:{
            ngUploadChange:"&",
            myId:"="
        },*/
        link:function($scope, $element, $attrs){
            $element.on("change",function(event){
                var locals = { $event: event,
                               $id : $scope.$eval($attrs.myId)
                };
                $scope.$eval($attrs.ngUploadChange, locals);
            });
            /*
            $scope.$on("$destroy",function(){
                $element.off();
            });*/
        }
    }
});
</code>```

Use $scope.$eval instead of isolate scope bindings.

Isolate scope adds a scope and additional watchers which have been known to cause digest cycle delays that fight the ngModelController.

Body:
I am not able to pass data to controller's function through angular directive, directive has one change event. In which i want to pass my dynamic id.
In controller i have myArray

$scope.myArray = [1,2,3,4,5];

I have following html.

    <input type="file" ng-upload-change="uploadFile($event, $id)" my-id="$index">

In Controller:

$scope.uploadFile = function($event, $id){
    var files = $event.target.files;
    console.log("id:"+$id);
};

In directive:

app.directive('ngUploadChange', function() {
    return{
        scope:{
            ngUploadChange:"&",
            myId:"="
        },
        link:function($scope, $element, $attrs){
            $element.on("change",function(event){
                $scope.ngUploadChange({$event: event, $id : $scope.myId});
            })
            $scope.$on("$destroy",function(){
                $element.off();
            });
        }
    }
});

As you can see that when i pass uploadFile function to ngUploadChange directive, it always pass first id (in this case it is 1) to controllers function.
I am not getting updated id every time.

Thanks in advance.

Body:
It is better to write the directive without isolate scope.

app.directive('ngUploadChange', function() {
    return{
        /*
        scope:{
            ngUploadChange:"&",
            myId:"="
        },*/
        link:function($scope, $element, $attrs){
            $element.on("change",function(event){
                var locals = { $event: event,
                               $id : $scope.$eval($attrs.myId)
                };
                $scope.$eval($attrs.ngUploadChange, locals);
            });
            /*
            $scope.$on("$destroy",function(){
                $element.off();
            });*/
        }
    }
});

Use $scope.$eval instead of isolate scope bindings.

Isolate scope adds a scope and additional watchers which have been known to cause digest cycle delays that fight the ngModelController.


问:
c# - Opening chosen file with associated App
I have successfully prompted user to select a file in  C# using

the openFileDialog control.

I now have the filename, lets call it foo.docx

I want to open the file with the asssoicated app.

i.e., if it is a docx file, launch with word.

Is there a best way to just pass the filename and it do the launch ?

I used System.Diagnostics.Process.Start(openFileDialog1.FileName.ToString());

TIA.

Ralph

答:
Simply use

```<code>Process.Start(filename);
</code>```

This will open the program in the default program set in Windows.

Also, you can use the same to open a URL in the user's default browser.

Body:
Simply use

Process.Start(filename);

This will open the program in the default program set in Windows.

Also, you can use the same to open a URL in the user's default browser.


问:
tkinter input and output in Python 3
I have been creating a gui using tkinter.

I want to receive a filename as input from the user, open the file and display a message box with text generated by a function.

Below is the code, can someone explain why this is not working?

```<code>   import tkinter as tk
   import csv
   import tkinter.simpledialog
   import tkinter.messagebox
   from tkinter import ttk

   file=tkinter.simpledialog.askstring("File: ","Enter your file name")

   with open(file, 'r') as f: #this line reads the file
    reader = csv.reader(f, delimiter=',')

   output=values
   def values(): #And this is the function
    print("Some text")#which should return whatever info is inside 'print' function

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.controller = controller
    button = ttk.Button(self, text="Submit", #I prefer using the button but any other way will do
                       command=tkmessagebox.showinfo("Results",output))
    button.pack()
</code>```

I get "name 'tksimpledialog' is not defined" error.

答:
You need a window for the askstring function to work:

```<code>...
window = tk.Tk()
window.withdraw() #hides the window
file = tkinter.simpledialog.askstring("File: ","Enter your file name")
...
</code>```

Then there is some issue with your line :

```<code>output=values
</code>```

It should be placed after the definition of the function, not before.
And contain parenthesis at the end. Like :

```<code>def values(): #And this is the function
    print("Some text")
    # which should return whatever info is inside 'print' function
output=values()
</code>```

This fixes the error I had when trying to run your script.

Title: tkinter input and output in Python 3

Body:
I have been creating a gui using tkinter.

I want to receive a filename as input from the user, open the file and display a message box with text generated by a function.

Below is the code, can someone explain why this is not working?

   import tkinter as tk
   import csv
   import tkinter.simpledialog
   import tkinter.messagebox
   from tkinter import ttk

   file=tkinter.simpledialog.askstring("File: ","Enter your file name")

   with open(file, 'r') as f: #this line reads the file
    reader = csv.reader(f, delimiter=',')

   output=values
   def values(): #And this is the function
    print("Some text")#which should return whatever info is inside 'print' function

   def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.controller = controller
    button = ttk.Button(self, text="Submit", #I prefer using the button but any other way will do
                       command=tkmessagebox.showinfo("Results",output))
    button.pack()

I get "name 'tksimpledialog' is not defined" error.

Body:
You need a window for the askstring function to work:

...
window = tk.Tk()
window.withdraw() #hides the window
file = tkinter.simpledialog.askstring("File: ","Enter your file name")
...

Then there is some issue with your line :

output=values

It should be placed after the definition of the function, not before.
And contain parenthesis at the end. Like :

def values(): #And this is the function
    print("Some text")
    # which should return whatever info is inside 'print' function
output=values()

This fixes the error I had when trying to run your script.


问:
Using Mimekit to send to email addresses that contain special characters
I am trying to send an email to an email address: coordinación@test.xxxxx.com that contains special characters using Mailkit via a mail server that has  the SMTPUTF8 extension enabled ( have double checked the same by sending a sample test email from a shell script).

Mailkit reports the exception as "The SMTP server doesn't support the SMTPUTF8 extension", is there something I should be doing to encode the email address differently ?.

I have tried using UTF-8 encoding for the MailboxAddress constructor but the results are the same. Please find the protocol log for the same.

```<code>Connected to smtp://mail5xx.xx.xxxxx.com:25/?starttls=when-available
S: 220 mail5xx.xx.xxxxx.com ESMTP service ready
C: EHLO [192.xxx.xx.xxx]
S: 250-mail5xx.xx.xxxxx.com says hello
S: 250-ENHANCEDSTATUSCODES
S: 250-PIPELINING
S: 250-CHUNKING
S: 250-8BITMIME
S: 250-AUTH CRAM-MD5 PLAIN LOGIN
S: 250-AUTH=CRAM-MD5 PLAIN LOGIN
S: 250-XACK
S: 250-SIZE 0
S: 250-VERP
S: 250 DSN
</code>```

Edit:
This is no longer a problem for me if I use Mailkit 1.1.4 ( thanks to Jeff for that quick patch), apparently some of the mailservers can send UTF mails even if they don't have the SMTPUTF8 extension enabled, which is strange.

答:
Based on the server response to the EHLO command, it does not support the SMTPUTF8 extension.

Note that if it did support it, then it would be listed in the response like so:

```<code>C: EHLO [192.xxx.xx.xxx]
S: 250-mail5xx.xx.xxxxx.com says hello
S: 250-ENHANCEDSTATUSCODES
S: 250-PIPELINING
S: 250-CHUNKING
S: 250-8BITMIME
S: 250-AUTH CRAM-MD5 PLAIN LOGIN
S: 250-AUTH=CRAM-MD5 PLAIN LOGIN
S: 250-XACK
S: 250-SIZE 0
S: 250-VERP
S: 250-DSN
S: 250 SMTPUTF8
</code>```

Body:
I am trying to send an email to an email address: coordinación@test.xxxxx.com that contains special characters using Mailkit via a mail server that has  the SMTPUTF8 extension enabled ( have double checked the same by sending a sample test email from a shell script).

Mailkit reports the exception as "The SMTP server doesn't support the SMTPUTF8 extension", is there something I should be doing to encode the email address differently ?.

I have tried using UTF-8 encoding for the MailboxAddress constructor but the results are the same. Please find the protocol log for the same.

Connected to smtp://mail5xx.xx.xxxxx.com:25/?starttls=when-available
S: 220 mail5xx.xx.xxxxx.com ESMTP service ready
C: EHLO [192.xxx.xx.xxx]
S: 250-mail5xx.xx.xxxxx.com says hello
S: 250-ENHANCEDSTATUSCODES
S: 250-PIPELINING
S: 250-CHUNKING
S: 250-8BITMIME
S: 250-AUTH CRAM-MD5 PLAIN LOGIN
S: 250-AUTH=CRAM-MD5 PLAIN LOGIN
S: 250-XACK
S: 250-SIZE 0
S: 250-VERP
S: 250 DSN

Edit:
This is no longer a problem for me if I use Mailkit 1.1.4 ( thanks to Jeff for that quick patch), apparently some of the mailservers can send UTF mails even if they don't have the SMTPUTF8 extension enabled, which is strange.

Body:
Based on the server response to the EHLO command, it does not support the SMTPUTF8 extension.

Note that if it did support it, then it would be listed in the response like so:

C: EHLO [192.xxx.xx.xxx]
S: 250-mail5xx.xx.xxxxx.com says hello
S: 250-ENHANCEDSTATUSCODES
S: 250-PIPELINING
S: 250-CHUNKING
S: 250-8BITMIME
S: 250-AUTH CRAM-MD5 PLAIN LOGIN
S: 250-AUTH=CRAM-MD5 PLAIN LOGIN
S: 250-XACK
S: 250-SIZE 0
S: 250-VERP
S: 250-DSN
S: 250 SMTPUTF8


问:
Google Play services leaderboard sample scripts are not running
I am trying to implement Google Leaderboard for my games.

So I have downloaded sample scripts from the following URL: https://github.com/playgameservices/web-basic-samples

and put it in the web server:

E:\wamp\www\sugumar\web-basic-samples-master

and in the browser I tried

http://localhost/sugumar/web-basic-samples-master/type-a-number-js/index.html

but it showed the following error

Not Found

The requested URL
  /sugumar/web-basic-samples-master/type-a-number-js/index.html was not
  found on this server.

so I checked the file permissions for the folder web-basic-samples-master (I have so many projects running under sugumar folder so no problem with that folder permission).

It was in read only mode, so I unchecked the readonly and clicked on apply and on the next screen I clicked ok for "Apply changes to this folder, subfolders files" and then I clicked on ok, and then run the following url again
http://localhost/sugumar/web-basic-samples-master/type-a-number-js/index.html

but it still shows the same problem:

Not Found

The requested URL
  /sugumar/web-basic-samples-master/type-a-number-js/index.html was not
  found on this server.

答:
It seems you've skipped the entire Running the sample application guide accompanying the code sample:

To run this sample application in your own environment, perform the
  following steps:

1.Get the latest Google APIs Client Library for PHP and extract it into your server directory.
   - We recommend you retrieve this using git, to ensure you always have the latest version. (e.g. git clone
  https://github.com/google/google-api-php-client)
   - Alternately, you can get the gzip file from the downloads page. Please make sure you download version 0.6.2 or later (updated June 3,
  2013), as the GameService contrib file does not exist in earlier
  versions.

2.This application assumes you have PHP/MySQL already running on your server. Create a users table with the following setup:

```<code> CREATE TABLE IF NOT EXISTS `users` (    `temp_key` varchar(128) NOT
> NULL,    `user_id` varchar(64) NOT NULL,    `bearer_token`
> varchar(1024) NOT NULL,    `last_modified` timestamp NOT NULL DEFAULT
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,    PRIMARY KEY
> (`user_id`)  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Create your own application in the Play Console, as described in the Create Client IDs portion of the documentation. Make sure you
  follow the "Web" instructions for creating your Client ID and linking
  your application.

If you've already set up your own version of the Type-a-Number sample
  application, you can repurpose that application here. Either create a
  new linked application (which will give you a new client ID), or add
  your test server to your list of Javascript Origins in the APIs
  Console (which will let you re-use your current client ID)

When you link your Web application, ensure the hostname matches the server from which you'll be testing your application. (e.g.
  http://localhost/ or https://www.mytestserver.com). Also, make sure
  that you have the right protocol (http vs. https)

Make a note of your Client ID and Client Secret as described in the documentation

Create a Leaderboard as described in the Leaderbords documentation. Give it a creative name like "High scores".

Once that's done, you'll want to replace the following constants defined in the SampleAppConstants.ini file.

In the api section, replace the following: clientId (Replace this with
  your OAuth2.0 Client ID) clientSecret (Replace this with your OAuth2.0
  Client secret) In the db section, replace the following: user (Replace
  this with your MySQL username) pass (Replace this with your MySQL
  password) host (Replace this with your MySQL hostname) name (Replace
  this with the name of the MySQL database you're using.) In the game
  section, replace the following: leaderboardId (Replace this with the
  ID of the leaderboard you created in the previous step.)

Move your AppConstants.ini file outside of your htdocs tree. This contains sensitive information and it shouldn't be located anywhere
  where it could accidentally be displayed to the user.

Update the constructor in your GameHandler file to point to the new location of AppConstants.ini.

That's it! Your application should be ready to run!

Body:
It seems you've skipped the entire Running the sample application guide accompanying the code sample:

To run this sample application in your own environment, perform the
  following steps:

1.Get the latest Google APIs Client Library for PHP and extract it into your server directory.
   - We recommend you retrieve this using git, to ensure you always have the latest version. (e.g. git clone
  https://github.com/google/google-api-php-client)
   - Alternately, you can get the gzip file from the downloads page. Please make sure you download version 0.6.2 or later (updated June 3,
  2013), as the GameService contrib file does not exist in earlier
  versions.

2.This application assumes you have PHP/MySQL already running on your server. Create a users table with the following setup:

 CREATE TABLE IF NOT EXISTS `users` (    `temp_key` varchar(128) NOT
> NULL,    `user_id` varchar(64) NOT NULL,    `bearer_token`
> varchar(1024) NOT NULL,    `last_modified` timestamp NOT NULL DEFAULT
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,    PRIMARY KEY
> (`user_id`)  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Create your own application in the Play Console, as described in the Create Client IDs portion of the documentation. Make sure you
  follow the "Web" instructions for creating your Client ID and linking
  your application.

If you've already set up your own version of the Type-a-Number sample
  application, you can repurpose that application here. Either create a
  new linked application (which will give you a new client ID), or add
  your test server to your list of Javascript Origins in the APIs
  Console (which will let you re-use your current client ID)

When you link your Web application, ensure the hostname matches the server from which you'll be testing your application. (e.g.
  http://localhost/ or https://www.mytestserver.com). Also, make sure
  that you have the right protocol (http vs. https)

Make a note of your Client ID and Client Secret as described in the documentation

Create a Leaderboard as described in the Leaderbords documentation. Give it a creative name like "High scores".

Once that's done, you'll want to replace the following constants defined in the SampleAppConstants.ini file.

In the api section, replace the following: clientId (Replace this with
  your OAuth2.0 Client ID) clientSecret (Replace this with your OAuth2.0
  Client secret) In the db section, replace the following: user (Replace
  this with your MySQL username) pass (Replace this with your MySQL
  password) host (Replace this with your MySQL hostname) name (Replace
  this with the name of the MySQL database you're using.) In the game
  section, replace the following: leaderboardId (Replace this with the
  ID of the leaderboard you created in the previous step.)

Move your AppConstants.ini file outside of your htdocs tree. This contains sensitive information and it shouldn't be located anywhere
  where it could accidentally be displayed to the user.

Update the constructor in your GameHandler file to point to the new location of AppConstants.ini.

That's it! Your application should be ready to run!


问:
Database (database/database.sqlite) does not exist. Database works from artisan tinker
I created my database.sqlite file in the database folder. My .env file contents are :

```<code>DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=absolute\path\to\database\database.sqlite
DB_USERNAME=admin
DB_PASSWORD=
</code>```

When I run php artisan tinker and DB::table('users')->get(); I get the info from the database.

My DatabaseController is:

```<code>class DatabaseController extends Controller
{
    public function main()
    {
        $users = DB::table('users')->get();

        return view('database',compact($users));
    }
}
</code>```

Yet when I request /database path I get the error:

QueryException in Connection.php line 647:
Database (database/database.sqlite) does not exist. (SQL: select * from "users")

UPDATE:
A temporary fix is to change the database.php from the config folder:

```<code>  'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => 'absolute\path\database\database.sqlite',
        'prefix' => '',
    ],
</code>```

Instead of using env('DB_DATABASE', database_path('database.sqlite')), which returns database/database.sqlite not my absolute path.

答:
I ran the following commands:

php artisan config:cache

php artisan config:clear

php artisan serve - restarted the server

Body:
I created my database.sqlite file in the database folder. My .env file contents are :

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=absolute\path\to\database\database.sqlite
DB_USERNAME=admin
DB_PASSWORD=

When I run php artisan tinker and DB::table('users')->get(); I get the info from the database.

My DatabaseController is:

class DatabaseController extends Controller
{
    public function main()
    {
        $users = DB::table('users')->get();

        return view('database',compact($users));
    }
}

Yet when I request /database path I get the error:

QueryException in Connection.php line 647:
Database (database/database.sqlite) does not exist. (SQL: select * from "users")

UPDATE:
A temporary fix is to change the database.php from the config folder:

  'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => 'absolute\path\database\database.sqlite',
        'prefix' => '',
    ],

Instead of using env('DB_DATABASE', database_path('database.sqlite')), which returns database/database.sqlite not my absolute path.


问:
"Call to Node module failed with error"s with Angular2 & ASP.NET
I'm getting an intermittent exception with my ASP.NET Core Angular 2 web-app:

```<code>Exception: Call to Node module failed with error: Error: This method is not implemented in Parse5DomAdapter: Parse5DomAdapter#getCookie
 at _notImplemented (D:\Projects\MyProject\MyProject\node_modules\angular2-platform-node\parse5-adapter.js:22:12)
 at Parse5DomAdapter.getCookie (D:\Projects\MyProject\MyProject\node_modules\angular2-platform-node\parse5-adapter.js:641:15)
 at CookieXSRFStrategy.configureRequest (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1597:92)
 at XHRBackend.createConnection (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1637:32)
 at httpRequest (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1975:24)
 at Http.get (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:2086:20)
 at ApiService.getChatMessages (D:\Projects\MyProject\MyProject\ClientApp\dist\main-server.js:557:20)
 at ChatPageComponent.ngOnInit (D:\Projects\MyProject\MyProject\ClientApp\dist\main-server.js:513:23)
 at AppView._View_ChatPageComponent_Host0.detectChangesInternal (ChatPageComponent_Host.ngfactory.js:30:86)
 at AppView.detectChanges (D:\Projects\MyProject\MyProject\node_modules\@angular\core\bundles\core.umd.js:9566:18)

MoveNext
</code>```

I believe it's something to do with the MVC views, as the error shows:

```<code>MoveNext in Index.cshtml

1.@{
2.    ViewData["Title"] = "Home Page";
3.}
4.
5.<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
6.
7.<script src="~/dist/vendor.js" asp-append-version="true"></script>
8.@section scripts {
</code>```

Which is code in my index.cshtml.

It seems to happen early on after launching the project. It all either works fine, or after loading the home page when any navagation is performed it throws an error.

I can force it to produce the error. I have 4 navagation destinations:

```<code>http://localhost:49954/home
http://localhost:49954/counter
http://localhost:49954/fetch-data
http://localhost:49954/chat-page
</code>```

That were all set up from the Visual Studio Angular 2 template. If I refresh home, everything is fine, and if it's had a chance to load for a while I can navagate to the other pages. However if I type in the url for any of the other pages, it produces this error every single time.

Edit: Also, interestingly, it produces a slightly different error with http://localhost:49954/counter. In my counter page I use an Angular Material Design component:

```<code><div class="mine">
    <h2>
        Counter Test
    </h2>
    <p>This is a simple example of an Angular 2 component.</p>
    <p>Current count:<strong>{{ currentCount }}</strong></p>
    <button md-raised-button (click)="incrementCounter()">Increment</button>
</div>
</code>```

and instead of the above error, it's a similar Call to Node module failed error, but in material design:

```<code>Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: document is not defined
 ReferenceError: document is not defined
 at new RippleRenderer (D:\Projects\MyProject\MyProject\node_modules\@angular\material\material.umd.js:193:31)
</code>```

答:
This worked for me. Change:

```<code><app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
</code>```

to

```<code><app asp-ng2-prerender-module="ClientApp/dist/main-server">Loading...</app>
</code>```

in the index.html

Body:
I'm getting an intermittent exception with my ASP.NET Core Angular 2 web-app:

Exception: Call to Node module failed with error: Error: This method is not implemented in Parse5DomAdapter: Parse5DomAdapter#getCookie
 at _notImplemented (D:\Projects\MyProject\MyProject\node_modules\angular2-platform-node\parse5-adapter.js:22:12)
 at Parse5DomAdapter.getCookie (D:\Projects\MyProject\MyProject\node_modules\angular2-platform-node\parse5-adapter.js:641:15)
 at CookieXSRFStrategy.configureRequest (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1597:92)
 at XHRBackend.createConnection (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1637:32)
 at httpRequest (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:1975:24)
 at Http.get (D:\Projects\MyProject\MyProject\node_modules\@angular\http\bundles\http.umd.js:2086:20)
 at ApiService.getChatMessages (D:\Projects\MyProject\MyProject\ClientApp\dist\main-server.js:557:20)
 at ChatPageComponent.ngOnInit (D:\Projects\MyProject\MyProject\ClientApp\dist\main-server.js:513:23)
 at AppView._View_ChatPageComponent_Host0.detectChangesInternal (ChatPageComponent_Host.ngfactory.js:30:86)
 at AppView.detectChanges (D:\Projects\MyProject\MyProject\node_modules\@angular\core\bundles\core.umd.js:9566:18)

MoveNext

I believe it's something to do with the MVC views, as the error shows:

MoveNext in Index.cshtml

1.@{
2.    ViewData["Title"] = "Home Page";
3.}
4.
5.<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
6.
7.
8.@section scripts {

Which is code in my index.cshtml.

It seems to happen early on after launching the project. It all either works fine, or after loading the home page when any navagation is performed it throws an error.

I can force it to produce the error. I have 4 navagation destinations:

http://localhost:49954/home
http://localhost:49954/counter
http://localhost:49954/fetch-data
http://localhost:49954/chat-page

That were all set up from the Visual Studio Angular 2 template. If I refresh home, everything is fine, and if it's had a chance to load for a while I can navagate to the other pages. However if I type in the url for any of the other pages, it produces this error every single time.

Edit: Also, interestingly, it produces a slightly different error with http://localhost:49954/counter. In my counter page I use an Angular Material Design component:

        Counter Test

This is a simple example of an Angular 2 component.

Current count:{{ currentCount }}

    <button md-raised-button (click)="incrementCounter()">Increment</button>

and instead of the above error, it's a similar Call to Node module failed error, but in material design:

Exception: Call to Node module failed with error: Error: Uncaught (in promise): ReferenceError: document is not defined
 ReferenceError: document is not defined
 at new RippleRenderer (D:\Projects\MyProject\MyProject\node_modules\@angular\material\material.umd.js:193:31)

Body:
This worked for me. Change:

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

to

<app asp-ng2-prerender-module="ClientApp/dist/main-server">Loading...</app>

in the index.html


问:
How to programmatically logon to a URL, keep the session, and browse around to different pages
I am working on small Java project to programmatically connect to a website with username/password, after login, browse to different links on the site to download some data. First, I need to connect to the website with username/password,
second, while I keep the session open, go to other links to download data.

How do I do this in Java?

Any help will be highly appreciated!

答: If you want to extract some data HtmlUnit can help you a lot it can manage the authentication and also help you with data extraction.</p>


答:
When you want to pass parameters through the function, you can use "=" instead of "&" for that attr binding, and in your HTML, you can specify like this:

```<code><input type="file" ng-upload-change="uploadFile" ... />
</code>```

And, I changed the way you were passing an object of params since there is no need to create that object.

Now, if you see the code snippet below, it correctly logs id: x (0-based) on each file upload.

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
myApp.controller('MyCtrl', function MyCtrl($scope) {
  $scope.myArray = [1, 2, 3, 4, 5];
  $scope.uploadFile = function($event, $id) {
    var files = $event.target.files;
    console.log("id: " + $id);
  };
});

myApp.directive('ngUploadChange', function() {
  return {
    scope: {
      ngUploadChange: "=",
      myId: "="
    },
    link: function($scope, $element, $attrs) {
      $element.on("change", function(event) {
        $scope.ngUploadChange(event, $scope.myId);
      })
      $scope.$on("$destroy", function() {
        $element.off();
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="data in myArray">
    <input type="file" ng-upload-change="uploadFile" my-id="$index">
  </div>
</div></code>```

Title: AngularJs #how to pass scope variable in on change event in directive in input file

Body:
When you want to pass parameters through the function, you can use "=" instead of "&" for that attr binding, and in your HTML, you can specify like this:

<input type="file" ng-upload-change="uploadFile" ... />

And, I changed the way you were passing an object of params since there is no need to create that object.

Now, if you see the code snippet below, it correctly logs id: x (0-based) on each file upload.

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
myApp.controller('MyCtrl', function MyCtrl($scope) {
  $scope.myArray = [1, 2, 3, 4, 5];
  $scope.uploadFile = function($event, $id) {
    var files = $event.target.files;
    console.log("id: " + $id);
  };
});

myApp.directive('ngUploadChange', function() {
  return {
    scope: {
      ngUploadChange: "=",
      myId: "="
    },
    link: function($scope, $element, $attrs) {
      $element.on("change", function(event) {
        $scope.ngUploadChange(event, $scope.myId);
      })
      $scope.$on("$destroy", function() {
        $element.off();
      });
    }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="data in myArray">
    <input type="file" ng-upload-change="uploadFile" my-id="$index">
  </div>
</div>


问:
Error in paste using hmd.mx
I'm a newbie in R and have been suggested to use the package Demography in R. My data will be read in from mortality.org and the package has a function named hmd.mx. Following is run

```<code>m_data<-hmd.mx("SWE", username@gmail.com, password, "Sweden")
</code>```

The error I get is

```<code>Error in paste(username, ":", password, sep = "") :
  object 'username' not found
</code>```

I tried finding similar issue online but find nothing like it. Can anyone guide me?

答: Thanks for the comment. The issue was the missing " around password and username. </p>

Title: Error in paste using hmd.mx

Body:
I'm a newbie in R and have been suggested to use the package Demography in R. My data will be read in from mortality.org and the package has a function named hmd.mx. Following is run

m_data<-hmd.mx("SWE", username@gmail.com, password, "Sweden")

The error I get is

Error in paste(username, ":", password, sep = "") :
  object 'username' not found

I tried finding similar issue online but find nothing like it. Can anyone guide me?