问:
Webpack different names for entries
How i can specify different filename for different entry output?

For example:

```<code>module.exports = {
  context: path.resolve(__dirname, 'assets'),
  entry: {
    vendor: ['react', 'react-dom', 'lodash', 'redux'],
    app: './src/app.js'
  }
  output: {
    path: path.resolve(__dirname, (isDevelopment) ? 'demo' : 'build'),
    filename: (isDevelopment) ? '[name].js' : '[name][chunkhash:12].js'
  }
}
</code>```

To receive output like this

```<code>build
-- index.html
-- app.2394035ufas0ue34.js
-- vendor.js
</code>```

So browser will cache vendor.js with all libraries. Since i don't plan to migrate to any major new release anytime soon and often.
And still being able to break cache for app.js with every update required.

is there some kind of option to set output as

```<code>output: {
  app: {
    ...
  },
  vendor: {
    ...
  },
}
</code>```

答:
Here is working code:

```<code>  entry: {
    './build/app': './src/app.js',
    './build/vendor': VENDOR_LIBS // or path to your vendor.js
  },
  output: {
    path: __dirname,
    filename: '[name].[chunkhash].js'
  },
</code>```

Add this code into your webpack plugins array as last element of an array.

```<code>plugins: [
 ... // place our new plugin here
]

function() {
  this.plugin("done", function(stats) {
    const buildDir = __dirname + '/build/';
    const fs = require('fs');
    var vendorTempFileName = '';

    new Promise(function(resolve, reject) {

      fs.readdir(buildDir, (err, files) => {
        files.forEach(file => {

        if (file.substr(0,6) === 'vendor') {
          resolve(file);
        }

        });
      });
    }).then(function(file) {

      fs.rename( buildDir + file, buildDir + 'vendor.js', function(err) {
        if ( err ) console.log('ERROR: ' + err);
      });

    });

  });
}
</code>```

Output should be as follows:

It is considered bad practice to leave your files without chunkhashes, due to browser caching.

Title: Webpack different names for entries

Body:
How i can specify different filename for different entry output?

For example:

module.exports = {
  context: path.resolve(__dirname, 'assets'),
  entry: {
    vendor: ['react', 'react-dom', 'lodash', 'redux'],
    app: './src/app.js'
  }
  output: {
    path: path.resolve(__dirname, (isDevelopment) ? 'demo' : 'build'),
    filename: (isDevelopment) ? '[name].js' : '[name][chunkhash:12].js'
  }
}

To receive output like this

build
-- index.html
-- app.2394035ufas0ue34.js
-- vendor.js

So browser will cache vendor.js with all libraries. Since i don't plan to migrate to any major new release anytime soon and often.
And still being able to break cache for app.js with every update required.

is there some kind of option to set output as

output: {
  app: {
    ...
  },
  vendor: {
    ...
  },
}

Body:
Here is working code:

  entry: {
    './build/app': './src/app.js',
    './build/vendor': VENDOR_LIBS // or path to your vendor.js
  },
  output: {
    path: __dirname,
    filename: '[name].[chunkhash].js'
  },

Add this code into your webpack plugins array as last element of an array.

plugins: [
 ... // place our new plugin here
]

function() {
  this.plugin("done", function(stats) {
    const buildDir = __dirname + '/build/';
    const fs = require('fs');
    var vendorTempFileName = '';

    new Promise(function(resolve, reject) {

      fs.readdir(buildDir, (err, files) => {
        files.forEach(file => {

        if (file.substr(0,6) === 'vendor') {
          resolve(file);
        }

        });
      });
    }).then(function(file) {

      fs.rename( buildDir + file, buildDir + 'vendor.js', function(err) {
        if ( err ) console.log('ERROR: ' + err);
      });

    });

  });
}

Output should be as follows:

It is considered bad practice to leave your files without chunkhashes, due to browser caching.


来源: stackexchange

问:
std::regex_replace: access index of disjunct match groups
I've been tasked with replacing boost::regex with std::regex and hit an issue with boost::regex references to capture group indexes.

The regex looks like that:

```<code>re = "(^Match1$)|(^Match2$)|(^Match3$)|(^Match4$)"
</code>```

With a replace string:

```<code>replace_str = "(?{1}M1)(?{2}M2)(?{3}M3)(?{4}M4)"
</code>```

If I call boost::regex_replace("Match1", re, replace_str, format_all)
i get "M1" as result and with std::regex_replace("Match1", re, replace_str) the result consists of the whole replace_str.

The standardized variant of regex does not have the format_all option (not sure if that is the issue).
http://en.cppreference.com/w/cpp/regex/match_flag_type

How do I reproduce a similar behaviour with the c++11/14 regex library?
Have I missed an option or syntax that does allow to use that behaviour without boost?

答:
The std::regex library does not support  Boost-Extended Format String Syntax that is supported by Boost regex engine.

If you are looking for an alternative to Boost, you may consider switching to PCRE2 that supports a similar conditional replacement pattern syntax. See PCRE2 Extended Replacement String Syntax article.

ContentLicense: CC BY-SA 3.0

Body:
I've been tasked with replacing boost::regex with std::regex and hit an issue with boost::regex references to capture group indexes.

The regex looks like that:

re = "(^Match1$)|(^Match2$)|(^Match3$)|(^Match4$)"

With a replace string:

replace_str = "(?{1}M1)(?{2}M2)(?{3}M3)(?{4}M4)"

If I call boost::regex_replace("Match1", re, replace_str, format_all)
i get "M1" as result and with std::regex_replace("Match1", re, replace_str) the result consists of the whole replace_str.

The standardized variant of regex does not have the format_all option (not sure if that is the issue).
http://en.cppreference.com/w/cpp/regex/match_flag_type

How do I reproduce a similar behaviour with the c++11/14 regex library?
Have I missed an option or syntax that does allow to use that behaviour without boost?


问:
How to pass parameters to main method using Gradle?
I have to pass two arguments to my main method. My build script is

```<code>// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'maven central' for resolving your dependencies.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    compile 'com.example:example-core:1.7.6'
}

task main(type: JavaExec, dependsOn: classes) {
    description = 'This task will start the main class of the example project'
    group = 'Example'
    main = 'com.example.core.Example'
    classpath = sourceSets.main.runtimeClasspath

}
</code>```

If I try:

```<code>gradlew main doc.json text.txt
</code>```

Then an error occured.

```<code>org.gradle.execution.TaskSelectionException: Task 'doc.json' not found in root project
</code>```

How can I pass arguments to my main method command line easily?

答:
```<code>task run1(type: JavaExec) {
    main = "pkg.mainclass"
    classpath = sourceSets.main.runtimeClasspath
    args = ["$arg1","$arg2",...]
}

//I have named as run1 it can be any task name

While invoking the gradle script:
c:\> gradle run1 -Parg1="test123" -Parg2="sss"
</code>```

Body:
I have to pass two arguments to my main method. My build script is

// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'maven central' for resolving your dependencies.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    compile 'com.example:example-core:1.7.6'
}

task main(type: JavaExec, dependsOn: classes) {
    description = 'This task will start the main class of the example project'
    group = 'Example'
    main = 'com.example.core.Example'
    classpath = sourceSets.main.runtimeClasspath

}

If I try:

gradlew main doc.json text.txt

Then an error occured.

org.gradle.execution.TaskSelectionException: Task 'doc.json' not found in root project

How can I pass arguments to my main method command line easily?


问:
Offering both asynchronous and synchronous API with a target callback queue
I am writing a networking API. Since the underlying call to NSURLSession is always asynchronous, I offer an asynchronous API by default:

```<code>- (void) callBackendServerWithCompletion: (dispatch_block_t) completion;
</code>```

It’s also very convenient to offer a synchronous version of this API, for example to simplify testing the code in Xcode playgrounds. The synchronous call is written in terms of the asynchronous one:

```<code>- (void) callBackendSynchronously
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self callBackendServerWithCompletion:^{
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
</code>```

This works fine.

