问:
Facebook like or share with dynamic document title
I found this problem all over the net but no answer yet, so maybe here someone solved it ...?
I built a page relying heavily on jquery.address. It's got one index page and the rest loads dynamically via Ajax following Google's /#!/ scheme for crawlable pages. Now I want to add Facebooks Like or share button but I can't get it to grab the actual page title or url.

Whatever I do, it always falls back to title and url of the index page. It tried:

(obviously) changing title an openGraph meta on load of the new parts.

"linking" the crawler page (?_escaped_fragmet_=xyx) but specifying the #! page in meta

"sharing" with a given title and url.

I never get anything but a link to the index page or a blank "share" to the right url with title and thumbnail ignored.

Has anyone got a similar setup working?

Thanks for any hints,
thomas

答: My guess would be that Facebook's crawler doesn't run Javascript and will always display whatever's actually in the page it gets from the server.</p>


来源: stackexchange

问:
In an example for a worldmap for d3v4 world_countries.json can't be found
When running the examaple found over here: http://bl.ocks.org/micahstubbs/8e15870eb432a21f0bc4d3d527b2d14f

I get the error that world_countries.json can't be found:

Failed to load resource: the server responded with a status of 404
  (Not Found)   http://localhost:8000/world_countries.json

world_countries.json is used in this piece of code:

```<code>queue()
    .defer(d3.json, "world_countries.json")
    .defer(d3.tsv, "world_population.tsv")
    .await(ready);
</code>```

I figured that world_countries.json might come from topojson, this is the way I load in the existing libraries

```<code>    <script src="http://d3js.org/queue.v1.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="js/graphs/d3-tip.js"></script>
    <script src="js/graphs/map.js"></script>
</code>```

I was really hoping someone could help me out here!

答:
from the terminal:

curl -O https://raw.githubusercontent.com/jdamiani27/Data-Visualization-and-D3/master/lesson4/world_countries.json

this will download https://raw.githubusercontent.com/jdamiani27/Data-Visualization-and-D3/master/lesson4/world_countries.json to your current working directory.

or just visit https://raw.githubusercontent.com/jdamiani27/Data-Visualization-and-D3/master/lesson4/world_countries.json in the browser, select-all, copy, paste into your favorite text editor and save as world_countries.json, in the same directory as the other files from the d3 example that you are working with.

good luck!

ContentLicense: CC BY-SA 3.0

Body:
When running the examaple found over here: http://bl.ocks.org/micahstubbs/8e15870eb432a21f0bc4d3d527b2d14f

I get the error that world_countries.json can't be found:

Failed to load resource: the server responded with a status of 404
  (Not Found)   http://localhost:8000/world_countries.json

world_countries.json is used in this piece of code:

queue()
    .defer(d3.json, "world_countries.json")
    .defer(d3.tsv, "world_population.tsv")
    .await(ready);

I figured that world_countries.json might come from topojson, this is the way I load in the existing libraries

I was really hoping someone could help me out here!


问:
How to load User Profile Type in Drupal 8?
I would like to load user profile module data by user id:

Code:

```<code>$profile_type = 'my_profile';
$user_id = 1;
$current_user = User::load($user_id);
$active_profile = $this->entityTypeManager()->getStorage('profile')->loadByUser($current_user, $profile_type);

print_r($active_profile);
</code>```

But, It will return following error.

Error:

```<code>The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 1 passed to Drupal\profile\ProfileStorage::loadByUser() must implement interface Drupal\Core\Session\AccountInterface, null given, called in C:\xampp\htdocs\catchow\htdocs\modules\custom\catchow_registration_contactlab\src\Controller\CatchowRegistrationContactlabController.php on line 122 and defined in Drupal\profile\ProfileStorage->loadByUser() (line 16 of modules\contrib\profile\src\ProfileStorage.php).
Drupal\profile\ProfileStorage->loadByUser(NULL, 'authenticated_user') (Line: 122)
</code>```

答:
Did you try to use user_load function instead of User::Load :

```<code>$current_user = user_load($user_id);
</code>```

https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_load/8.2.x

And when you are dumping $current_user do you have some data ?

Body:
I would like to load user profile module data by user id:

Code:

$profile_type = 'my_profile';
$user_id = 1;
$current_user = User::load($user_id);
$active_profile = $this->entityTypeManager()->getStorage('profile')->loadByUser($current_user, $profile_type);

print_r($active_profile);

But, It will return following error.

Error:

The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 1 passed to Drupal\profile\ProfileStorage::loadByUser() must implement interface Drupal\Core\Session\AccountInterface, null given, called in C:\xampp\htdocs\catchow\htdocs\modules\custom\catchow_registration_contactlab\src\Controller\CatchowRegistrationContactlabController.php on line 122 and defined in Drupal\profile\ProfileStorage->loadByUser() (line 16 of modules\contrib\profile\src\ProfileStorage.php).
Drupal\profile\ProfileStorage->loadByUser(NULL, 'authenticated_user') (Line: 122)

Body:
Did you try to use user_load function instead of User::Load :

$current_user = user_load($user_id);

https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_load/8.2.x

And when you are dumping $current_user do you have some data ?


问:
Get line number of beginning and end of Ruby method given a ruby file
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

```<code>1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end
</code>```

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

答:
Ruby has a source_location method which gives you the file and the beginning line:

```<code>class Home
  def initialize(color)
    @color = color
  end
end

p Home.new(1).method(:initialize).source_location
# => ["test2.rb", 2]
</code>```

To find the end, perhaps look for the next def or EOF.

Body:
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

Body:
Ruby has a source_location method which gives you the file and the beginning line:

class Home
  def initialize(color)
    @color = color
  end
end

p Home.new(1).method(:initialize).source_location
# => ["test2.rb", 2]

To find the end, perhaps look for the next def or EOF.


问:
PHP encryption using OpenSSL
I have been trying to write two functions that will encrypt and decrypt my data, as I'm storing some information that I don't want going into database in plain text. The function that encrypts works fine. But I don't know why the decryption doesn't bring back the plain text?

Is there something I have done wrong?

```<code><?php
$string = "This is my string!";

$encryption_key = "DVF0!LoQs2bPyTvSF0epXPFStbIn!057";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));

function encryptString($encryption_key, $iv, $string) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = openssl_encrypt($string, AES_256_CBC, $encryption_key, 0, $iv);
    return $encrypted;
}

function decryptString($encryption_key, $iv, $encrypted) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = $encrypted . ':' . $iv;
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], AES_256_CBC, $encryption_key, 0, $parts[1]);
    return $decrypted;
}

$encryptstring = encryptString($encryption_key, $iv, $string);
$decryptstring = decryptString($encryption_key, $iv, $encryptstring);
?>
</code>```

Original: <? print $string; ?>

Encryption Key: <?php print $encryption_key; ?>

Encrypted func: <?php print $encryptstring; ?>

Decrypted func: <?php print $decryptstring; ?>

答:
Your encryption key changes with each function call using openssl_random_pseudo_bytes

Make the key static such as $encryption_key = "XXXX"; or global the variable and only call it once.

Don't forget to apply that to your $iv as well.

Title: PHP encryption using OpenSSL

Body:
I have been trying to write two functions that will encrypt and decrypt my data, as I'm storing some information that I don't want going into database in plain text. The function that encrypts works fine. But I don't know why the decryption doesn't bring back the plain text?

Is there something I have done wrong?

<?php
$string = "This is my string!";

$encryption_key = "DVF0!LoQs2bPyTvSF0epXPFStbIn!057";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));

function encryptString($encryption_key, $iv, $string) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = openssl_encrypt($string, AES_256_CBC, $encryption_key, 0, $iv);
    return $encrypted;
}

function decryptString($encryption_key, $iv, $encrypted) {
    define('AES_256_CBC', 'aes-256-cbc');
    $encrypted = $encrypted . ':' . $iv;
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], AES_256_CBC, $encryption_key, 0, $parts[1]);
    return $decrypted;
}

$encryptstring = encryptString($encryption_key, $iv, $string);
$decryptstring = decryptString($encryption_key, $iv, $encryptstring);
?>

Original: <? print $string; ?>

Encryption Key: <?php print $encryption_key; ?>

Encrypted func: <?php print $encryptstring; ?>

Decrypted func: <?php print $decryptstring; ?>


问:
Unable to pass props to child component in react
I'm still getting to grips with react but I can't see why this isn't working, it should be passing the props from tabs into <Tab /> and outputting the button each time.

If I put no text next to {this.props.content} it doesn't display anything, if I put testText next to {this.props.content} it will output the button 5 times but only display testText not the name field it should be displaying via the content={item.name} prop

```<code>class TopCategories extends React.Component {

render() {
const Tab = () => (
  <TestBtn key={this.props.key} >
   testText {this.props.content}
  </TestBtn>
)

const items = [
  { id: 1, name: 'tab-1', text: 'text' },
  { id: 2, name: 'tab-2', text: 'text' },
  { id: 3, name: 'tab-3', text: 'text' },
  { id: 4, name: 'tab-4', text: 'text' },
  { id: 5, name: 'tab-5', text: 'text' },
]

const tabs = items.map(item =>
  <Tab key={item.id} content={item.name} />,
)

return (
  <Container>
    <Wrapper>
      {tabs}
    </Wrapper>
  </Container>
  )
 }
}

 export default TopCategories
</code>```

答:
You need to pass props to the stateless function and since it's a stateless component, this is not available. It should be something like:</p>