Now I would like to add an extra convenience feature, a default dispatch queue to call the completion blocks on. This callback queue defaults to the UI queue, so that the consumer of this API doesn’t have to dispatch_async(dispatch_get_main_queue(), ^{…}) all the time:

```<code>// This:
[webservice callBackendServerWithCompletion:^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateUI];
    });
}];

// Would be replaced with this:
[webservice callBackendServerWithCompletion:^{
    // Guaranteed to run on the main queue
    [self updateUI];
}];
</code>```

This was fairly easy to do, but now I have a deadlock when calling the synchronous method on the main queue:

-callBackendSynchronously calls -callBackendServerWithCompletion and waits on the semaphore.

The asynchonous method processes the network request and dispatches the callback on the main queue.

Since the main queue is already waiting for the semaphore, the code deadlocks.

What’s a simple way to offer all three features, ie. both synchronous & asynchronous API methods and a default callback queue?

答:
Add a private, overloaded version of callBackendServerWithCompletion accepting a dispatch queue. In callBackendSynchronouslycall this new overloaded method with a custom background queue.

And, finally, in your originalcallBackendServerWithCompletion method call the overloaded version passing the default queue as parameter.

Body:
I am writing a networking API. Since the underlying call to NSURLSession is always asynchronous, I offer an asynchronous API by default:

- (void) callBackendServerWithCompletion: (dispatch_block_t) completion;

It’s also very convenient to offer a synchronous version of this API, for example to simplify testing the code in Xcode playgrounds. The synchronous call is written in terms of the asynchronous one:

- (void) callBackendSynchronously
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self callBackendServerWithCompletion:^{
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

This works fine.

Now I would like to add an extra convenience feature, a default dispatch queue to call the completion blocks on. This callback queue defaults to the UI queue, so that the consumer of this API doesn’t have to dispatch_async(dispatch_get_main_queue(), ^{…}) all the time:

// This:
[webservice callBackendServerWithCompletion:^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateUI];
    });
}];

// Would be replaced with this:
[webservice callBackendServerWithCompletion:^{
    // Guaranteed to run on the main queue
    [self updateUI];
}];

This was fairly easy to do, but now I have a deadlock when calling the synchronous method on the main queue:

-callBackendSynchronously calls -callBackendServerWithCompletion and waits on the semaphore.

The asynchonous method processes the network request and dispatches the callback on the main queue.

Since the main queue is already waiting for the semaphore, the code deadlocks.

What’s a simple way to offer all three features, ie. both synchronous & asynchronous API methods and a default callback queue?


问:
PHP contact form returning zeros instead of information
I have a problem with a contact form a created on a website:
The form only returns zeros where it should get the information entered by the user !
Before "echo" i tried $body_message and it gave me this :
0
0

0
0
00
Now with echo i only get two zeros. Echo was sugested by a solution on another website where a user had the same problem but it didn't fix mine.
PHP:

```<code>  $field_name = $_POST['cd-name'];
  $field_company = $_POST['cd-company'];
 $field_email = $_POST['cd-email'];
 $field_budget = $_POST['cd-budget'];
 $field_info = $_POST['cd-textarea'];

 $mail_to = 'glxymedias@gmail.com';
 $subject = 'New project '.$field_name;

 echo "Name:  " . $field_name;
 echo "Company: " .$field_company;
 echo "Email:  " . $field_email;
 echo "Budget: " . $field_budget;
 echo "Message:  " . $field_info;

 $headers = 'From: '.$field-email."\r\n";
 $headers .= 'Reply-To: '.$field-email."\r\n";

 $mail_status = mail($mail_to, $subject, $body_message, $headers);

 if ($mail_status) { ?>
 <script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to glxymedias@gmail.com');
    window.location = 'index.html';
</script>
<?php
}
?>
</code>```

HTML:

```<code><form class="cd-form" action="contact.php" method="post">
                <fieldset>
                    <center>

                        <p><label class="cd-label wow fadeInUp" for="cd-name">Name</label></p>
                        <p><input class="user wow bounceIn" type="text" name="cd-name" id="cd-name" required></p>

                        <p><label class="cd-label wow fadeInUp" for="cd-company">Company</label></p>
                        <p><input class="company wow bounceIn" type="text" name="cd-company" id="cd-company"></p>

                        <p><label class="cd-label wow fadeInUp" for="cd-email">Email</label></p>
                        <p><input class="email wow bounceIn" type="email" name="cd-email" id="cd-email" required></p>

                    <div>

                        <p><label class="wow fadeInUp">Budget</label></p>
                        <p class="cd-select ">
                            <select class="budget wow bounceIn">
                                <option value="0"> </option>
                                <option value="1">1000-3000R</option>
                                <option value="2">3000-5000R</option>
                                <option value="3">5000-10000R</option>
                                <option value="3">10000-20000R</option>
                                <option value="3">+20000R</option>
                            </select>
                        </p>

                    </div>

                        <p><label class="cd-label wow fadeInUp" for="cd-textarea">Project Description</label></p>
                        <p><textarea class="message wow bounceIn" name="cd-textarea" id="cd-textarea" required></textarea></p>

                    <div>
                        <p> <center><input class="buttonsend"type="submit" value="Submit"></center></p>
                                </div>

                    </center>
                </fieldset>
            </form>
</code>```

This is the new coe but it still doesn't work. I copied it from your answer. (opened with

```<code>ini_set('display_errors', 1);  error_reporting(E_ALL);
$field_name    = $_POST['cd-name'];
$field_company = $_POST['cd-company'];
$field_email   = $_POST['cd-email'];
$field_budget  = $_POST['cd-budget'];
$field_info    = $_POST['cd-textarea'];

$mail_to = 'glxymedias@gmail.com';
$subject = 'New project ' . $field_name;

$body_message = "Name:  " . $field_name . "\n";
$body_message .= "Company: " . $field_company . "\n";
$body_message .= "Email:  " . $field_email . "\n";
$body_message .= "Budget :" . $field_budget . "\n";
$body_message .= "Message:  " . $field_info . "\n";

$headers = 'From: ' . $field_email . "\r\n";
$headers .= 'Reply-To: ' . $field_email . "\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) {
?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We will contact you shortly.');
window.location = 'index.html';
</script>
<?php
} else {
?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to glxymedias@gmail.com');
window.location = 'index.html';
</script>
<?php
</code>```

答:
As I have said you are using $body_message without defining the variable first and you have couple of other errors.

Which are as follows:

$field_budget = $_POST['cd-budget']; cd-budget is undefined because none of your form fields have name attribute cd-budget  your <select class="budget wow bounceIn"> is missing the name attribute therefore the value of it won't be pickedup by your script.

your select tag should be <select class="budget wow bounceIn" name="cd-budget">

$headers = 'From: '.$field-email."\r\n"; this is wrong, you don't use - on variables you should use _ instead, now this $field-email. reads as $field as a string which is also undefined, should throw a Notice: Use of undefined constant email

error reporting on top of your php script you add

ini_set('display_errors', 1);  error_reporting(E_ALL)

This how your code should look :

your select tag on the html page should be this:

```<code><select class="budget wow bounceIn" name="cd-budget">
    <option value="0"> </option>
    <option value="1">1000-3000R</option>
    <option value="2">3000-5000R</option>
    <option value="3">5000-10000R</option>
    <option value="3">10000-20000R</option>
    <option value="3">+20000R</option>
</select>
</code>```

then contact.php

```<code><?php
    $field_name    = $_POST['cd-name'];
    $field_company = $_POST['cd-company'];
    $field_email   = $_POST['cd-email'];
    $field_budget  = $_POST['cd-budget'];
    $field_info    = $_POST['cd-textarea'];

    $mail_to = 'glxymedias@gmail.com';
    $subject = 'New project ' . $field_name;

    $body_message = "Name:  " . $field_name . "\n";
    $body_message .= "Company: " . $field_company . "\n";
    $body_message .= "Email:  " . $field_email . "\n";
    $body_message .= "Budget :" . $field_budget . "\n";
    $body_message .= "Message:  " . $field_info . "\n";

    $headers = 'From: ' . $field_email . "\r\n";
    $headers .= 'Reply-To: ' . $field_email . "\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) {
?>
 <script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'index.html';
</script>
<?php
} else {
?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to glxymedias@gmail.com');
    window.location = 'index.html';
</script>
<?php
}
?>
</code>```

Body:
I have a problem with a contact form a created on a website:
The form only returns zeros where it should get the information entered by the user !
Before "echo" i tried $body_message and it gave me this :
0
0

0
0
00
Now with echo i only get two zeros. Echo was sugested by a solution on another website where a user had the same problem but it didn't fix mine.
PHP:

  $field_name = $_POST['cd-name'];
  $field_company = $_POST['cd-company'];
 $field_email = $_POST['cd-email'];
 $field_budget = $_POST['cd-budget'];
 $field_info = $_POST['cd-textarea'];

 $mail_to = 'glxymedias@gmail.com';
 $subject = 'New project '.$field_name;

 echo "Name:  " . $field_name;
 echo "Company: " .$field_company;
 echo "Email:  " . $field_email;
 echo "Budget: " . $field_budget;
 echo "Message:  " . $field_info;

 $headers = 'From: '.$field-email."\r\n";
 $headers .= 'Reply-To: '.$field-email."\r\n";

 $mail_status = mail($mail_to, $subject, $body_message, $headers);

 if ($mail_status) { ?>

<?php
}
else { ?>

<?php
}
?>

HTML:

<form class="cd-form" action="contact.php" method="post">
                <fieldset>

Name

<input class="user wow bounceIn" type="text" name="cd-name" id="cd-name" required>

Company

<input class="company wow bounceIn" type="text" name="cd-company" id="cd-company">

Email

<input class="email wow bounceIn" type="email" name="cd-email" id="cd-email" required>

Budget

                            <select class="budget wow bounceIn">
                                <option value="0"> </option>
                                <option value="1">1000-3000R</option>
                                <option value="2">3000-5000R</option>
                                <option value="3">5000-10000R</option>
                                <option value="3">10000-20000R</option>
                                <option value="3">+20000R</option>
                            </select>

Project Description

<textarea class="message wow bounceIn" name="cd-textarea" id="cd-textarea" required></textarea>

 <input class="buttonsend"type="submit" value="Submit">

                </fieldset>
            </form>

This is the new coe but it still doesn't work. I copied it from your answer. (opened with

ini_set('display_errors', 1);  error_reporting(E_ALL);
$field_name    = $_POST['cd-name'];
$field_company = $_POST['cd-company'];
$field_email   = $_POST['cd-email'];
$field_budget  = $_POST['cd-budget'];
$field_info    = $_POST['cd-textarea'];

$mail_to = 'glxymedias@gmail.com';
$subject = 'New project ' . $field_name;

$body_message = "Name:  " . $field_name . "\n";
$body_message .= "Company: " . $field_company . "\n";
$body_message .= "Email:  " . $field_email . "\n";
$body_message .= "Budget :" . $field_budget . "\n";
$body_message .= "Message:  " . $field_info . "\n";

$headers = 'From: ' . $field_email . "\r\n";
$headers .= 'Reply-To: ' . $field_email . "\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) {
?>

<?php
} else {
?>

<?php

Body:
As I have said you are using $body_message without defining the variable first and you have couple of other errors.

Which are as follows:

$field_budget = $_POST['cd-budget']; cd-budget is undefined because none of your form fields have name attribute cd-budget  your <select class="budget wow bounceIn"> is missing the name attribute therefore the value of it won't be pickedup by your script.

your select tag should be <select class="budget wow bounceIn" name="cd-budget">

$headers = 'From: '.$field-email."\r\n"; this is wrong, you don't use - on variables you should use _ instead, now this $field-email. reads as $field as a string which is also undefined, should throw a Notice: Use of undefined constant email

error reporting on top of your php script you add

ini_set('display_errors', 1);  error_reporting(E_ALL)

This how your code should look :

your select tag on the html page should be this:

<select class="budget wow bounceIn" name="cd-budget">
    <option value="0">&nbsp;</option>
    <option value="1">1000-3000R</option>
    <option value="2">3000-5000R</option>
    <option value="3">5000-10000R</option>
    <option value="3">10000-20000R</option>
    <option value="3">+20000R</option>
</select>

then contact.php

<?php
    $field_name    = $_POST['cd-name'];
    $field_company = $_POST['cd-company'];
    $field_email   = $_POST['cd-email'];
    $field_budget  = $_POST['cd-budget'];
    $field_info    = $_POST['cd-textarea'];

    $mail_to = 'glxymedias@gmail.com';
    $subject = 'New project ' . $field_name;

    $body_message = "Name:  " . $field_name . "\n";
    $body_message .= "Company: " . $field_company . "\n";
    $body_message .= "Email:  " . $field_email . "\n";
    $body_message .= "Budget :" . $field_budget . "\n";
    $body_message .= "Message:  " . $field_info . "\n";

    $headers = 'From: ' . $field_email . "\r\n";
    $headers .= 'Reply-To: ' . $field_email . "\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) {
?>
 <script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'index.html';
</script>
<?php
} else {
?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to glxymedias@gmail.com');
    window.location = 'index.html';
</script>
<?php
}
?>


问:
Making a Fill In Questionaire Java Excercise
Before I begin I want to point out that I'm in severe stress and frustration due to not being able to make this excercise. I have searched and asked all over the internet and I feel hopeless. As my last hope I came to Stack Overflow to ask this question. I do not understand the excercise. It is a very strange one. I would be forever grateful to you if you could assist me in making this excercise that I am stuck with for a month. My life really depends on this. Please help me.

```<code>public class Question {
    private String text;
    private String answer;

    public Question() {
        text = "";
        answer = "";
    }

    public void setText(String questionText) {
        text = questionText;
    }

    public void setAnswer(String correctResponse){
        answer = correctResponse;
    }

    public boolean checkAnswer(String response){
        return response.equals(answer);
    }

    public void display() {
        System.out.println(text);
    }
    }
</code>```

Im going to add a class FillInQuestion to this class. Such a question is constructed with a string that contains the answer, surrounded by _ _, for exam ple, The inventor of Java was James Gosling. The question should be displayed as The inventor of Java was _____. But I'm not sure how I could make this? Could I receive the way to make a string that contains the answer in such a way.

The question is cited as "Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is
constructed with a string that contains the answer, surrounded by _ _, for example,
"The inventor of Java was _James Gosling_". The question should be displayed as
The inventor of Java was _____"

How can I construct a string that contains the answer like that?
How can I display _James Gosling_ like ____?
What do they mean. I dont understand.

Thank you.

答:
I think the input will be a String and you need to extract the answer and create the question text.

```<code>public FillInQuestion(String fillInQuestion) {
    // The inventor of Java was _James Gosling_ -> James Gosling
    this.answer = extractAnswer(fillInQuestion);
    // The inventor of Java was _James Gosling_ -> The inventor of Java was _____
    this.text = createQuestion(fillInQuestion);
}
</code>```

Body:
Before I begin I want to point out that I'm in severe stress and frustration due to not being able to make this excercise. I have searched and asked all over the internet and I feel hopeless. As my last hope I came to Stack Overflow to ask this question. I do not understand the excercise. It is a very strange one. I would be forever grateful to you if you could assist me in making this excercise that I am stuck with for a month. My life really depends on this. Please help me.

public class Question {
    private String text;
    private String answer;

    public Question() {
        text = "";
        answer = "";
    }

    public void setText(String questionText) {
        text = questionText;
    }

    public void setAnswer(String correctResponse){
        answer = correctResponse;
    }

    public boolean checkAnswer(String response){
        return response.equals(answer);
    }

    public void display() {
        System.out.println(text);
    }
    }