```<code>const Tab = (props) => {
   return (
       <TestBtn key={props.key} >
           testText {props.content}
       </TestBtn>
   );
 }
</code>```

Body:
I'm still getting to grips with react but I can't see why this isn't working, it should be passing the props from tabs into <Tab /> and outputting the button each time.

If I put no text next to {this.props.content} it doesn't display anything, if I put testText next to {this.props.content} it will output the button 5 times but only display testText not the name field it should be displaying via the content={item.name} prop

class TopCategories extends React.Component {

render() {
const Tab = () => (
  <TestBtn key={this.props.key} >
   testText {this.props.content}
  </TestBtn>
)

const items = [
  { id: 1, name: 'tab-1', text: 'text' },
  { id: 2, name: 'tab-2', text: 'text' },
  { id: 3, name: 'tab-3', text: 'text' },
  { id: 4, name: 'tab-4', text: 'text' },
  { id: 5, name: 'tab-5', text: 'text' },
]

const tabs = items.map(item =>
  <Tab key={item.id} content={item.name} />,
)

return (
  <Container>
    <Wrapper>
      {tabs}
    </Wrapper>
  </Container>
  )
 }
}

 export default TopCategories

Body:
You need to pass props to the stateless function and since it's a stateless component, this is not available. It should be something like:

const Tab = (props) => {
   return (
       <TestBtn key={props.key} >
           testText {props.content}
       </TestBtn>
   );
 }


问:
Extract Custom object from ruby collection
I have a custom object, very simple jsut to try and figure out how ruby works.

```<code>    class SomeObject
  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end
</code>```

I'm then running a search using chef, and creating several of these objects and adding them to a collection : collection = [] and then collection << myObject where myObject is myObject = SomeObject.new('someName')

I'm them trying to iterate over this collection, get the object and call sayHello.

```<code>collection.each do |i|
  p "Something...."
  p i.name #fails
  #i.sayHello # fails

end
</code>```

Can anyone tell me where I'm going wrong or how I might achieve this?  Thanks.

Edit:  If I print 'i' to the screen I get

<#::SomeObject:0x00000005546a50 @myName="some-name">

So I'm sure its being created and is in the collection, i jsut can't get the thing out :D

答:
Your instance variable is named @myName not @name, additionally you need to allow your instance variable to be read publicly using the attr_reader directive:

```<code>class SomeObject
  attr_reader :myName

  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end

collection = [ SomeObject.new('Hunter') ]
collection.each do |i|
  puts i.myName # output= Hunter
  i.sayHello()  # output= Hello Hunter
end
</code>```

Body:
I have a custom object, very simple jsut to try and figure out how ruby works.

    class SomeObject
  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end

I'm then running a search using chef, and creating several of these objects and adding them to a collection : collection = [] and then collection << myObject where myObject is myObject = SomeObject.new('someName')

I'm them trying to iterate over this collection, get the object and call sayHello.

collection.each do |i|
  p "Something...."
  p i.name #fails
  #i.sayHello # fails

end

Can anyone tell me where I'm going wrong or how I might achieve this?  Thanks.

Edit:  If I print 'i' to the screen I get

<#::SomeObject:0x00000005546a50 @myName="some-name">

So I'm sure its being created and is in the collection, i jsut can't get the thing out :D

Body:
Your instance variable is named @myName not @name, additionally you need to allow your instance variable to be read publicly using the attr_reader directive:

class SomeObject
  attr_reader :myName

  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end

collection = [ SomeObject.new('Hunter') ]
collection.each do |i|
  puts i.myName # output= Hunter
  i.sayHello()  # output= Hello Hunter
end


问:
scheme style guide
I've done some Googling for a Scheme style guide, but haven't come up with anything as easily refereceable and concrete as, say, the Google Style Guide for C++. The best I've found so far is this guy. Are there Scheme style guides out there that are as good or better?</p>

答: "That guy" is quite good and you should read that.</p>

ContentLicense: CC BY-SA 2.5

Title: scheme style guide


问:
adding Datatables sorting to PHP page
I have tried to add datatables to my PHP web apps table. I have followed the instructions and add a thead and tbody tag, also the link at the top and the document.ready in the script tags at the bottom. Nothing seems to be working. any ideas?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link rel="stylesheet" type="text/css" href="css/style.css">

<title>View Records</title>

GCS Reproduction Environment

All Reproductions

<?php

/*

VIEW.PHP

Displays all data from 'players' table

*/

// connect to the database

include('php/connect-db.php');

// ordering the ID function

$ascdesc = "";
$order = isset($_GET['sort'])?$_GET['sort']:'id';

$ascdesc = isset($_GET['ascdesc'])?$_GET['ascdesc']:'DESC';
switch(strtoupper($ascdesc))
  {
  case 'DESC': $ascdesc = 'ASC'; break;
  case 'ASC': $ascdesc = 'DESC'; break;
  default: $ascdesc = 'DESC'; break;
  }

// get results from database

$result = mysql_query("SELECT * FROM players ORDER BY $order $ascdesc")

or die(mysql_error());

// display data in table

echo "
";
echo "

 ID	 Administration Console	 Product Version	 Platform	 Database	 Owner	 Status

";

// loop through results of database query, displaying them in the table

while($row = mysql_fetch_array( $result )) {

// echo out the contents of each row into a table
echo "
";

echo "
";

echo '' . $row['id'] . '	';

echo ''.$row['curl'].'	';

echo '' . $row['pversion'] . '	';

echo '' . $row['platform'] . '	';

echo '' . $row['dversion'] . '	';

echo '' . $row['email'].'	';

echo '' . $row['status'] .'	';

echo 'Edit	';

echo 'Delete	';

echo "
";

echo "
";

}

// close table>

echo "
";

?>

Add a new record

```

答:
You don't have to use # to specify ID. Change the following
echo "
";

to
    echo "
";

Also, you are including multiple versions of jQuery. You may only include

Note that the original mysql extension is deprecated. (http://php.net/manual/en/migration55.deprecated.php)

Title: adding Datatables sorting to PHP page

Body:
You don't have to use # to specify ID. Change the following
echo "<table id='#myTable' align='center' border='1' cellpadding='2'>";

to
    echo "<table id='myTable' align='center' border='1' cellpadding='2'>";

Also, you are including multiple versions of jQuery. You may only include
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Note that the original mysql extension is deprecated. (http://php.net/manual/en/migration55.deprecated.php)


问:
Webpack regex test for .js & .jsx
I'm using webpack and wondering if there is a way to determine .js or .jsx file extensions with the test regex?

i.e.

```<code>test: /\.jsx?$/
</code>```

Would this work?

答:
Yes. test: /.jsx?$/ should be the right way. But you also need to set resolve.extensions parameter to make it work.

```<code>module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.jsx']
  }
  ...
}
</code>```

Title: Webpack regex test for .js & .jsx

Body:
I'm using webpack and wondering if there is a way to determine .js or .jsx file extensions with the test regex?

i.e.

test: /\.jsx?$/

Would this work?

Body:
Yes. test: /.jsx?$/ should be the right way. But you also need to set resolve.extensions parameter to make it work.

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.jsx']
  }
  ...
}


问:
How to escape single quote (') in Thymeleaf

I want this to output

What's up?

But I get an TemplateInputException. I have tried with HTML entity but it fails the same.

答:
maybe use htm ascii code : '

```<code><h1 th:text="${'What's up?'}"></h1>
</code>```

Body:
maybe use htm ascii code : &#39;

<h1 th:text="${'What&#39;s up&#63;'}"></h1>


问:
CSS div (absolute within relative)
How i can make 2 different divs elements A and B what they are included on a div element C .

A and B to start from the same corner from top left, i try to change A and B to position absolute and working but i need A to keep it via position relative. the code can be found here https://jsfiddle.net/bms1upkn/2/

Html

```<code><div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

</div>
</code>```

CSS

```<code>.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
}
.a {
  position: relative;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}
</code>```

答:
Not sure if this is what you want? Your description is difficult to comprehend.

https://jsfiddle.net/bms1upkn/4/

CSS:

```<code>.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
  position:relative;
}
.a {
  position: absolute;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}