Im going to add a class FillInQuestion to this class. Such a question is constructed with a string that contains the answer, surrounded by _ _, for exam ple, The inventor of Java was James Gosling. The question should be displayed as The inventor of Java was _____. But I'm not sure how I could make this? Could I receive the way to make a string that contains the answer in such a way.

The question is cited as "Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is
constructed with a string that contains the answer, surrounded by _ _, for example,
"The inventor of Java was _James Gosling_". The question should be displayed as
The inventor of Java was _____"

How can I construct a string that contains the answer like that?
How can I display _James Gosling_ like ____?
What do they mean. I dont understand.

Thank you.

Body:
I think the input will be a String and you need to extract the answer and create the question text.

public FillInQuestion(String fillInQuestion) {
    // The inventor of Java was _James Gosling_ -> James Gosling
    this.answer = extractAnswer(fillInQuestion);
    // The inventor of Java was _James Gosling_ -> The inventor of Java was _____
    this.text = createQuestion(fillInQuestion);
}


问:
Android -urlConnection.getInputStream() fails - InputStream stays null
I'm trying to retrieve JSON data from the Google Directions Server in Android. But getting the inputstream fails and an exception is thrown. I get the error message ,,null" and that the inputstream is null.

What am I doing wrong with the HTTP connection? The URL is working on my browser.

```<code>     private String doRequest() {
    String response = null;
    HttpURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;
    String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
            "-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";

    try {
        url = new URL(queryString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = urlConnection.getInputStream();
    }

    catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() +e.getMessage();
        }

    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    if (response == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response;
}
</code>```

EDIT:

Here is the error message

EDIT 2:

Okay, I've tried a mix of every ones suggestions. Now when I execute the code nothing happens. I can't open a dialog, so I don't know what problem it is this time.

```<code>public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}
</code>```

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.net.http.HttpsConnection;

import android.os.AsyncTask;

import android.support.v7.app.AlertDialog;

import android.view.View;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

(public class GetData extends AsyncTask)

{

```<code>private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
    this.context = context;
}

protected String doInBackground(String... urls)
{
    this.response = doRequest(urls[0]);

    return response;
}

protected void onPostExecute() {
    // TODO: check this.exception
    // TODO: do something with the feed

    if (this.exception != null && response != null)
    {
        getDialog(getResponse(), context).show();
    }
    else
    {
        getDialog("sorry" + exception.getMessage(), context).show();
    }

}

private String doRequest(String queryString) {
    String response1 = null;
    HttpsURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;

    try {
        url = new URL(queryString);
        urlConnection =(HttpsURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET"); // or POST
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK)
        {
            in = urlConnection.getInputStream();
            response1 = convertStreamToString(in);
        }

    } catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response1 == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() + e.getMessage();
        }

    }

    finally
    {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    if (response1 == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response1;
}

private String convertStreamToString(java.io.InputStream is)
{
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

public String getResponse()
{
    return this.response;
}

public Dialog getDialog(String string, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();

}
</code>```

答:
Your link using HTTPS protocol, but you're trying to cast the connection to HTTP not HTTPS:

```<code>urlConnection = (HttpURLConnection) url.openConnection();
</code>```

Try to remove casting and do:

```<code>URLConnection urlConnection = url.openConnection();
</code>```

Or cast it to HTTPS:

```<code>urlConnection = (HttpsURLConnection) url.openConnection();
</code>```

Now the InputStream should be not null.

Regards

Body:
I'm trying to retrieve JSON data from the Google Directions Server in Android. But getting the inputstream fails and an exception is thrown. I get the error message ,,null" and that the inputstream is null.

What am I doing wrong with the HTTP connection? The URL is working on my browser.

     private String doRequest() {
    String response = null;
    HttpURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;
    String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
            "-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";

    try {
        url = new URL(queryString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = urlConnection.getInputStream();
    }

    catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() +e.getMessage();
        }

    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    if (response == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response;
}

EDIT:

Here is the error message

EDIT 2:

Okay, I've tried a mix of every ones suggestions. Now when I execute the code nothing happens. I can't open a dialog, so I don't know what problem it is this time.

public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.net.http.HttpsConnection;

import android.os.AsyncTask;

import android.support.v7.app.AlertDialog;

import android.view.View;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

(public class GetData extends AsyncTask)

{

private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
    this.context = context;
}

protected String doInBackground(String... urls)
{
    this.response = doRequest(urls[0]);

    return response;
}

protected void onPostExecute() {
    // TODO: check this.exception
    // TODO: do something with the feed

    if (this.exception != null && response != null)
    {
        getDialog(getResponse(), context).show();
    }
    else
    {
        getDialog("sorry" + exception.getMessage(), context).show();
    }

}

private String doRequest(String queryString) {
    String response1 = null;
    HttpsURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;

    try {
        url = new URL(queryString);
        urlConnection =(HttpsURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET"); // or POST
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK)
        {
            in = urlConnection.getInputStream();
            response1 = convertStreamToString(in);
        }

    } catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response1 == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() + e.getMessage();
        }

    }

    finally
    {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    if (response1 == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response1;
}

private String convertStreamToString(java.io.InputStream is)
{
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

public String getResponse()
{
    return this.response;
}

public Dialog getDialog(String string, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();

}

Body:
Your link using HTTPS protocol, but you're trying to cast the connection to HTTP not HTTPS:

urlConnection = (HttpURLConnection) url.openConnection();

Try to remove casting and do:

URLConnection urlConnection = url.openConnection();

Or cast it to HTTPS:

urlConnection = (HttpsURLConnection) url.openConnection();

Now the InputStream should be not null.

Regards


答:
you may attempts to perform a networking operation in  doRequest() on  main thread. Run your code in AsyncTask https://developer.android.com/reference/android/os/AsyncTask.html
following code may help you

problem is with your onPostExecute and dialog. you should override onPostExecute and getDialog will return AlertDialog. Whenever your request is successful exception must be null. check my edited code:

```<code>    class GetData extends AsyncTask<String, Void, String> {

        private Exception exception;
        public String response;
        private Context context;
        private ProgressDialog dialog = null;

        public GetData(Context context) {
            this.context = context;
        }

        protected String doInBackground(String... urls) {
            this.response = doRequest(urls[0]);

            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            // TODO: check this.exception
            // TODO: do something with the feed

            if (this.exception == null && response != null) {
                getDialog(response, context).show();
            } else {
                getDialog("sorry" + exception.getMessage(), context).show();
            }

        }

        private String doRequest(String queryString) {
            HttpsURLConnection urlConnection = null;
            InputStream in = null;
            URL url = null;

            try {
                url = new URL(queryString);
                urlConnection = (HttpsURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET"); // or POST
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
                urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                int responseCode = urlConnection.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    in = urlConnection.getInputStream();
                    response = convertStreamToString(in);
                }

            } catch (Exception e) {
                {
                    exception = e;
                    StringBuilder builder = new StringBuilder();
                    if (response == null)
                        builder.append("Response is null.");
                    if (url == null)
                        builder.append("url is null.");
                    if (urlConnection == null)
                        builder.append("UrlConnection is null.");
                    if (in == null)
                        builder.append("Inputstream is null.");

                    return builder.toString() + e.getMessage();
                }

            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();
            }

            if (response == null) {
                return "sorry, response is null. At least it passed the exceptions.";
            }
            return response;
        }

        private String convertStreamToString(java.io.InputStream is) {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }

       /* public String getResponse() {
            return this.response;
        }*/

        public AlertDialog getDialog(String string, Context context) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(string);
            builder.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            return builder.create();

   }
}

public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(MainActivity.this).execute(queryString);//MainActivity will be your activity
}
</code>```

Title: Android -urlConnection.getInputStream() fails - InputStream stays null

Body:
you may attempts to perform a networking operation in  doRequest() on  main thread. Run your code in AsyncTask https://developer.android.com/reference/android/os/AsyncTask.html
following code may help you

problem is with your onPostExecute and dialog. you should override onPostExecute and getDialog will return AlertDialog. Whenever your request is successful exception must be null. check my edited code:

    class GetData extends AsyncTask<String, Void, String> {

        private Exception exception;
        public String response;
        private Context context;
        private ProgressDialog dialog = null;

        public GetData(Context context) {
            this.context = context;
        }

        protected String doInBackground(String... urls) {
            this.response = doRequest(urls[0]);

            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            // TODO: check this.exception
            // TODO: do something with the feed

            if (this.exception == null && response != null) {
                getDialog(response, context).show();
            } else {
                getDialog("sorry" + exception.getMessage(), context).show();
            }

        }

        private String doRequest(String queryString) {
            HttpsURLConnection urlConnection = null;
            InputStream in = null;
            URL url = null;

            try {
                url = new URL(queryString);
                urlConnection = (HttpsURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET"); // or POST
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
                urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                int responseCode = urlConnection.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    in = urlConnection.getInputStream();
                    response = convertStreamToString(in);
                }

            } catch (Exception e) {
                {
                    exception = e;
                    StringBuilder builder = new StringBuilder();
                    if (response == null)
                        builder.append("Response is null.");
                    if (url == null)
                        builder.append("url is null.");
                    if (urlConnection == null)
                        builder.append("UrlConnection is null.");
                    if (in == null)
                        builder.append("Inputstream is null.");

                    return builder.toString() + e.getMessage();
                }

            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();
            }

            if (response == null) {
                return "sorry, response is null. At least it passed the exceptions.";
            }
            return response;
        }

        private String convertStreamToString(java.io.InputStream is) {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }

       /* public String getResponse() {
            return this.response;
        }*/

        public AlertDialog getDialog(String string, Context context) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(string);
            builder.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            return builder.create();

   }
}

public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(MainActivity.this).execute(queryString);//MainActivity will be your activity
}


问:
crud ajax jquery symfony3 wont work
Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.

I just started learning Symfony 3 and I got trouble adding data using AJAX.
I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.

new.html.twig

UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.

```<code><script>
    $(function () {
        $('.withdropdown').dropdown();
        $('.add-company-launch').modal();

        $('#company-form').submit(function(e) {

            var formUrl = "{{ path('monteal_backend_company_ajax') }}";
            var formData = new FormData(this)

            $.ajax({
                url: formUrl,
                type: 'POST',
                data:  formData,
                 contentType: false,
                 cache: false,
                processData: false,
                success: function(data, textStatus, jqXHR)
                {
                    if(data['status'] === 'success'){
                        alert('success');
                    } else {
                        $('#add-company').html(data['html']);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                }
            });

            e.preventDefault();
        });
    })
</script>
</code>```

{% endblock %}

CompanyController.php

UPDATE: I have create two methods for AJAX,
1. Method to handle a form.
2. AjaxHandler.

```<code>   public function newAction() {

        $company = new Company();

        $form = $this->createForm(CompanyForm::class, $company);

        return $this->render('Admin/Backend/Company/new.html.twig', array(
            'form'=>$form->createView()
        ));
    }

    public function ajaxAction(Request $request) {

        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
        }

        $company = new Company();
        $form = $this->createForm(CompanyForm::class, $company);
        $form->handleRequest($request);

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($company);
            $em->flush();

            return new JsonResponse(array(
                'status' => 'success'), 200
            );
        }

        $html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
            'form' => $form->createView())
        );

        return new JsonResponse(['status' => 'error', 'html' => $html]);
    }
</code>```

答:
1 - In your newAction, just create the form and pass the view (createView) to your template.

2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable :
$html = $this->renderView('yourTemplate.html.twig', array($form->createView()));
Edit: of course your ajax must post the form to your newly ajax url... END Edit

3 - if it is'nt validated
Return a JsonResponse(array('html' => $html, 'status' => 'error'));
    if validated
Return a JsonResponse(array('status' => 'success'));

4 - In your ajax success callback, render the newly form if status error..
    if status success, redirect or whatever

Hope this help

Edit :

something like this for your controler :

```<code>    use Symfony\Component\HttpFoundation\JsonResponse;
    public function ajaxFormHandlerAction(Request $request)
    {
        $company = getYourCompany(); //get it from db?
        $form = $this->createForm(CompanyForm::class, $company));
        $form ->handleRequest($request);
        if($form ->isValid()){
             //do whatever you want, maybe persist, flush()
             return new JsonResponse(array(
                'status' => 'success'));
        }
        $html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
        return new JsonResponse(['status' => 'error', 'html' => $html]);
     }
</code>```

And in your success ajax callback:

```<code>success: function(data, textStatus, jqXHR)
{
    if(data['status'] === 'success'){
        alert('success');
        // maybe redirect the user ???
    }else if(data['status' === 'error']){
        $('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
    }
},
</code>```

You have to create a twig template with only the modal inside...

Title: crud ajax jquery symfony3 wont work

Body:
Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.

I just started learning Symfony 3 and I got trouble adding data using AJAX.
I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.

new.html.twig

UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.

{% endblock %}

CompanyController.php

UPDATE: I have create two methods for AJAX,
1. Method to handle a form.
2. AjaxHandler.

   public function newAction() {

        $company = new Company();

        $form = $this->createForm(CompanyForm::class, $company);

        return $this->render('Admin/Backend/Company/new.html.twig', array(
            'form'=>$form->createView()
        ));
    }

    public function ajaxAction(Request $request) {

        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
        }

        $company = new Company();
        $form = $this->createForm(CompanyForm::class, $company);
        $form->handleRequest($request);

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($company);
            $em->flush();

            return new JsonResponse(array(
                'status' => 'success'), 200
            );
        }

        $html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
            'form' => $form->createView())
        );

        return new JsonResponse(['status' => 'error', 'html' => $html]);
    }

Body:
1 - In your newAction, just create the form and pass the view (createView) to your template.

2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable :
$html = $this->renderView('yourTemplate.html.twig', array($form->createView()));
Edit: of course your ajax must post the form to your newly ajax url... END Edit

3 - if it is'nt validated
Return a JsonResponse(array('html' => $html, 'status' => 'error'));
    if validated
Return a JsonResponse(array('status' => 'success'));

4 - In your ajax success callback, render the newly form if status error..
    if status success, redirect or whatever

Hope this help

Edit :

something like this for your controler :

    use Symfony\Component\HttpFoundation\JsonResponse;
    public function ajaxFormHandlerAction(Request $request)
    {
        $company = getYourCompany(); //get it from db?
        $form = $this->createForm(CompanyForm::class, $company));
        $form ->handleRequest($request);
        if($form ->isValid()){
             //do whatever you want, maybe persist, flush()
             return new JsonResponse(array(
                'status' => 'success'));
        }
        $html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
        return new JsonResponse(['status' => 'error', 'html' => $html]);
     }

And in your success ajax callback:

success: function(data, textStatus, jqXHR)
{
    if(data['status'] === 'success'){
        alert('success');
        // maybe redirect the user ???
    }else if(data['status' === 'error']){
        $('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
    }
},

You have to create a twig template with only the modal inside...


问:
How to Initialize adapter in RecycleVIew?
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

```<code> No adapter attached; skipping layout
</code>```

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

```<code>public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}
</code>```

ListViewAdapter

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}
</code>```

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

```<code>  RecyclerView.Adapter<MyViewHolder>
</code>```

then getting errors that's why i just kept extends Baseadapter what i did i listview.

答:
Use this library for Horizontal ListView. Works like a charm.

https://github.com/MeetMe/Android-HorizontalListView

Body:
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

 No adapter attached; skipping layout

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}

ListViewAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

  RecyclerView.Adapter<MyViewHolder>

then getting errors that's why i just kept extends Baseadapter what i did i listview.


问:
How to append row in table body using script
From the json data I'm trying to display values in table of html but it fails to do the same. I'm not able to recognize the error.I've used in the following way but I can't find the answer:

```<code><html>
<head>
<title>Check</title>
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
function getRow(begin,phrase,buggy,words,negative,comma,loos,leng) {

jQuery('#donut').empty();

jQuery(document).ready(function () {
var nb = begin;
var bp = phrase;
var bw = buggy;
var uw = words;
var nt = negative;
var punc = comma;
var loose = loos;
Morris.Donut({
  element: 'donut',
  data: [
    {value: nb, label: 'Should not begin'},
    {value: bp, label: 'Buggy phrase'},
    {value: bw, label: 'Buggy word'},
    {value: uw, label: 'Useless word'},
    {value: nt, label: 'Negative term'},
    {value: punc, label: 'Punctuation mistake'},
    {value: loose, label: 'Loose sentence'},
    {value: 0, label: 'Tense'}
  ],
  formatter: function (x) { return x + "%"}
}).on('click', function(i, row){
  console.log(i, row);
});
});
}
</script>