</code>```

Title: CSS div (absolute within relative)

Body:
How i can make 2 different divs elements A and B what they are included on a div element C .

A and B to start from the same corner from top left, i try to change A and B to position absolute and working but i need A to keep it via position relative. the code can be found here https://jsfiddle.net/bms1upkn/2/

Html

CSS

.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
}
.a {
  position: relative;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}

Body:
Not sure if this is what you want? Your description is difficult to comprehend.

https://jsfiddle.net/bms1upkn/4/

CSS:

.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
  position:relative;
}
.a {
  position: absolute;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}


问:
Prompt when trying to dial a phone number using tel:// scheme on iOS 10.3
After updating to 10.3, my app no longer automatically dials a phone number after pressing the call button in my app using the openURL: options: completionHandler: method.

Instead, a prompt comes up every time to confirm the user's intentions.

As per the Apple Documentation:

The tel URL scheme is used to launch the Phone app on iOS devices and initiate dialing of the specified phone number. When a user taps a telephone link in a webpage, iOS displays an alert asking if the user really wants to dial the phone number and initiates dialing if the user accepts. When a user opens a URL with the tel scheme in a native app, iOS does not display an alert and initiates dialing without further prompting the user. However, a native app can be configured to display its own alert.

According to this, the prompt displays for webpages but doesn't display in a native iOS app.

Could this be a bug in 10.3? Or is there a new function I need to use or a new property to include in the info.plist I do not know about?

Thanks.

答:
This is listed as a known issue in the 10.3 release notes.

https://developer.apple.com/library/content/releasenotes/General/RN-iOSSDK-10.3/

openURL

When a third party application invokes openURL: on a tel://,
  facetime://, or facetime-audio:// URL, iOS displays a prompt and
  requires user confirmation before dialing.

It is also listed in the Security content of the 10.3 update, so I'm assuming this a new feature that is here to stay.

An issue existed in iOS allowing for calls without prompting.  This
  issue was addressed by prompting a user to confirm call initiation.


问:
How does the :type field get populated in Single Table Inheritance?
I asked a question earlier about how to structure the data in a simple app I am building to manage content. The answer was to look at Single Table Inheritance and I think it's going to be the ticket.

I've read quite a few examples but one thing that always seems to be left out is how the :type column is actually populated? Do I include a form field w/ a drop down so the user can select the types?

I believe I fully understand how STI works now (the type field takes on the class name) but am still missing something very basic (and probably very obvious, but I'm missing it). Can someone fill me in?

I have a content table like so:

```<code>id
type
name
desc
</code>```

And the different types would be "Site", "Blog", "Photo".

答:
@jyoseph, yes you are absolutely correct. You can add a drop-down in you new and edit view which will hold the types, in your case "Site", "Blog", "Photo". You can also make a helper in your Application Helper file as follows

```<code>def content_type
   return ["Site", "Blog", "Photo"]
end
</code>```

and then in your contents/new.html.erb you can do

```<code><p>
    <%= f.label :type %><br />
    <%= f.select :type, content_type %>
</p>
</code>```

Try it, this might work.

Just in case if anyone wants to know more about STI visit my Blog

Body:
I asked a question earlier about how to structure the data in a simple app I am building to manage content. The answer was to look at Single Table Inheritance and I think it's going to be the ticket.

I've read quite a few examples but one thing that always seems to be left out is how the :type column is actually populated? Do I include a form field w/ a drop down so the user can select the types?

I believe I fully understand how STI works now (the type field takes on the class name) but am still missing something very basic (and probably very obvious, but I'm missing it). Can someone fill me in?

I have a content table like so:

id
type
name
desc

And the different types would be "Site", "Blog", "Photo".

Body:
@jyoseph, yes you are absolutely correct. You can add a drop-down in you new and edit view which will hold the types, in your case "Site", "Blog", "Photo". You can also make a helper in your Application Helper file as follows

def content_type
   return ["Site", "Blog", "Photo"]
end

and then in your contents/new.html.erb you can do

<p>
    <%= f.label :type %><br />
    <%= f.select :type, content_type %>
</p>

Try it, this might work.

Just in case if anyone wants to know more about STI visit my Blog


问:
gradle transitive dependencies download local ivy
I have a project that i am coverting to gradle. the project has some dependencies like junit etc.
The Jars for the dependencies get downloaded but the dependencies of those Jars are not downloaded.
The build.gradle file is as follows

```<code>apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

repositories {
     ivy  {
        url 'http://localserver/repo'
        layout 'pattern', {
              artifact 'snapshot/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              artifact '3rd-party/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              artifact 'b2bdev/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              file 'snapshot/[organisation]/[module]/ivys/ivy-[revision].xml'
              file '3rd-party/[organisation]/[module]/ivys/ivy-[revision].xml'
        }
    }
}

targetCompatibility = sourceCompatibility = JavaVersion.VERSION_1_6

dependencies {
    testCompile('test:project:17.20.SNAPSHOT') {
        transitive = true
    }
    testCompile('org.hibernate.common:hibernate-commons-annotations:4.0.1.Final') {
        transitive = false
    }
    testCompile('org.hibernate:hibernate-ehcache:4.1.2.Final') {
        transitive = false
    }
    testCompile('org.javassist:javassist:3.16.1-GA') {
        transitive = false
    }
    compileOnly('javax.servlet:javax.servlet-api:3.0.1') {
        transitive = false
    }
    compileOnly('dom4j:dom4j:1.6.1') {
        transitive = false
    }
}
</code>```

Why is the Jars required by test:project:17.20.SNAPSHOT not downloaded ?
this thing works with ant+ivy project

Update 1

I have added the ivy.xml file of test project

```<code><ivy-module xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info organisation="test" module="project" revision="17.20.SNAPSHOT" status="integration" publication="434334345"></info>
<configurations>
<conf name="test" visibility="public" description="Dependencies needed only for testing"/>
<conf name="compile" visibility="public" description="Dependencies required for compile time that are not provided by a container"/>
<conf name="runtime" extends="compile" visibility="public" description="Dependencies not needed for compile time but are needed for runtime"/>
<conf name="provided" visibility="public" description="Dependencies provided by a container"/>
<conf name="ear" visibility="public" description="Dependencies managed by ear level classloader"/>
<conf name="war" visibility="public" description="Dependencies managed by war level classloader"/>
<conf name="default" visibility="public"/>
<conf name="optional" visibility="public"/>
<conf name="sources" visibility="public"/>
</configurations>
<publications>
<artifact name="project"/>
<artifact name="project-sources" type="src" ext="jar" conf="sources"/>
</publications>
<dependencies>

<!--  Spring and related dependencies  -->
<dependency org="org.springframework" name="spring-core" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-context" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-web" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-beans" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-expression" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-aop" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-orm" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-tx" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-jdbc" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-test" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-context-support" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-oxm" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.data" name="spring-data-neo4j" rev="2.1.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.data" name="spring-data-neo4j-tx" rev="2.1.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.batch" name="spring-batch-core" rev="2.1.8.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.batch" name="spring-batch-infrastructure" rev="2.1.8.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-core" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-web" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-config" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-ldap" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.ldap" name="spring-ldap" rev="1.3.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
</ivy-module>
</code>```

答:
I think it might be because of your configuration in ivy.xml ties them up to compile default and Gradle is trying to resolve default configuration which doesnt have anything declared.

You might try to:
create a new configuration configurations.add("yourConf")
and extend it from compile configurations.yourConf.extendsFrom(configurations.compile)
and use it for test project

or extend the 'default' configuration from compile

```<code>configurations.add("default")
configurations.default.extendsFrom(configurations.compile)
</code>```

or try to delete/change the conf from ivy.xml

if you're not able to to this you might want to play with some groovy to do it.

```<code>asNode().dependencies.dependency.findAll { it.@conf }.each { it.attributes().remove("conf") }
</code>```

Body:
I have a project that i am coverting to gradle. the project has some dependencies like junit etc.
The Jars for the dependencies get downloaded but the dependencies of those Jars are not downloaded.
The build.gradle file is as follows

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

repositories {
     ivy  {
        url 'http://localserver/repo'
        layout 'pattern', {
              artifact 'snapshot/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              artifact '3rd-party/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              artifact 'b2bdev/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]'
              file 'snapshot/[organisation]/[module]/ivys/ivy-[revision].xml'
              file '3rd-party/[organisation]/[module]/ivys/ivy-[revision].xml'
        }
    }
}

targetCompatibility = sourceCompatibility = JavaVersion.VERSION_1_6

dependencies {
    testCompile('test:project:17.20.SNAPSHOT') {
        transitive = true
    }
    testCompile('org.hibernate.common:hibernate-commons-annotations:4.0.1.Final') {
        transitive = false
    }
    testCompile('org.hibernate:hibernate-ehcache:4.1.2.Final') {
        transitive = false
    }
    testCompile('org.javassist:javassist:3.16.1-GA') {
        transitive = false
    }
    compileOnly('javax.servlet:javax.servlet-api:3.0.1') {
        transitive = false
    }
    compileOnly('dom4j:dom4j:1.6.1') {
        transitive = false
    }
}

Why is the Jars required by test:project:17.20.SNAPSHOT not downloaded ?
this thing works with ant+ivy project

Update 1

I have added the ivy.xml file of test project

<ivy-module xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info organisation="test" module="project" revision="17.20.SNAPSHOT" status="integration" publication="434334345"></info>
<configurations>
<conf name="test" visibility="public" description="Dependencies needed only for testing"/>
<conf name="compile" visibility="public" description="Dependencies required for compile time that are not provided by a container"/>
<conf name="runtime" extends="compile" visibility="public" description="Dependencies not needed for compile time but are needed for runtime"/>
<conf name="provided" visibility="public" description="Dependencies provided by a container"/>
<conf name="ear" visibility="public" description="Dependencies managed by ear level classloader"/>
<conf name="war" visibility="public" description="Dependencies managed by war level classloader"/>
<conf name="default" visibility="public"/>
<conf name="optional" visibility="public"/>
<conf name="sources" visibility="public"/>
</configurations>
<publications>
<artifact name="project"/>
<artifact name="project-sources" type="src" ext="jar" conf="sources"/>
</publications>
<dependencies>

<dependency org="org.springframework" name="spring-core" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-context" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-web" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-beans" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-expression" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-aop" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-orm" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-tx" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-jdbc" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-test" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-context-support" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework" name="spring-oxm" rev="4.1.6.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.data" name="spring-data-neo4j" rev="2.1.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.data" name="spring-data-neo4j-tx" rev="2.1.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.batch" name="spring-batch-core" rev="2.1.8.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.batch" name="spring-batch-infrastructure" rev="2.1.8.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-core" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-web" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-config" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.security" name="spring-security-ldap" rev="3.2.4.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
<dependency org="org.springframework.ldap" name="spring-ldap" rev="1.3.0.RELEASE" transitive="false" conf="compile->default; war->default; ear->default"/>
</ivy-module>

Body:
I think it might be because of your configuration in ivy.xml ties them up to compile default and Gradle is trying to resolve default configuration which doesnt have anything declared.

You might try to:
create a new configuration configurations.add("yourConf")
and extend it from compile configurations.yourConf.extendsFrom(configurations.compile)
and use it for test project

or extend the 'default' configuration from compile

configurations.add("default")
configurations.default.extendsFrom(configurations.compile)

or try to delete/change the conf from ivy.xml

if you're not able to to this you might want to play with some groovy to do it.

asNode().dependencies.dependency.findAll { it.@conf }.each { it.attributes().remove("conf") }


问:
Plotting logarthmic chart - N log N in Excel
I am currently analysing and profiling Quick Sort with numerous data size. I have already collected the required data from the profiler. And I have also plotted the graph for the average run time against the data size.

Now I would like to plot the N log N chart as well so that I can compare the theoritical data against the data I have. However I am not able to plot the N log N graph using excel.

There is an option under Chart Design --> Add Chart Element --> Trendline --> Logarithmic. It also gives us the option to customise it as shown below.

However I am not entirely sure about plotting N log N using this feature. I need this for analysing the Quick Sort and few other sort algorithms.

答:
You have time(y-axis) and n(x-axis) and as you already did, you can plot a graph and get the trendline easily by using some options in Chart dialogue.

More importantly, you can also get the trendline equation by linest() (for linear regression). You should search and learn how to use linest() for sure. In short, what you have to do now is just to add another column and fill it n * log and then use linest() with those columns.

The image is a portion of what I have done many years ago. B3:B11 is n and L3:L11 is time for randomized input data. As you can see, you can say that for randomized input, quicksort's performance is the most well fitted to n*log(n) because its R^2 (L21, which you should look carefully its forumula) is very close to 1.0 and the largest among n and n^2. Likewise, for already sorted(M3:M11) or reversly sorted(N3:N11) input, you can see and say that its performance is almost n^2. Hope this will help you.


问:
Loop with output save for levels of factor variable
I'm working with a large dataset (18 million observations).

I have one continuous variable X in particular that I need to analyze, by a factor variable with about 6k levels. I'd like help in creating a loop function that for each level of the factor variable, will give me the mean and standard deviation for X, save the mean and standard deviation and then move on to the next level of the factor and repeat.

I'm thinking that a loop will solve this problem, as I need to repeat this procedure for ~6,000 levels of the factor. I especially would like to know how to tell Stata to move on to the next factor level once it finishes with the previous, and save the mean & standard deviation without over-writing these statistics for the previous factor level.

Ideally, I'd be able to save the output for each level of the factor to an Excel sheet, with each row representing one level of the factor, and three columns: A would be the factor level, B would be the mean and C would be the standard deviation.

答:
No loop is needed; just use Stata's collapse command:

```<code>set seed 123
clear
set obs 100000
gen x = runiform()
gen a = runiformint(1,60)

collapse (mean) m=x (sd) sd=x, by(a)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
No loop is needed; just use Stata's collapse command:

set seed 123
clear
set obs 100000
gen x = runiform()
gen a = runiformint(1,60)

collapse (mean) m=x (sd) sd=x, by(a)


问:
Download offline maps with Android Mapbox SDK
Android Mapbox SDK support offline downloads (https://www.mapbox.com/android-sdk/examples/offline-manager/). I've setup my own verctor tile server with OpenMapTiles (https://openmaptiles.org/). Does offline functionality work with your own tile server, or is it only supported when using mapbox tiles?</p>

答:
If your tile server is using the same vector tile specification and they load up correctly inside the mapview while online, you shouldn't have any issues.

Just a note that very soon we will be adding a document walking through the offline API here. https://www.mapbox.com/android-docs/map-sdk/5.0.1/getting-started/


问:
MSBuild doesn't show entry target message
I have the following dummy build script files:

Common.targets

```<code><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

    <Target Name="TargetA">
        <Message Text="This is TargetA"/>
    </Target>
    <Target Name="TargetB">
        <Message Text="This is TargetB"/>
    </Target>

</Project>
</code>```

EntryPoint.proj

```<code><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

    <Import Project="Common.targets"/>

    <Target Name="EntryPointTarget" DependsOnTargets="TargetA">
        <!--But why this message is not shown during build?-->
        <Message Text="This is Entry Point Target"/>
    </Target>
</Project>
</code>```

Why is EntryPointTarget message not shown during build?

答:
If you do not specify a target on the commandline and no DefaultTarget is specified then msbuild executes the first target it sees, TargetA in this case. If you switch TargetA and TargetB you'll see TargetB being executed first. If you remove the import and make EntryPointTarget not depend on any other targets EntryPointTarget will be executed. Those aren't proper fixes obviously, so either:

specify the target explicitly call msbuild EntryPoint.proj /t:EntryPointTarget

make it determinstic what gets executed by adding the DefaultTargets=EntryPointTarget attribute to the Project tag, then you can just call msbuild EntryPoint.proj and it will execute EntryPoint.

Body:
I have the following dummy build script files:

Common.targets

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

    <Target Name="TargetA">
        <Message Text="This is TargetA"/>
    </Target>
    <Target Name="TargetB">
        <Message Text="This is TargetB"/>
    </Target>

</Project>

EntryPoint.proj

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

    <Import Project="Common.targets"/>

    <Target Name="EntryPointTarget" DependsOnTargets="TargetA">

        <Message Text="This is Entry Point Target"/>
    </Target>
</Project>

Why is EntryPointTarget message not shown during build?


问:
How to listen for a WebView finishing loading a URL?
I have a WebView that is loading a page from the Internet. I want to show a ProgressBar until the loading is complete.

How do I listen for the completion of page loading of a WebView?

答:
Here's a method which allows you to register a Runnable to be executed once a particular web address has finished loading. We associate each Runnable with a corresponding URL String in a Map, and we use the WebView's getOriginalUrl() method to choose the appropriate callback.

```<code>package io.github.cawfree.webviewcallback;

/**
 *  Created by Alex Thomas (@Cawfree), 30/03/2017.
 **/

import android.net.http.SslError;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;
import java.util.Map;

/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {

    /* Member Variables. */
    private WebView               mWebView;
    private Map<String, Runnable> mCallbackMap;

    /** Create the Activity. */
    @Override protected final void onCreate(final Bundle pSavedInstanceState) {
        // Initialize the parent definition.
        super.onCreate(pSavedInstanceState);
        // Set the Content View.
        this.setContentView(R.layout.activity_main);
        // Fetch the WebView.
        this.mWebView     = (WebView)this.findViewById(R.id.webView);
        this.mCallbackMap = new HashMap<>();
        // Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
        this.getWebView().setWebViewClient(new WebViewClient() {
            /** Handle when a request has been launched. */
            @Override public final void onPageFinished(final WebView pWebView, final String pUrl) {
                // Determine whether we're allowed to process the Runnable; if the page hadn't been redirected, or if we've finished redirection.
                if(pUrl.equals(pWebView.getOriginalUrl())) {
                    // Fetch the Runnable for the OriginalUrl.
                    final Runnable lRunnable = getCallbackMap().get(pWebView.getOriginalUrl());
                    // Is it valid?
                    if(lRunnable != null) { lRunnable.run(); }
                }
                // Handle as usual.
                super.onPageFinished(pWebView, pUrl);
            }
            /** Ensure we handle SSL state properly. */
            @Override public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); }
        });
        // Assert that we wish to visit Zonal's website.
        this.getWebView().loadUrl("http://www.zonal.co.uk/");
        // Align a Callback for Zonal; this will be serviced once the page has loaded.
        this.getCallbackMap().put("http://www.zonal.co.uk/", new Runnable() {     @Override public void run() { /* Do something. */ } });
    }

    /* Getters. */
    public final WebView getWebView() {
        return this.mWebView;
    }

    private final Map<String, Runnable> getCallbackMap() {
        return this.mCallbackMap;
    }

}
</code>```

Body:
Here's a method which allows you to register a Runnable to be executed once a particular web address has finished loading. We associate each Runnable with a corresponding URL String in a Map, and we use the WebView's getOriginalUrl() method to choose the appropriate callback.

package io.github.cawfree.webviewcallback;

/**
 *  Created by Alex Thomas (@Cawfree), 30/03/2017.
 **/

import android.net.http.SslError;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;
import java.util.Map;

/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {

    /* Member Variables. */
    private WebView               mWebView;
    private Map<String, Runnable> mCallbackMap;

    /** Create the Activity. */
    @Override protected final void onCreate(final Bundle pSavedInstanceState) {
        // Initialize the parent definition.
        super.onCreate(pSavedInstanceState);
        // Set the Content View.
        this.setContentView(R.layout.activity_main);
        // Fetch the WebView.
        this.mWebView     = (WebView)this.findViewById(R.id.webView);
        this.mCallbackMap = new HashMap<>();
        // Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
        this.getWebView().setWebViewClient(new WebViewClient() {
            /** Handle when a request has been launched. */
            @Override public final void onPageFinished(final WebView pWebView, final String pUrl) {
                // Determine whether we're allowed to process the Runnable; if the page hadn't been redirected, or if we've finished redirection.
                if(pUrl.equals(pWebView.getOriginalUrl())) {
                    // Fetch the Runnable for the OriginalUrl.
                    final Runnable lRunnable = getCallbackMap().get(pWebView.getOriginalUrl());
                    // Is it valid?
                    if(lRunnable != null) { lRunnable.run(); }
                }
                // Handle as usual.
                super.onPageFinished(pWebView, pUrl);
            }
            /** Ensure we handle SSL state properly. */
            @Override public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); }
        });
        // Assert that we wish to visit Zonal's website.
        this.getWebView().loadUrl("http://www.zonal.co.uk/");
        // Align a Callback for Zonal; this will be serviced once the page has loaded.
        this.getCallbackMap().put("http://www.zonal.co.uk/", new Runnable() {     @Override public void run() { /* Do something. */ } });
    }

    /* Getters. */
    public final WebView getWebView() {
        return this.mWebView;
    }

    private final Map<String, Runnable> getCallbackMap() {
        return this.mCallbackMap;
    }

}