<script>

jQuery(document).ready(function () {

var tab1 = "";
var posts = [{"begin": 0, "loose": 1, "leng": 8, "buggy": 0, "negative": 1, "nam": "10.Conclusion and future ", "comma": 5, "words": 1, "date": "2017-04-03 16:08:40", "phrase": 0}, {"begin": 0, "loose": 1, "leng": 11, "buggy": 5, "negative": 1, "nam": "8.Chapter 5.docx", "comma": 5, "words": 0, "date": "2017-04-03 16:06:49", "phrase": 0}, {"begin": 10, "loose": 6, "leng": 280, "buggy": 16, "negative": 12, "nam": "7.Chapter 4.docx", "comma": 194, "words": 2, "date": "2017-04-03 12:11:23", "phrase": 0}, {"begin": 1, "loose": 2, "leng": 20, "buggy": 5, "negative": 6, "nam": "eunoia", "comma": 4, "words": 3, "date": "2016-12-20 12:33:40", "phrase": 4}];

jQuery(posts).each(function(i,f){
alert(f.leng);
   var dt = f.date.split(" ");
   var tblRow = "<tr role=\"row\">" + "<td onclick=\"getRow(" +f.begin,f.phrase,f.buggy,f.words,f.negative,f.comma,f.loose,f.leng+")\">" + f.nam +"<td>" + dt[0] + "</td>" + "<td>" + dt[1] + "</td>" + "</tr>";
       tab1 += tblRow;

     });
            jQuery(tab1).appendTo("#example tbody");

});
</script>
</head>

<body>

            <table id="example" style="width: 100%; border: 1px solid black">
                <thead>
                    <tr role="row">
                        <th rowspan="1" colspan="1" style="width: 150px;">File Name</th>
                        <th rowspan="1" colspan="1" style="width: 109px;">Date</th>
                        <th rowspan="1" colspan="1" style="width: 82px;">Time</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>

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

From the json data I'm trying to display values in table of html but it fails to do the same. I'm not able to recognize the error.

答:
You can append table row like below,</p>

```<code>function table_element(posts) {
for (i = 0; i < posts.length; i++) {
  if (i % 2 == 0) {
    var t1= "<tr class=\"even\" role=\"row\">" + "<td onclick=\"getRow("  + posts[i].begin, posts[i].leng + ")\" >" + "</td>" + "<td class=\"\">" + posts[i].nam + "</td>" + "<td class=\"\">" + posts[i].words + "</td>" + "<td class=\"sorting_1\">" + posts[i].date.split(" ")[0] + "</td>" + "<td>" + posts[i].date.split(" ")[1] + "</td>" + "</tr>"
    $("#example1").append(t1);
  } else {
    var t2 = "<tr class=\"odd\" role=\"row\">"+"<td onclick=\"getRow("+posts[i].begin, posts[i].leng+")\">"+"</td>"+"<td class=\"\">" +posts[i].nam+"</td>"+"<td class=\"\">" +posts[i].words+"</td>"+"<td class=\"sorting_1\">" +posts[i].date.split(" ")[0]+"</td>"+"<td>"+posts[i].date.split(" ")[1]+"</td>"+"</tr>"
    $("#example1").append(t2);
 }
 }
}
</code>```

Body:
From the json data I'm trying to display values in table of html but it fails to do the same. I'm not able to recognize the error.I've used in the following way but I can't find the answer:

<title>Check</title>
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

                        File Name
                        Date
                        Time

From the json data I'm trying to display values in table of html but it fails to do the same. I'm not able to recognize the error.

Body:
You can append table row like below,

function table_element(posts) {
for (i = 0; i < posts.length; i++) {
  if (i % 2 == 0) {
    var t1= "<tr class=\"even\" role=\"row\">" + "<td onclick=\"getRow("  + posts[i].begin, posts[i].leng + ")\" >" + "</td>" + "<td class=\"\">" + posts[i].nam + "</td>" + "<td class=\"\">" + posts[i].words + "</td>" + "<td class=\"sorting_1\">" + posts[i].date.split(" ")[0] + "</td>" + "<td>" + posts[i].date.split(" ")[1] + "</td>" + "</tr>"
    $("#example1").append(t1);
  } else {
    var t2 = "<tr class=\"odd\" role=\"row\">"+"<td onclick=\"getRow("+posts[i].begin, posts[i].leng+")\">"+"</td>"+"<td class=\"\">" +posts[i].nam+"</td>"+"<td class=\"\">" +posts[i].words+"</td>"+"<td class=\"sorting_1\">" +posts[i].date.split(" ")[0]+"</td>"+"<td>"+posts[i].date.split(" ")[1]+"</td>"+"</tr>"
    $("#example1").append(t2);
 }
 }
}


问:
How to de-saturate a color defined by RGB in declarative QML
Using QtQuick, is it possible to take an existing color defined by RGB and desaturate it without resorting to Javascript?</p>

答:
```<code>function desaturate(colorString)
{
    let c = Qt.darker(colorString, 1.0);
    return Qt.hsla(c.hslHue, 0.0, c.hslLightness, c.a);
}
</code>```

ContentLicense: CC BY-SA 4.0


问:
SUMIFs in Google sheets with 2 filters on same criteria range
I have looked at various answers but all use filters on different columns. I need an OR type filter like this:

=SUMIFs(B2:B22,C2:C22,"Incurred",C2:C22,"Expected")

Where C2:C22 specifies if the cell in B is an incurred or expected or deferred expense.

How do I do this? Note the filters are on the same set of cells in column C.

答:
This is the data in A6:C6:

```<code>1   A   C
2   B   D
3   A   D
4   B   C
5   A   D
6   B   D
</code>```

To sum the values if column B is A or column C is D you can use:

```<code>=SUM(ARRAYFORMULA((IF(((B1:B6="A")+(C1:C6="D"))>0,A1:A6))))
</code>```

This uses the fact that True equals 1 and False equals 0 once you want to use them in equation.

Body:
This is the data in A6:C6:

1   A   C
2   B   D
3   A   D
4   B   C
5   A   D
6   B   D

To sum the values if column B is A or column C is D you can use:

=SUM(ARRAYFORMULA((IF(((B1:B6="A")+(C1:C6="D"))>0,A1:A6))))

This uses the fact that True equals 1 and False equals 0 once you want to use them in equation.


问:
Split uint8 into 4 unit2 in C to have unit10 later
I want to make an extension to my uint8 variable with 2 other bits to have let say uint10. For that I used this method, but it takes only the mask in the consideration.</p>

```<code>void splitbits(unsigned int x){ //x=11001010 and i want to have this for any given X
   split[0]=(x>> 6) & 0x01 ; //split[0]=11
   split[1]=(x>> 4) & 0x01 ; //split[1]=00
   split[2]=(x>> 2) & 0x01 ; //split[2]=10
   split[3]=x & 0x01 ; //split[3]=10
}
</code>```

答:
```<code>split[0]=(x>> 6) & 0x01 ; //split[0]=11
</code>```

The comment is factually incorrect. You mask out all but the least significant bit, not the two least significant bits. You need to mask with binary 11 which is 3 in decimal or hex.

```<code>split[0]=(x>> 6) & 0x03 ; //split[0]=11
//                    ^ binary 11
</code>```

However, if you are wanting to make a 10 bit number out of any other number, you can do it all in one go. i.e.