问:
doctrine 2.0 : use SQL timestamp
I'm looking for a way to make doctrine using TIMESTAMP instead of DATETIME for MySql.

Additionaly I need to set ON UPDATE CURRENT_TIMESTAMP and CURRENT_TIMESTAMP as default values.

I would like to have the possibility to have all this code in PHP annotations to have everything in one central place.

How can I do that?

答: @ORM\Version works only for one property per entity so it is not an option if you need to have more than one timestamp field in a table.</p>

Title: doctrine 2.0 : use SQL timestamp


问:
How to call a method of the base class from the inherited class in VBA?
I have initial class(class module) CSVUtiltiy with the following function:

```<code>Public Sub fillData(ByRef d As Dictionary, ByRef TmpAr() As String)
End Sub
</code>```

and I have inherited class(class module) CSVUtilityInherited, with overwritten function:

```<code>Implements csvUtility
Private Sub csvUtility_fillData(d As Scripting.IDictionary, TmpAr() As String)
End Sub
</code>```

How can I call from csvUtility_fillData function of the base class fillData?

答:
=(

I think there is no way to call base sub.

VBA only implements interfaces. So, you must write realisation of all public functions, subs and properties.

When you implement "class", vba just implements its "hidden" interface (interface of this class). not more =(

Vba use QueryInterface calls to read declaration of all base-class members

So, you need to make your own realization of all base "class" members

=(((

Body:
I have initial class(class module) CSVUtiltiy with the following function:

Public Sub fillData(ByRef d As Dictionary, ByRef TmpAr() As String)
End Sub

and I have inherited class(class module) CSVUtilityInherited, with overwritten function:

Implements csvUtility
Private Sub csvUtility_fillData(d As Scripting.IDictionary, TmpAr() As String)
End Sub

How can I call from csvUtility_fillData function of the base class fillData?


问:
Synchronize Method, can I use it to not main thread?
I rarely use threads and I have question about this class:

```<code>unit ExpectingThread;

interface

uses
    System.Classes;

type
    TExpectingThread = class(TThread)
    private
        _timeoutMs: Integer;
        _buff: string;
        _patterns: TArray<string>;
        _result: Integer;
        function Timeouted(startTime: Cardinal): Boolean;
        function ExpectedDetected: Boolean;

    protected
        procedure Execute; override;
    public
        constructor Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
        //this method is called from other NOT MAIN thread
        procedure BuffUpdate(text: string);
    end;

implementation

uses
    Winapi.Windows,
    System.RegularExpressions;

{ TExpectingThread }

constructor TExpectingThread.Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
begin
    _patterns := patterns;
    _timeoutMs := timeoutMs;
    _buff := buff;
end;

//this method is called from other NOT MAIN thread
procedure TExpectingThread.BuffUpdate(text: string);
begin
    // lock
    TThread.Synchronize(Self, procedure
        begin
            _buff := _buff + text;
        end);
    // unlock
end;

procedure TExpectingThread.Execute;
var
    startTime: Cardinal;
begin
    inherited;

    startTime := GetTickCount;
    while true do
    begin
        if Timeouted(startTime) then
        begin
            Self.ReturnValue := 0; // timeouted
            Exit;
        end;

        if ExpectedDetected then
        begin
            Self.ReturnValue := 1; // found
            Exit;
        end;
    end;
end;

function TExpectingThread.ExpectedDetected: Boolean;
var
    regex: TRegEx;
    i: Integer;
begin
    // lock
    result := 0;
    for i := 0 to High(_patterns) do
    begin
        regex.Create(_patterns[i]);
        if regex.IsMatch(_buff) then
        begin
            _result := i;
            Exit(true);
        end;
    end;
    // unlock
end;

function TExpectingThread.Timeouted(startTime: Cardinal): Boolean;
var
    currentTime: Cardinal;
begin
    currentTime := GetTickCount;
    result := currentTime - startTime > _timeoutMs;
end;

end.
</code>```

Thread has to cheacking if any pattern is match to buffer over timeout. But other thread(NOT MAIN) can change buffer by using BuffUpdate method. Did I use Synchronization method correctly?

答:
Synchronize() is specifically designed to work with the main UI thread.  You can use it for inter-thread syncing, however ALL threads involved would have to use it. In your example, only the thread(s) that write to _buff are using it, but the thread that reads from _buff is not.  So that is a hole in your logic.

That being said, if the main UI thread does not need to touch your data, then Synchronize() is not the best solution to use. You can just wrap the data access with a synchronization object instead, like a TCriticalSection, TMutex, TEvent, TMREWSync, Sytem.TMonitor, etc.  For example:

```<code>unit ExpectingThread;

interface

uses
  System.Classes, System.SyncObjs;

type
  TExpectingThread = class(TThread)
    private
      _timeoutMs: Integer;
      _buff: string;
      _buffLock: TCriticalSection;
      _buffChanged: Boolean;
      _patterns: TArray<string>;
      _result: Integer;
      function Timeouted(startTime: Cardinal): Boolean;
      function ExpectedDetected: Boolean;
    protected
      procedure Execute; override;
    public
      constructor Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
      destructor Destroy; override;
      //this method is called from other NOT MAIN thread
      procedure BuffUpdate(text: string);
    end;

implementation

uses
  Winapi.Windows, System.RegularExpressions;

{ TExpectingThread }

constructor TExpectingThread.Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
begin
  inherited Create(False);
  _buffLock := TCriticalSection.Create;
  _patterns := patterns;
  _timeoutMs := timeoutMs;
  _buff := buff;
  _buffChanged := True;
end;

destructor TExpectingThread.Destroy;
begin
  _buffLock.Free;
  inherited;
end;

//this method is called from other NOT MAIN thread
procedure TExpectingThread.BuffUpdate(text: string);
begin
  _buffLock.Enter;
  try
    _buff := _buff + text;
    _buffChanged := True;
  finally
    _buffLock.Leave;
  end;
end;

procedure TExpectingThread.Execute;
var
  startTime: DWORD;
begin
  startTime := GetTickCount;
  while not Terminated do
  begin
    if Timeouted(startTime) then
    begin
      Self.ReturnValue := 0; // timeouted
      Exit;
    end;
    if ExpectedDetected then
    begin
      Self.ReturnValue := 1; // found
      Exit;
    end;
  end;
end;

function TExpectingThread.ExpectedDetected: Boolean;
var
  i: Integer;
  buff: string;
begin
  Result := False;
  _buffLock.Enter;
  try
    If not _buffChanged then Exit;
    buff := _buff;
    UniqueStr(buff);
    _buffChanged := False;
  finally
    _buffLock.Leave;
  end;
  for i := Low(_patterns) to High(_patterns) do
  begin
    if TRegEx.IsMatch(buff, _patterns[i]) then
    begin
      _result := i;
      Exit(True);
    end;
  end;
end;

function TExpectingThread.Timeouted(startTime: Cardinal): Boolean;
var
  currentTime: DWORD;
begin
  currentTime := GetTickCount;
  result := currentTime - startTime > _timeoutMs;
end;

end.
</code>```

Body:
I rarely use threads and I have question about this class:

unit ExpectingThread;

interface

uses
    System.Classes;

type
    TExpectingThread = class(TThread)
    private
        _timeoutMs: Integer;
        _buff: string;
        _patterns: TArray<string>;
        _result: Integer;
        function Timeouted(startTime: Cardinal): Boolean;
        function ExpectedDetected: Boolean;

    protected
        procedure Execute; override;
    public
        constructor Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
        //this method is called from other NOT MAIN thread
        procedure BuffUpdate(text: string);
    end;

implementation

uses
    Winapi.Windows,
    System.RegularExpressions;

{ TExpectingThread }

constructor TExpectingThread.Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
begin
    _patterns := patterns;
    _timeoutMs := timeoutMs;
    _buff := buff;
end;

//this method is called from other NOT MAIN thread
procedure TExpectingThread.BuffUpdate(text: string);
begin
    // lock
    TThread.Synchronize(Self, procedure
        begin
            _buff := _buff + text;
        end);
    // unlock
end;

procedure TExpectingThread.Execute;
var
    startTime: Cardinal;
begin
    inherited;

    startTime := GetTickCount;
    while true do
    begin
        if Timeouted(startTime) then
        begin
            Self.ReturnValue := 0; // timeouted
            Exit;
        end;

        if ExpectedDetected then
        begin
            Self.ReturnValue := 1; // found
            Exit;
        end;
    end;
end;

function TExpectingThread.ExpectedDetected: Boolean;
var
    regex: TRegEx;
    i: Integer;
begin
    // lock
    result := 0;
    for i := 0 to High(_patterns) do
    begin
        regex.Create(_patterns[i]);
        if regex.IsMatch(_buff) then
        begin
            _result := i;
            Exit(true);
        end;
    end;
    // unlock
end;

function TExpectingThread.Timeouted(startTime: Cardinal): Boolean;
var
    currentTime: Cardinal;
begin
    currentTime := GetTickCount;
    result := currentTime - startTime > _timeoutMs;
end;

end.

Thread has to cheacking if any pattern is match to buffer over timeout. But other thread(NOT MAIN) can change buffer by using BuffUpdate method. Did I use Synchronization method correctly?

Body:
Synchronize() is specifically designed to work with the main UI thread.  You can use it for inter-thread syncing, however ALL threads involved would have to use it. In your example, only the thread(s) that write to _buff are using it, but the thread that reads from _buff is not.  So that is a hole in your logic.

That being said, if the main UI thread does not need to touch your data, then Synchronize() is not the best solution to use. You can just wrap the data access with a synchronization object instead, like a TCriticalSection, TMutex, TEvent, TMREWSync, Sytem.TMonitor, etc.  For example:

unit ExpectingThread;

interface

uses
  System.Classes, System.SyncObjs;

type
  TExpectingThread = class(TThread)
    private
      _timeoutMs: Integer;
      _buff: string;
      _buffLock: TCriticalSection;
      _buffChanged: Boolean;
      _patterns: TArray<string>;
      _result: Integer;
      function Timeouted(startTime: Cardinal): Boolean;
      function ExpectedDetected: Boolean;
    protected
      procedure Execute; override;
    public
      constructor Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
      destructor Destroy; override;
      //this method is called from other NOT MAIN thread
      procedure BuffUpdate(text: string);
    end;

implementation

uses
  Winapi.Windows, System.RegularExpressions;

{ TExpectingThread }

constructor TExpectingThread.Create(patterns: TArray<string>; buff: string; timeoutMs: Integer);
begin
  inherited Create(False);
  _buffLock := TCriticalSection.Create;
  _patterns := patterns;
  _timeoutMs := timeoutMs;
  _buff := buff;
  _buffChanged := True;
end;

destructor TExpectingThread.Destroy;
begin
  _buffLock.Free;
  inherited;
end;

//this method is called from other NOT MAIN thread
procedure TExpectingThread.BuffUpdate(text: string);
begin
  _buffLock.Enter;
  try
    _buff := _buff + text;
    _buffChanged := True;
  finally
    _buffLock.Leave;
  end;
end;

procedure TExpectingThread.Execute;
var
  startTime: DWORD;
begin
  startTime := GetTickCount;
  while not Terminated do
  begin
    if Timeouted(startTime) then
    begin
      Self.ReturnValue := 0; // timeouted
      Exit;
    end;
    if ExpectedDetected then
    begin
      Self.ReturnValue := 1; // found
      Exit;
    end;
  end;
end;

function TExpectingThread.ExpectedDetected: Boolean;
var
  i: Integer;
  buff: string;
begin
  Result := False;
  _buffLock.Enter;
  try
    If not _buffChanged then Exit;
    buff := _buff;
    UniqueStr(buff);
    _buffChanged := False;
  finally
    _buffLock.Leave;
  end;
  for i := Low(_patterns) to High(_patterns) do
  begin
    if TRegEx.IsMatch(buff, _patterns[i]) then
    begin
      _result := i;
      Exit(True);
    end;
  end;
end;

function TExpectingThread.Timeouted(startTime: Cardinal): Boolean;
var
  currentTime: DWORD;
begin
  currentTime := GetTickCount;
  result := currentTime - startTime > _timeoutMs;
end;

end.


问:
Please explain me the below query
I have Mysql query to be used in a php script. I just need to know how is it processing and producing output..</p>

```<code>$sql = "SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto "
      ."FROM events "
      ."WHERE events_active = 1 AND events_start = 1 AND "
      ." (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday ";
</code>```

答:
Select the event id, event name, control id and the number of days to the event (substract from the event date the acctual date converted to number of days)

```<code>SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto
</code>```

From the table events

```<code>FROM events
</code>```

When the event is active (events_active =1), event start is one (i don't know the semantics of the fields.. sorry) and the number of days left to the event are included in the list of valid number of days ($noticeeventsday sould be a list like (1,2,3) so if the event is in the next one, two or three days it will be returned by the query.)

```<code>WHERE events_active = 1 AND events_start = 1 AND (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday
</code>```

HTH!

Title: Please explain me the below query

Body:
I have Mysql query to be used in a php script. I just need to know how is it processing and producing output..

$sql = "SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto "
      ."FROM events "
      ."WHERE events_active = 1 AND events_start = 1 AND "
      ." (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday ";

Body:
Select the event id, event name, control id and the number of days to the event (substract from the event date the acctual date converted to number of days)

SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto

From the table events

FROM events

When the event is active (events_active =1), event start is one (i don't know the semantics of the fields.. sorry) and the number of days left to the event are included in the list of valid number of days ($noticeeventsday sould be a list like (1,2,3) so if the event is in the next one, two or three days it will be returned by the query.)

WHERE events_active = 1 AND events_start = 1 AND (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday

HTH!


问:
Magento sql query have no index
I'm having a problem with SQL queries.

Currently I have two magento versions on different servers, both are upgraded from 1.9.2.4 to 1.9.3.2.

The problem, when I check queries with SHOW FULL PROCESSLIST I see that they are taking a lot of time. After some researches I have tried to run same query on both servers (directly via SQL command).

Results are 1:15 (68 x 263 rows vs 68 x 961902) in speed, also one of colleagues checked EXPLAIN SQL function and saw that in the slower query server there are no key (index). Tried to run adding USE INDEX () and using key from faster query server and seems that is the problem because query went with same results and speed.

In conclusion we thing that some of MYSQL configuration are not correct.

Maybe someone could suggest which MYSQL configuration or server variables can cause this problem?
Because currently I'm out of ideas. I have tried googling but no results could help me.

SQL query.

```<code>SELECT  `main_table`.`entity_id`, main_table.`name`, main_table.`path`,
        `main_table`.`is_active`, `main_table`.`is_anchor`,
        `url_rewrite`.`request_path`
    FROM  `catalog_category_flat_store_1` AS `main_table`
    LEFT JOIN  `core_url_rewrite` AS `url_rewrite`
       ON  url_rewrite.category_id=main_table.entity_id
      AND  url_rewrite.is_system=1
      AND  url_rewrite.store_id = 1
      AND  url_rewrite.id_path LIKE 'category/%'
    WHERE  (main_table.include_in_menu = '1')
      AND  (main_table.is_active = '1')
      AND  (main_table.path like '1/2/3/%')
      AND  (`level` <= 3)
    ORDER BY  `main_table`.`position` ASC
</code>```

答:
Probably the best indexes would be these 'composite' indexes:

```<code>main_table:  INDEX(include_in_menu, is_active, path)
url_rewrite: INDEX(is_system, store_id, category_id, id_path)
</code>```

Is there some reason for using LEFT?

If you still have issues after adding those indexes, please provide SHOW CREATE TABLE and EXPLAIN SELECT ....

Title: Magento sql query have no index

Body:
I'm having a problem with SQL queries.

Currently I have two magento versions on different servers, both are upgraded from 1.9.2.4 to 1.9.3.2.

The problem, when I check queries with SHOW FULL PROCESSLIST I see that they are taking a lot of time. After some researches I have tried to run same query on both servers (directly via SQL command).

Results are 1:15 (68 x 263 rows vs 68 x 961902) in speed, also one of colleagues checked EXPLAIN SQL function and saw that in the slower query server there are no key (index). Tried to run adding USE INDEX () and using key from faster query server and seems that is the problem because query went with same results and speed.

In conclusion we thing that some of MYSQL configuration are not correct.

Maybe someone could suggest which MYSQL configuration or server variables can cause this problem?
Because currently I'm out of ideas. I have tried googling but no results could help me.

SQL query.

SELECT  `main_table`.`entity_id`, main_table.`name`, main_table.`path`,
        `main_table`.`is_active`, `main_table`.`is_anchor`,
        `url_rewrite`.`request_path`
    FROM  `catalog_category_flat_store_1` AS `main_table`
    LEFT JOIN  `core_url_rewrite` AS `url_rewrite`
       ON  url_rewrite.category_id=main_table.entity_id
      AND  url_rewrite.is_system=1
      AND  url_rewrite.store_id = 1
      AND  url_rewrite.id_path LIKE 'category/%'
    WHERE  (main_table.include_in_menu = '1')
      AND  (main_table.is_active = '1')
      AND  (main_table.path like '1/2/3/%')
      AND  (`level` <= 3)
    ORDER BY  `main_table`.`position` ASC

Body:
Probably the best indexes would be these 'composite' indexes:

main_table:  INDEX(include_in_menu, is_active, path)
url_rewrite: INDEX(is_system, store_id, category_id, id_path)

Is there some reason for using LEFT?

If you still have issues after adding those indexes, please provide SHOW CREATE TABLE and EXPLAIN SELECT ....


问:
Partition groups of data by group
I have the following dataset:

```<code>df<- as.data.frame(c(rep("a", times = 9), rep("b", times = 18), rep("c", times = 27)))
colnames(df)<-"Location"
Year<-c(rep(1:3,times = 3), rep(1:6, times = 3), rep(1:9, times = 3))
df$Year<-Year

df<- df %>%
      mutate(Predictor = seq_along(Location)) %>%
      ungroup(df)

print(df)

Location Year Predictor
        a    1         1
        a    2         2
        a    3         3
        a    1         4
        a    2         5
        a    3         6
        a    1         7
        a    2         8
        a    3         9
        b    1        10
        b    2        11
        b    3        12
        b    4        13
        b    5        14
... 40 more rows
</code>```

I want to split the above dataframe into training and test sets. For the test set, I want to randomly sample a third of the number of years in each Location, while keeping the years together. So if year "1" is selected for location "a", I want all three "1's" in the test set and so on. My test set should look something like this:

```<code> Location Year Predictor
        a    1         1
        a    1         4
        a    1         7
        b    3        12
        b    3        18
        b    3        24
        b    5        14
        b    5        20
        b    5        26
        c    3        30
        c    3        39
        c    3        48
        c    6        33
        c    6        42
        c    6        51
        c    7        34
        c    7        43
        c    7        52
</code>```

I found a similar question here, but this procedure would sample the same year and the same number of years from every location (and YEAR is numeric, not a factor). I want a different random sample of years from each location and a proportional number of samples.

Would like to do this in dplyr if possible

答:
You can first create a distinct set of year/location combinations, then sample some of them for each location and use that in a semi_join on the original data. This could be done as:

```<code>df %>%
  distinct(Location, Year) %>%
  group_by(Location) %>%
  sample_frac(.3) %>%
  semi_join(df, .)

#    Location Year Predictor
# 1         a    3         3
# 2         a    3         6
# 3         a    3         9
# 4         b    4        13
# 5         b    4        19
# 6         b    4        25
# 7         b    5        14
# 8         b    5        20
# 9         b    5        26
# 10        c    8        35
# 11        c    8        44
# 12        c    8        53
# 13        c    1        28
# 14        c    1        37
# 15        c    1        46
# 16        c    2        29
# 17        c    2        38
# 18        c    2        47
</code>```

Title: Partition groups of data by group

Body:
I have the following dataset:

df<- as.data.frame(c(rep("a", times = 9), rep("b", times = 18), rep("c", times = 27)))
colnames(df)<-"Location"
Year<-c(rep(1:3,times = 3), rep(1:6, times = 3), rep(1:9, times = 3))
df$Year<-Year

df<- df %>%
      mutate(Predictor = seq_along(Location)) %>%
      ungroup(df)

print(df)

Location Year Predictor
        a    1         1
        a    2         2
        a    3         3
        a    1         4
        a    2         5
        a    3         6
        a    1         7
        a    2         8
        a    3         9
        b    1        10
        b    2        11
        b    3        12
        b    4        13
        b    5        14
... 40 more rows

I want to split the above dataframe into training and test sets. For the test set, I want to randomly sample a third of the number of years in each Location, while keeping the years together. So if year "1" is selected for location "a", I want all three "1's" in the test set and so on. My test set should look something like this:

 Location Year Predictor
        a    1         1
        a    1         4
        a    1         7
        b    3        12
        b    3        18
        b    3        24
        b    5        14
        b    5        20
        b    5        26
        c    3        30
        c    3        39
        c    3        48
        c    6        33
        c    6        42
        c    6        51
        c    7        34
        c    7        43
        c    7        52

I found a similar question here, but this procedure would sample the same year and the same number of years from every location (and YEAR is numeric, not a factor). I want a different random sample of years from each location and a proportional number of samples.

Would like to do this in dplyr if possible

Body:
You can first create a distinct set of year/location combinations, then sample some of them for each location and use that in a semi_join on the original data. This could be done as:

df %>%
  distinct(Location, Year) %>%
  group_by(Location) %>%
  sample_frac(.3) %>%
  semi_join(df, .)

#    Location Year Predictor
# 1         a    3         3
# 2         a    3         6
# 3         a    3         9
# 4         b    4        13
# 5         b    4        19
# 6         b    4        25
# 7         b    5        14
# 8         b    5        20
# 9         b    5        26
# 10        c    8        35
# 11        c    8        44
# 12        c    8        53
# 13        c    1        28
# 14        c    1        37
# 15        c    1        46
# 16        c    2        29
# 17        c    2        38
# 18        c    2        47


问:
App Engine Process randomly terminated because of "too much memory"
For the past year, I've been using google app engine to make PDF's and then output them onto the page. They have always been working flawlessly until today.

Now, I get the following error - not all the time, but probably around 40% of my requests come back with a 500 error about it being terminated.

Does anyone know why this would be happening and how to avoid it?

While handling this request, the process that handled this request was found to be using too much memory and was terminated. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may have a memory leak in your application.

This is my script. Sometimes I add images to it using $pdf->MemImage();
or I add text with $pdf->Cell() but that is about the only difference.

```<code><?php
    define('FPDF_FONTPATH','lib/fpdi/fonts');
    require_once('lib/fpdf.php');
    require_once('lib/fpdi/fpdi.php');

    $pdfPath = file_get_contents("gs://bucket/template.pdf");
    $temp_id = "12345";
    $max_pages = 5;

    //put the pdf image into a temp directory in google drive
    $object_url = "gs://bucket2/template.pdf";
    file_put_contents($object_url, $pdfPath);

    //Start the FPDI
    $pdf = new FPDI('P', 'pt');
    $pdf->SetAutoPageBreak(false);

    //Set the source PDF file
    $source_file = $pdf->setSourceFile("gs://bucket2/template.pdf");

    for($page_count = 1; $page_count <= $max_pages; $page_count++)
    {
        //Import the first page of the file
        $tppl = $pdf->importPage($page_count);
        $pdf->AddPage();

        //get size of pdf page
        $size = $pdf->getTemplateSize($tppl);

        $pdf->useTemplate($tppl, null, null, $size['w'], $size['h'], true);
    }

    header('Content-Type: application/pdf');
    $pdf->Output("template.pdf", "I");
    unlink("gs://bucket2/template.pdf");
?>
</code>```

答:
I solved this by updating the instance class and basic scaling in app.yaml. This is just experimentation and might need to be different based on use case but it did solve the problem for me. Thanks to everyone who helped in the above comments.

```<code>application: <APPLICATION NAME>
version: 1
runtime: php55
api_version: 1
instance_class: B2
basic_scaling:
  max_instances: 5
</code>```

Body:
For the past year, I've been using google app engine to make PDF's and then output them onto the page. They have always been working flawlessly until today.

Now, I get the following error - not all the time, but probably around 40% of my requests come back with a 500 error about it being terminated.

Does anyone know why this would be happening and how to avoid it?

While handling this request, the process that handled this request was found to be using too much memory and was terminated. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may have a memory leak in your application.

This is my script. Sometimes I add images to it using $pdf->MemImage();
or I add text with $pdf->Cell() but that is about the only difference.

<?php
    define('FPDF_FONTPATH','lib/fpdi/fonts');
    require_once('lib/fpdf.php');
    require_once('lib/fpdi/fpdi.php');

    $pdfPath = file_get_contents("gs://bucket/template.pdf");
    $temp_id = "12345";
    $max_pages = 5;

    //put the pdf image into a temp directory in google drive
    $object_url = "gs://bucket2/template.pdf";
    file_put_contents($object_url, $pdfPath);

    //Start the FPDI
    $pdf = new FPDI('P', 'pt');
    $pdf->SetAutoPageBreak(false);

    //Set the source PDF file
    $source_file = $pdf->setSourceFile("gs://bucket2/template.pdf");

    for($page_count = 1; $page_count <= $max_pages; $page_count++)
    {
        //Import the first page of the file
        $tppl = $pdf->importPage($page_count);
        $pdf->AddPage();

        //get size of pdf page
        $size = $pdf->getTemplateSize($tppl);

        $pdf->useTemplate($tppl, null, null, $size['w'], $size['h'], true);
    }

    header('Content-Type: application/pdf');
    $pdf->Output("template.pdf", "I");
    unlink("gs://bucket2/template.pdf");
?>

Body:
I solved this by updating the instance class and basic scaling in app.yaml. This is just experimentation and might need to be different based on use case but it did solve the problem for me. Thanks to everyone who helped in the above comments.

application: <APPLICATION NAME>
version: 1
runtime: php55
api_version: 1
instance_class: B2
basic_scaling:
  max_instances: 5


问:
Max date of DateVector in Rcpp
How to save  the maximum date within a DateVector as a variable in Rcpp?

The toy example below returns the error message:

no viable conversion from '__gnu_cxx::__normal_iterator<Rcpp::Date
  *, std::vector<Rcpp::Date, std::allocator<Rcpp::Date> > >' to 'NumericVector' (aka 'Vector<14>')

```<code>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Date date_toy_example(DataFrame d){

  // Get date vector from data frame
  DateVector  dte = d["date"];

  // Get max date
  Date max_dte = std::max_element(dte.begin(), dte.end());

  // Return maximum date
  return max_dte;
}

// R code

/*** R
df <- data.frame(id=1:10, date=seq(as.Date("2015-01-01"),as.Date("2015-01-10"), by="day"))
date_toy_example(df)
*/
</code>```

答:
std::max_element returns an iterator; you need to dereference it to get the underlying value:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
    DateVector  dte = d["date"];
    Date max_dte = *std::max_element(dte.begin(), dte.end());
    //            ^^^

    return max_dte;
}

/*** R

df <- data.frame(
    id=1:10,
    date = seq(as.Date("2015-01-01"),
        as.Date("2015-01-10"),
        by="day")
)
MaxDate(df)
# [1] "2015-01-10"

max(df$date)
# [1] "2015-01-10"

*/
```

<hr>

<p>Alternatively, treat your input as an ordinary <code>NumericVector</code> and use <code>Rcpp::max</code>: </p>

<pre class="lang-cpp prettyprint-override"><code>// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
    NumericVector dte = d["date"];
    return Date(Rcpp::max(dte));
}
</code>```

Title: Max date of DateVector in Rcpp

Body:
How to save  the maximum date within a DateVector as a variable in Rcpp?

The toy example below returns the error message:

no viable conversion from '__gnu_cxx::__normal_iterator<Rcpp::Date
  *, std::vector<Rcpp::Date, std::allocator<Rcpp::Date> > >' to 'NumericVector' (aka 'Vector<14>')

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Date date_toy_example(DataFrame d){

  // Get date vector from data frame
  DateVector  dte = d["date"];

  // Get max date
  Date max_dte = std::max_element(dte.begin(), dte.end());

  // Return maximum date
  return max_dte;
}

// R code

/*** R
df <- data.frame(id=1:10, date=seq(as.Date("2015-01-01"),as.Date("2015-01-10"), by="day"))
date_toy_example(df)
*/

Body:
std::max_element returns an iterator; you need to dereference it to get the underlying value:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
    DateVector  dte = d["date"];
    Date max_dte = *std::max_element(dte.begin(), dte.end());
    //            ^^^

    return max_dte;
}

/*** R

df <- data.frame(
    id=1:10,
    date = seq(as.Date("2015-01-01"),
        as.Date("2015-01-10"),
        by="day")
)
MaxDate(df)
# [1] "2015-01-10"

max(df$date)
# [1] "2015-01-10"

*/

Alternatively, treat your input as an ordinary NumericVector and use Rcpp::max:

// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
    NumericVector dte = d["date"];
    return Date(Rcpp::max(dte));
}


问:
In chrome my pictures height changes
I have created one big picture that contains 4 smaller pictures.

My 4 pictures all have an height of 425.5px. In Firefox it looks great, however in Chrome there becomes an gap between the 4 pictures so you can see some of the big picture behind them.

It looks like the height of my 4 pictures becomes a little smaller in google chrome, without the bigger picture does.

答:
```<code>img {
   display: block;
}
</code>```

And please please please don't use 425.5px (half a pixel)...

Title: In chrome my pictures height changes

Body:
img {
   display: block;
}

And please please please don't use 425.5px (half a pixel)...


问:
adding Datatables sorting to PHP page
I have tried to add datatables to my PHP web apps table. I have followed the instructions and add a thead and tbody tag, also the link at the top and the document.ready in the script tags at the bottom. Nothing seems to be working. any ideas?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link rel="stylesheet" type="text/css" href="css/style.css">

<title>View Records</title>

GCS Reproduction Environment

All Reproductions

<?php

/*

VIEW.PHP

Displays all data from 'players' table

*/

// connect to the database

include('php/connect-db.php');

// ordering the ID function

$ascdesc = "";
$order = isset($_GET['sort'])?$_GET['sort']:'id';

$ascdesc = isset($_GET['ascdesc'])?$_GET['ascdesc']:'DESC';
switch(strtoupper($ascdesc))
  {
  case 'DESC': $ascdesc = 'ASC'; break;
  case 'ASC': $ascdesc = 'DESC'; break;
  default: $ascdesc = 'DESC'; break;
  }

// get results from database

$result = mysql_query("SELECT * FROM players ORDER BY $order $ascdesc")

or die(mysql_error());

// display data in table

echo "
";
echo "

 ID	 Administration Console	 Product Version	 Platform	 Database	 Owner	 Status

";

// loop through results of database query, displaying them in the table

while($row = mysql_fetch_array( $result )) {

// echo out the contents of each row into a table
echo "
";

echo "
";

echo '' . $row['id'] . '	';

echo ''.$row['curl'].'	';

echo '' . $row['pversion'] . '	';

echo '' . $row['platform'] . '	';

echo '' . $row['dversion'] . '	';

echo '' . $row['email'].'	';

echo '' . $row['status'] .'	';

echo 'Edit	';

echo 'Delete	';

echo "
";

echo "
";

}

// close table>

echo "
";

?>

Add a new record

```

答: Your biggest issue here is you're not calling your database in your query. It should be mysqli_query($db, "SELECT * FROM players ORDER BY $order $ascdesc") where $db is your mysqli_connect variable called in your connect-db.php file. Also your mysqli_error() should be mysqli_error($db) or whatever you called your mysqli_connect. On doing that, the mysqli_error will give you a better idea of where you're failing. You can also check your php log file to catch errors there.</p>

Title: adding Datatables sorting to PHP page


问:
Replacing certain characters while allowing unicode (PHP)
So I got a search box in a site we're developing that will search in a database with both English and Greek product strings. I'm trying to clear the text input from all kinds of special characters like: / . , ' ] [ % & _ etc. and replace them with a space or totally delete them. Even double instances of them should be deleted, like ^^, &&, [[ etc.

I have been messing around with preg_replace but can't find a solution...

Thanks in advance.

答:
With preg_replace you can do what you are looking for. In the next example all non a-z nor A-Z, nor / _ | + - characters are replaced by '' (nothing, empty string)

```<code>preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str);
</code>```

add the characters you want to allow in that list and you will have your function.

Other way would be with str_replace() but here you have to insert one by one all the elements that you want to remove in different function calls.

I hope it helps

Body:
With preg_replace you can do what you are looking for. In the next example all non a-z nor A-Z, nor / _ | + - characters are replaced by '' (nothing, empty string)

preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str);

add the characters you want to allow in that list and you will have your function.

Other way would be with str_replace() but here you have to insert one by one all the elements that you want to remove in different function calls.

I hope it helps


问:
Compare a NSNumber to an int
I've a simple question (I think):
I'm trying to compare a NSNumber with a int, to see if it is 0 or 1. Here is the code:

```<code>id i = [dictionary objectForKey:@"error"]; //class = NSCFNumber

NSLog(@"%@ == 0 -> %@", i, i == 0);
NSLog(@"%@ == 0 -> %@", i, [i compare:[NSNumber numberWithBool:NO]]);
</code>```

I tried this to methods but I get null as result:

```<code>2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
</code>```

Can you help me?

答:
This worked</p>

```<code>if (thevariable.intValue==0) {
  ...
}
</code>```

Title: Compare a NSNumber to an int

Body:
I've a simple question (I think):
I'm trying to compare a NSNumber with a int, to see if it is 0 or 1. Here is the code:

id i = [dictionary objectForKey:@"error"]; //class = NSCFNumber

NSLog(@"%@ == 0 -> %@", i, i == 0);
NSLog(@"%@ == 0 -> %@", i, [i compare:[NSNumber numberWithBool:NO]]);

I tried this to methods but I get null as result:

2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)

Can you help me?

Body:
This worked

if (thevariable.intValue==0) {
  ...
}


问:
CSS div (absolute within relative)
How i can make 2 different divs elements A and B what they are included on a div element C .

A and B to start from the same corner from top left, i try to change A and B to position absolute and working but i need A to keep it via position relative. the code can be found here https://jsfiddle.net/bms1upkn/2/

Html

```<code><div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

<div class="c">
  <div class="a">
  </div>
  <div class="b">
  </div>
</div>

</div>
</code>```

CSS

```<code>.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
}
.a {
  position: relative;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}
</code>```

答:
```<code>.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
  position:relative; //new
}
.a {
  position: relative;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
  left:0px; //new
  top:0px; //new
}
</code>```

Title: CSS div (absolute within relative)

Body:
How i can make 2 different divs elements A and B what they are included on a div element C .

A and B to start from the same corner from top left, i try to change A and B to position absolute and working but i need A to keep it via position relative. the code can be found here https://jsfiddle.net/bms1upkn/2/

Html

CSS

.data {
  width: 100%;
}
.c {
  height: 200px;
  width: 25%;
  float: left;
  margin-left: 10px;
  margin-bottom: 20px;
}
.a {
  position: relative;
  background-color: red;
  height: 200px;
  width: 100%;
}

.b {
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
}


问:
json_encode format for array
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

```<code>array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}
</code>```

The ouput in json_encode() is:

```<code>{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}
</code>```

However I am looking to output as:

```<code>[
 [1441065600,1,1,1.28,1.35]
]
</code>```

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

答:
Try it:</p>

```<code>foreach( $array as $key => &$item )
    $item = array( $key ) + array_values( $item );

echo json_encode( array_values( $array ) );
// OR
echo json_encode( current( array_values( $array ) ) ); // For array with single key
</code>```

Title: json_encode format for array

Body:
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}

The ouput in json_encode() is:

{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}

However I am looking to output as:

[
 [1441065600,1,1,1.28,1.35]
]

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

Body:
Try it:

foreach( $array as $key => &$item )
    $item = array( $key ) + array_values( $item );

echo json_encode( array_values( $array ) );
// OR
echo json_encode( current( array_values( $array ) ) ); // For array with single key