```<code>uint16_t my10Bit number = anotherNumber & 0x3ff // 3ff is 1111111111 in binary
</code>```

I used uint16_t because that is the smallest portable type that will contain 10 bits.

Body:
I want to make an extension to my uint8 variable with 2 other bits to have let say uint10. For that I used this method, but it takes only the mask in the consideration.

void splitbits(unsigned int x){ //x=11001010 and i want to have this for any given X
   split[0]=(x>> 6) & 0x01 ; //split[0]=11
   split[1]=(x>> 4) & 0x01 ; //split[1]=00
   split[2]=(x>> 2) & 0x01 ; //split[2]=10
   split[3]=x & 0x01 ; //split[3]=10
}

Body:
split[0]=(x>> 6) & 0x01 ; //split[0]=11

The comment is factually incorrect. You mask out all but the least significant bit, not the two least significant bits. You need to mask with binary 11 which is 3 in decimal or hex.

split[0]=(x>> 6) & 0x03 ; //split[0]=11
//                    ^ binary 11

However, if you are wanting to make a 10 bit number out of any other number, you can do it all in one go. i.e.

uint16_t my10Bit number = anotherNumber & 0x3ff // 3ff is 1111111111 in binary

I used uint16_t because that is the smallest portable type that will contain 10 bits.


问:
C++ equivalent of fgets for reading from popen
I need to process some data from standard output. Here is the code I am using:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

```<code>FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}
</code>```

答:
Use std::getline (preferably, giving some std::string which would be updated) or std::istream::getline

(however, standard C++ don't know about popen....)

BTW, on POSIX, with both C and C++ you might use getline(3) (dealing with some malloc-ed char*buffer read from some FILE* handle).

Body:
I need to process some data from standard output. Here is the code I am using:

FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}


问:
What's the simplest way of returning the larger of two numbers?
Let's say I have an entity that looks like this:

```<code>public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}
</code>```

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}
</code>```

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}
</code>```

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

```<code>public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}
</code>```

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

答:
Just store the max value in a temporary:</p>

```<code>public DateTime LastActivity
{
    get {
        DateTime maxLastUpdated = Pictures.Max(x => x.LastUpdated);
        return maxLastUpdated > this.LastUpdated
            ? maxLastUpdated
            : this.LastUpdated) };
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

Body:
Just store the max value in a temporary:

public DateTime LastActivity
{
    get {
        DateTime maxLastUpdated = Pictures.Max(x => x.LastUpdated);
        return maxLastUpdated > this.LastUpdated
            ? maxLastUpdated
            : this.LastUpdated) };
}


问:
Use of undeclared type "Firebase"
I installed cocoapods using "sudo gem install cocoapods" and followed the very basic instructions from Firebase along with many tutorials to install the frameworks, yet I keep getting this error when I try to create my first reference. The file lets me import Firebase without error, it lets me use FIRApp.configure() without error, but when I want to make a Firebase reference I can't do it. Any help would be much appreciated, thank you.

答:
To solve your problem, use an import statement this way after pod installation:

```<code>#import <FirebaseAuth/FirebaseAuth.h>
</code>```

Add this in appdelegate.h and wherever you are using view controller.

Title: Use of undeclared type "Firebase"

Body:
To solve your problem, use an import statement this way after pod installation:

#import <FirebaseAuth/FirebaseAuth.h>

Add this in appdelegate.h and wherever you are using view controller.


问:
Mapping through an array of objects in javascript
i have an array of objects like this:

```<code>[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
</code>```

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

答:
Simple solution using Array#forEach and Object.keys().

var arr = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150}], obj = {}, res = [];

arr.forEach(function(v){
 (obj[v.side] || (obj[v.side] = [])).push(v.price);
});
var res = Object.keys(obj).reduce(function(s,a) {
  s[a] = obj[a].length;
  s['avg' + a] = obj[a].reduce((a,b) => a + b) / obj[a].length;
  return s;
}, {});
console.log(res);```

Body:
i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)


问:
Position fixed - not breaking out of document flow
Im pretty good with my css and i'd like to think i can figure why most things do what they do when it comes to frontend development. But i came across an issue today that I don't fully understand.

Heres the code:

.nav-toggle {
  position: absolute;
  transform: translateY(50%);
}

.nav-open .nav-toggle:after {
  background: rgba(0, 0, 0, 0.5);
  content: '';
  display: block;
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span data-action="toggle-nav" class="action nav-toggle">
         <span>Menu</span>
</span></code>```

Here is a fiddle for it:

https://jsfiddle.net/0vm962be/1/

And here is the second fiddle with the transform commented out.

https://jsfiddle.net/0vm962be/2/

So you'll see the difference.

So, what i would expect to happen is the after would be 100% width of the body and 100% height of the body, when the parent element has a .nav-open class.

However because of 1 simple line of code (transform: translateY(50%)), this doesn't happen, what actually happens is the fixed element acts like a absolutely positioned element inside of the .nav-toggle and only goes 100% to its parent.

why would a transform on a parent have an impact of a fixed element? I though position: fixed; broke the document flow no matter what. And only listened to the window width height. I need to learn why this happened.

Any advice would be great. Links to specs etc?

答:
Haha, that's funny. I had the same issue not that long ago.

Apparently, it's a bug in webkit browsers.
See: https://bugs.chromium.org/p/chromium/issues/detail?id=20574
As mentioned here: https://stackoverflow.com/a/2637267/2632061

That means, there is no way this can work, unfortunately.
You could try something similar with flexbox probably but what are you even trying to achieve, it's not 100% clear to me just from that fiddle.

In the HTML namespace, any value other than none for the transform
  results in the creation of both a stacking context and a containing
  block. The object acts as a containing block for fixed positioned
  descendants.

This means that fixed positioning becomes fixed to the transformed element, rather than the viewport.

Body:
Im pretty good with my css and i'd like to think i can figure why most things do what they do when it comes to frontend development. But i came across an issue today that I don't fully understand.

Heres the code:

.nav-toggle {
  position: absolute;
  transform: translateY(50%);
}

.nav-open .nav-toggle:after {
  background: rgba(0, 0, 0, 0.5);
  content: '';
  display: block;
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  z-index: 1;
}

         Menu

Here is a fiddle for it:

https://jsfiddle.net/0vm962be/1/

And here is the second fiddle with the transform commented out.

https://jsfiddle.net/0vm962be/2/

So you'll see the difference.

So, what i would expect to happen is the after would be 100% width of the body and 100% height of the body, when the parent element has a .nav-open class.

However because of 1 simple line of code (transform: translateY(50%)), this doesn't happen, what actually happens is the fixed element acts like a absolutely positioned element inside of the .nav-toggle and only goes 100% to its parent.

why would a transform on a parent have an impact of a fixed element? I though position: fixed; broke the document flow no matter what. And only listened to the window width height. I need to learn why this happened.

Any advice would be great. Links to specs etc?


问:
Nav-tabs don't work on route profile/{name} Laravel
I made a profile page in Laravel with something like /profile/{name} and I use a UserController@showProfile:

```<code>public function showProfile($name)
{
    if(!Cache::has($name))
    {
        if(DB::table('users')->where('name', $name)->exists())
        {
            $user = DB::table('users')->where('name', $name)->get();
            Cache::put($name, $user, 10);
        }
        else
        {
            return view ('error404');
        }
    }

    return view ('user.profile', ['profile_stats' => Cache::get($name)]);
}
</code>```

But nav-tabs don't work if I put /profile/{name}, if I let it just /profile in routes everything works.

This is profile.blade.php with nav-tabs: https://pastebin.com/wzKM8wRd and this https://pastebin.com/XLBKX6Gr is the layout.

Route::get('profile/{name}', 'UserController@showProfile');

答:
I solved, problem was:

```<code><script type="text/javascript">
        window.jQuery || document.write("<script src='js/jquery.js'>"+"<"+"/script>");
    </script>
</code>```

I forgot to put / in front of js/jquery.js:

```<code><script type="text/javascript">
        window.jQuery || document.write("<script src='/js/jquery.js'>"+"<"+"/script>");
    </script>
</code>```

However thanks for your answers!

Body:
I made a profile page in Laravel with something like /profile/{name} and I use a UserController@showProfile:

public function showProfile($name)
{
    if(!Cache::has($name))
    {
        if(DB::table('users')->where('name', $name)->exists())
        {
            $user = DB::table('users')->where('name', $name)->get();
            Cache::put($name, $user, 10);
        }
        else
        {
            return view ('error404');
        }
    }

    return view ('user.profile', ['profile_stats' => Cache::get($name)]);
}

But nav-tabs don't work if I put /profile/{name}, if I let it just /profile in routes everything works.

This is profile.blade.php with nav-tabs: https://pastebin.com/wzKM8wRd and this https://pastebin.com/XLBKX6Gr is the layout.

Route::get('profile/{name}', 'UserController@showProfile');

Body:
I solved, problem was:

<script type="text/javascript">
        window.jQuery || document.write("<script src='js/jquery.js'>"+"<"+"/script>");
    </script>

I forgot to put / in front of js/jquery.js:

<script type="text/javascript">
        window.jQuery || document.write("<script src='/js/jquery.js'>"+"<"+"/script>");
    </script>

However thanks for your answers!


问:
Check only used space on CentOS server
I want to view only column named Use% i have tried to do like this:

df -h | awk '{print $%}'

But i have too long names in Filesystem colum and when i do that it show me mixed colum Use% and Mounted on.

How can I display only the Use% column

答:
In a normal case, if the file-system column does NOT have whitespaces to worry about, e.g. for an output as

```<code>$ df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/msys64       238G  132G  107G  56% /
</code>```

doing df -h | awk 'NR>1{print $5}' would have been just fine to print the 5th column representing the usage. But for a case as complex as you said, when the file-system name is expected to have some spaces, looping through the columns to find the column matching % would be the right approach,

```<code>df -h | awk 'NR>1{for(i=1;i<=NF;i++) if (match($i,/\%$/)) { print $i; break } }'
56%
</code>```

Title: Check only used space on CentOS server

Body:
In a normal case, if the file-system column does NOT have whitespaces to worry about, e.g. for an output as

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/msys64       238G  132G  107G  56% /

doing df -h | awk 'NR>1{print $5}' would have been just fine to print the 5th column representing the usage. But for a case as complex as you said, when the file-system name is expected to have some spaces, looping through the columns to find the column matching % would be the right approach,

df -h | awk 'NR>1{for(i=1;i<=NF;i++) if (match($i,/\%$/)) { print $i; break } }'
56%


问:
Systeminfo: Product ID
If you type systeminfo at the command prompt, there is a listing for Product ID.  Can someone explain what this is exactly, and would it make a good seed for a registration code algorithm?

答:
It's a good start. But (IMHO) you can use directly a GUID.
Read more here: http://en.wikipedia.org/wiki/Device_fingerprint (read about Active fingerprinting)

OwnerDisplayName: stout

Title: Systeminfo: Product ID

OwnerDisplayName: Click Ok


问:
Should i use nginx for my image hosting site with high traffic?
I am suggested by a friend to use nginx for my site http://www.imgzzz.com . its an image hosting site with loads of traffic.

Currently im on a vps ..CentOS 5.4 x64 , Apache

Most views are on image pages. So far to decrease the load on server i have done cache of almost all data like user details, image name, path, category details etc.

Still i have to go with about 3 sql queries every page/view.

Addition of Views

Displaying Views

Addition of user ad views with respect to their ads shown

Considering the traffic from social media sites like digg, stumbleupon. per second online user peaks upto 1500-2500. So i guess you can get the idea of php queries per second.. Sometimes it causes the server to lag.

The rest of the stuff on  image pages is static. So now do you guys suggest nginx or any other better option for my server?

Thanks in advance :)
Edit : This is a custom system not any cms

答: I would recommend using nginx as your static file server.  I run nginx for this and it works great, and I could vouch for alot of other people I know that uses it.  It's fast and reliable.</p>


问:
Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined
I upgraded to the latest Java 7u40 on MacOS X and started getting the following message on the console when launching my application using Eclipse. The app works fine but I would like to find out the cause of the problem and hopefully a fix for it.

```<code>objc[10012]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
</code>```

Does anyone know why this message is printed and how to fix it?

答:
As of October 2017, this issue is now resolved in

jdk1.9

jdk1.8.152

jdk1.7.161

Body:
I upgraded to the latest Java 7u40 on MacOS X and started getting the following message on the console when launching my application using Eclipse. The app works fine but I would like to find out the cause of the problem and hopefully a fix for it.

objc[10012]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.

Does anyone know why this message is printed and how to fix it?


问:
IntersectionObserver debouncer
I'm using the IntersectionObserver polyfill to lazyload images on tiles.
The problem is I have a few thousand tiles each one with a image on it that needs to be lazyloaded.

Previously I used a scroll debouncer to load the image only when the scroll stops which was gave huge improvement in performance.

The question is how to use a scroll debouncer together with IntersectionObserver?

One solution but a stupid one is to create a preliminary array of visible items and add a timeout

```<code> let timeoutLastEntities;

 new IntersectionObserver((entries) => {
     setTimeout(function(){
        timeoutLastEntities.add(entities);
      }, 3000);
      // debouncer logic
 }, { threshold: 0.5 }).observe(imageTileElements);
</code>```

答:
Ok i found a recipe but it's still not fitting perfectly</p>

```<code>private initializeLazyLoader() {
    this.observer = new IntersectionObserver(
        this.processLazyChanges,
        { threshold: [0.5] }
    );

    // When scroll is triggered
    this.registerIntersectionObserverEvent(this.nativeElement, 'scroll', 300);
}

processLazyChanges(changes: any) {
    changes.forEach((change: any) => {
        var container = change.target;
        $(container).css('border', '1px solid red');
        this.observer.unobserve(container);
    });
}

private registerIntersectionObserverEvent(element: any, event: any, debouncerTime: number) {
    Observable.fromEvent(element, event)
        .debounceTime(debouncerTime)
        .subscribe((event) => this.initializeObservers(event));
}

private initializeObservers(event: any) {
    Array.from(document.querySelectorAll('app-tile')).forEach((tile: any) => {
        this.observer.observe(tile);
    });
}
</code>```

Title: IntersectionObserver debouncer

Body:
I'm using the IntersectionObserver polyfill to lazyload images on tiles.
The problem is I have a few thousand tiles each one with a image on it that needs to be lazyloaded.

Previously I used a scroll debouncer to load the image only when the scroll stops which was gave huge improvement in performance.

The question is how to use a scroll debouncer together with IntersectionObserver?

One solution but a stupid one is to create a preliminary array of visible items and add a timeout

 let timeoutLastEntities;

 new IntersectionObserver((entries) => {
     setTimeout(function(){
        timeoutLastEntities.add(entities);
      }, 3000);
      // debouncer logic
 }, { threshold: 0.5 }).observe(imageTileElements);

Body:
Ok i found a recipe but it's still not fitting perfectly

private initializeLazyLoader() {
    this.observer = new IntersectionObserver(
        this.processLazyChanges,
        { threshold: [0.5] }
    );

    // When scroll is triggered
    this.registerIntersectionObserverEvent(this.nativeElement, 'scroll', 300);
}

processLazyChanges(changes: any) {
    changes.forEach((change: any) => {
        var container = change.target;
        $(container).css('border', '1px solid red');
        this.observer.unobserve(container);
    });
}

private registerIntersectionObserverEvent(element: any, event: any, debouncerTime: number) {
    Observable.fromEvent(element, event)
        .debounceTime(debouncerTime)
        .subscribe((event) => this.initializeObservers(event));
}

private initializeObservers(event: any) {
    Array.from(document.querySelectorAll('app-tile')).forEach((tile: any) => {
        this.observer.observe(tile);
    });
}