答:
Private data members of a class are not accessible from other classes when they are set as private.

But with the use of return functions, it is possible for the child classes to retrieve private data members from the parent class.

Example

```<code>class Parent{
    int age = 35;

    public int getAge(){
        return age;
    }
}

class Child : public Parent{

}

int main(){
    Child c;
    printf("%d", c.getAge());
    return 0;
}
</code>```

The output will be

```<code>35
</code>```

Title: Does the sub class inherit the private data members too in c++? But are accessed through the public methods of the super class?

Body: I'm new to c++. I used to believe that the super class private data members and member functions are not inherited by the derived class. But recently I saw a program in which the private member of the super class could be accessed through its public member function. How is it possible when the derived class doesn't have the private data member ..? please clear my concept if I am wrong .

Body:
Private data members of a class are not accessible from other classes when they are set as private.

But with the use of return functions, it is possible for the child classes to retrieve private data members from the parent class.

Example

class Parent{
    int age = 35;

    public int getAge(){
        return age;
    }
}

class Child : public Parent{

}

int main(){
    Child c;
    printf("%d", c.getAge());
    return 0;
}

The output will be

35


来源: stackexchange

问:
Difference between an object in Java versus an object in Scala
I have started learning Scala.Is there any difference between an object in Java versus an object in Scala. As per my understanding the object created in Scala is singleton. Any other pointers please. </p>

答:
It depends on how you are creating an object in Scala. It's not like all object creation is Singleton.

For example:

```<code>object Shiva { /*some code*/}
</code>```

Will create a singleton object. But if you define a class like you do in Java, you can create multiple instances.

ContentLicense: CC BY-SA 3.0

Body:
It depends on how you are creating an object in Scala. It's not like all object creation is Singleton.

For example:

object Shiva { /*some code*/}

Will create a singleton object. But if you define a class like you do in Java, you can create multiple instances.


问:
Very simple Javascript ad placement engine
I have ten different banner ads uploaded on my site. I want to make a Javascript program that will randomly show one each time a page is loaded. How would I do this?</p>

答:
Why not do it server-side? i.e. before rendering the page, you pick one banner from your server?

If you really must do it using javascript, consider using AJAX

ContentLicense: CC BY-SA 2.5


问:
How I get all users except the current_user by username
In my index controller I have this:</p>

```<code>@users = User.where(User.find_by(username: params[:id]))
</code>```

答:
If your current_user has set in application_controller.rb you can create a method there that list all users without him like:

```<code>class ApplicationController < ActionController::Base
    ...
    def all_users
        User.where.not id: current_user.id
    end
end
</code>```

Whatever, you could use:

```<code>User.where.not username: current_user.username
</code>```

Body:
In my index controller I have this:

@users = User.where(User.find_by(username: params[:id]))

Body:
If your current_user has set in application_controller.rb you can create a method there that list all users without him like:

class ApplicationController < ActionController::Base
    ...
    def all_users
        User.where.not id: current_user.id
    end
end

Whatever, you could use:

User.where.not username: current_user.username


问:
Web.config iis url rewrite
I am trying to add a iis url rewrite rule that differs in the development environment (on my local machine) and once uploaded to the server and published (deployed).

My IIS Rewrite Rule works, but I don't want to have to remember to change localhost to my server hosting address once I deploy the website. Any suggestions?

Below are my IIS URL Rewrite rules in <system.webServer>

```<code><!-- IIS Rules Rewrite -->
<rewrite>
  <rules>
<!-- Serve site map with proper XML content type response header. -->
    <rule name="Sitemap XML" enabled="true" stopProcessing="true">
      <match url="sitemap.xml" />
      <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
    </rule>
    <!-- Access block rule - is used to block all requests made to a Web site if those requests do not have the host header set. This type of rule is useful when you want to prevent hacking attempts that are made by issuing HTTP requests against the IP address of the server instead of using the host name -->
    <rule name="Fail bad requests">
      <match url=".*"/>
      <conditions>
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="AbortRequest" />
    </rule>
    <!-- HTTP to HTTPS Rule
    <rule name="Redirect to https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" negate="false" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="off" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
    </rule>-->
</code>```

答:
I think you can use configuration file transformation (msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx)

NOTE: The whole system.webServer section will be replaced with whatever put inside the web.release.config

web.config

```<code><?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
          <rules>
            <rule name="Sitemap XML" enabled="true" stopProcessing="true">
              <match url="sitemap.xml" />
              <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
            </rule>
            <rule name="Fail bad requests">
              <match url=".*"/>
              <conditions>
                <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
              </conditions>
              <action type="AbortRequest" />
            </rule>
          </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

web.release.config

```<code><?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer xdt:Transform="Replace">
        <rewrite>
          <rules>
            <rule name="Sitemap XML" enabled="true" stopProcessing="true">
              <match url="sitemap.xml" />
              <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
            </rule>
            <rule name="Fail bad requests">
              <match url=".*"/>
              <conditions>
                <add input="{HTTP_HOST}" pattern="YOUR_NEW_SERVER_URL_HERE" negate="true" />
              </conditions>
              <action type="AbortRequest" />
            </rule>
          </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

Title: Web.config iis url rewrite

Body:
I am trying to add a iis url rewrite rule that differs in the development environment (on my local machine) and once uploaded to the server and published (deployed).

My IIS Rewrite Rule works, but I don't want to have to remember to change localhost to my server hosting address once I deploy the website. Any suggestions?

Below are my IIS URL Rewrite rules in <system.webServer>

<rewrite>
  <rules>

    <rule name="Sitemap XML" enabled="true" stopProcessing="true">
      <match url="sitemap.xml" />
      <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
    </rule>

    <rule name="Fail bad requests">
      <match url=".*"/>
      <conditions>
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="AbortRequest" />
    </rule>

Body:
I think you can use configuration file transformation (msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx)

NOTE: The whole system.webServer section will be replaced with whatever put inside the web.release.config

web.config

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
          <rules>
            <rule name="Sitemap XML" enabled="true" stopProcessing="true">
              <match url="sitemap.xml" />
              <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
            </rule>
            <rule name="Fail bad requests">
              <match url=".*"/>
              <conditions>
                <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
              </conditions>
              <action type="AbortRequest" />
            </rule>
          </rules>
        </rewrite>
    </system.webServer>
</configuration>

web.release.config

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer xdt:Transform="Replace">
        <rewrite>
          <rules>
            <rule name="Sitemap XML" enabled="true" stopProcessing="true">
              <match url="sitemap.xml" />
              <action type="Rewrite" url="sitemap.aspx" appendQueryString="false"/>
            </rule>
            <rule name="Fail bad requests">
              <match url=".*"/>
              <conditions>
                <add input="{HTTP_HOST}" pattern="YOUR_NEW_SERVER_URL_HERE" negate="true" />
              </conditions>
              <action type="AbortRequest" />
            </rule>
          </rules>
        </rewrite>
    </system.webServer>
</configuration>

ContentLicense: CC BY-SA 4.0


问:
Node.js and Grunt install on Windows
I have Node.js installed and I have ran npm install -g grunt-cli I have cd to the directory of the app I am to work on and followed the instructions here. When I run grunt in my cmd it returns

```<code>module.js:340
    throw err;
          ^

Error: Cannot find module '\\Server\username$\Redirected\AppData\npm\AppData\npm\node_modules\grunt-cli'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3
</code>```

I really am not sure why its trying to read from \AppData\npm\AppData\npm\ as I haven't made any changes and I don't know how to change the grunt location

But when I use npm install -g grunt-cli it downloads and installs to the following \\Server\username$\Redirected\AppData\npm\node_modules\grunt-cli

答:
You need to change the global install directory.

Try this ..

In C:\Users{username}\, create .npmrc file with contents:

```<code>prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"
</code>```

This is discussed more fully here:

Change default global installation directory for node.js modules in Windows?

Title: Node.js and Grunt install on Windows

Body:
I have Node.js installed and I have ran npm install -g grunt-cli I have cd to the directory of the app I am to work on and followed the instructions here. When I run grunt in my cmd it returns

module.js:340
    throw err;
          ^

Error: Cannot find module '\\Server\username$\Redirected\AppData\npm\AppData\npm\node_modules\grunt-cli'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

I really am not sure why its trying to read from \AppData\npm\AppData\npm\ as I haven't made any changes and I don't know how to change the grunt location

But when I use npm install -g grunt-cli it downloads and installs to the following \\Server\username$\Redirected\AppData\npm\node_modules\grunt-cli

Body:
You need to change the global install directory.

Try this ..

In C:\Users{username}\, create .npmrc file with contents:

prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"

This is discussed more fully here:

Change default global installation directory for node.js modules in Windows?


问:
Get data from text in UTF8 format URL
There is a text hosted on a server, in plain text but I try to get that data in UTF-8 format that is able to recognize "ñ" and more. I tried this

```<code>String readLine;
    try {
        URL url = new URL("http://miurl/data.txt");
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

        while ((readLine = in.readLine()) != null) {
           byte ptext[] = readLine.getBytes(ISO_8859_1);
           String value = new String(ptext, UTF_8);
           System.out.println(value);
        }

    }
    catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

The problem is that it reads data from url but not encoded as utf8, the letters such as "ñ" are printed strangely.

答:
Did you simply tried this ?

```<code>        String readLine;
        try {
            URL url = new URL("http://miurl/data.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

            while ((readLine = in.readLine()) != null) {
                System.out.println(readline);
            }

        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
</code>```

I tried this on this sample text from here
and it parses all UTF-8 characters quite okay.

Title: Get data from text in UTF8 format URL

Body:
There is a text hosted on a server, in plain text but I try to get that data in UTF-8 format that is able to recognize "ñ" and more. I tried this

String readLine;
    try {
        URL url = new URL("http://miurl/data.txt");
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

        while ((readLine = in.readLine()) != null) {
           byte ptext[] = readLine.getBytes(ISO_8859_1);
           String value = new String(ptext, UTF_8);
           System.out.println(value);
        }

    }
    catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

The problem is that it reads data from url but not encoded as utf8, the letters such as "ñ" are printed strangely.

Body:
Did you simply tried this ?

        String readLine;
        try {
            URL url = new URL("http://miurl/data.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

            while ((readLine = in.readLine()) != null) {
                System.out.println(readline);
            }

        }
        catch (IOException ex) {
            ex.printStackTrace();
        }

I tried this on this sample text from here
and it parses all UTF-8 characters quite okay.


问:
How to handle HttpServerErrorException?
I am currently using java and spring boot to get authorized in a API. It depends on the value that users inserts to see weather the api is valid or not.If it's valid it would basically display data.

Main Problem

When user enters wrong value in the end of the api. I get error 500 "internal server error" and it stops my spring application. I want to create an exception where it would catch this error and spits out that there's an error 500 rather than stopping my application. Even with wrong value I want my application to continue running.

Error

When users enter the wrong params I receive an error below

```<code> org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
</code>```

How can I override it, so that even if user enter wrong data, Don't break my application and continue running. Just display Null for data.

Attempt to handle

I was able to allow my application to continue running with following code below

```<code>try {  //OauthRestTemplate exhanges credentials for api access
 } catch (HttpServerErrorException e ) {
   e.getStatusCode();
   logger.info(e + "Server bypass, Continue running application");
    //allow application to continue running but does not display the actual message that would be on the api.
        }
  //output
   org.springframework.web.client.HttpServerErrorException: 500 Internal Server ErrorServer bypass, Continue running application
</code>```

But I want it to by pass the status 500 and display the actual message when I am on the api with wrong parameters. I should receive the same values that are printed on the api. Example Below

```<code>{"message":"Physical resource does not exist for mac address: D","code":"APRO-2001","timestamp":1490895756655,"type":"com.server.camp.framework.exception.ErrorResponse","status":"INTERNAL_SERVER_ERROR"}
</code>```

答:
I don't know if this applies to your problem (as you did not provide your code yet) but this might help:

```<code>@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
 public class OrderNotFoundException extends RuntimeException {
     // ...
 }
</code>```

You can basically add the @ResponseStatus to a function inside your class, set the value to the appropriate one (in your case INTERNAL_SERVER_ERROR as shown here).

I hope this helps! If not, please provide your code.

Maybe this link about Exception-Handling in spring might help: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Title: How to handle HttpServerErrorException?

Body:
I am currently using java and spring boot to get authorized in a API. It depends on the value that users inserts to see weather the api is valid or not.If it's valid it would basically display data.

Main Problem

When user enters wrong value in the end of the api. I get error 500 "internal server error" and it stops my spring application. I want to create an exception where it would catch this error and spits out that there's an error 500 rather than stopping my application. Even with wrong value I want my application to continue running.

Error

When users enter the wrong params I receive an error below

 org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error

How can I override it, so that even if user enter wrong data, Don't break my application and continue running. Just display Null for data.

Attempt to handle

I was able to allow my application to continue running with following code below

try {  //OauthRestTemplate exhanges credentials for api access
 } catch (HttpServerErrorException e ) {
   e.getStatusCode();
   logger.info(e + "Server bypass, Continue running application");
    //allow application to continue running but does not display the actual message that would be on the api.
        }
  //output
   org.springframework.web.client.HttpServerErrorException: 500 Internal Server ErrorServer bypass, Continue running application

But I want it to by pass the status 500 and display the actual message when I am on the api with wrong parameters. I should receive the same values that are printed on the api. Example Below

{"message":"Physical resource does not exist for mac address: D","code":"APRO-2001","timestamp":1490895756655,"type":"com.server.camp.framework.exception.ErrorResponse","status":"INTERNAL_SERVER_ERROR"}

Body:
I don't know if this applies to your problem (as you did not provide your code yet) but this might help:

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
 public class OrderNotFoundException extends RuntimeException {
     // ...
 }

You can basically add the @ResponseStatus to a function inside your class, set the value to the appropriate one (in your case INTERNAL_SERVER_ERROR as shown here).

I hope this helps! If not, please provide your code.

Maybe this link about Exception-Handling in spring might help: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc


问:
Pandas DataFrame multiplication with respect to MultiIndex
I want to multiplicate the following two DataFrames with respect to the MultiIndex foreach dimension of the second DataFrame

```<code>base = pd.DataFrame({'date':pd.date_range('2000-01-01', periods=3),
                    'id':[1,2,1],
                    'V1':[.3,.3,.1]}).set_index(['date','id'])
print (base)
                V1
date       id
2000-01-01 1   0.3
2000-01-01 2   0.1
2000-01-02 1   0.3
2000-01-02 2   0.1

ref = pd.DataFrame({'1':[1,2],'2':[1,2]}, index=[1,2])
ref.index.name = 'id'
print (ref)
    1  2
id
1   2  1
2   1  2
</code>```

And archive this:

```<code>                 V1
date       id
2000-01-01 1   (2*0.3 + 1*0.1)
2000-01-01 2   (2*0.1 + 1*0.3)
2000-01-01 1   (2*0.3 + 1*0.1)
2000-01-01 2   (2*0.1 + 1*0.3)
</code>```

I tried it with this code snipped (foreach id):

```<code>base.unstack(level='id').apply(lambda x: np.asarray(x) * np.asarray(ref.loc[??]), axis=1).stack().groupby(level='date').sum()
</code>```

答:
Since you want products and sums... I think dot product.

```<code>base.V1.unstack().dot(ref).stack()

date
2000-01-01  1    0.7
            2    0.5
2000-01-02  1    0.7
            2    0.5
dtype: float64
</code>```

setup

This provides the data the OP shows

```<code>base = pd.DataFrame(
    dict(V1=[.3, .1] * 2),
    pd.MultiIndex.from_product(
        [pd.to_datetime(['2000-01-01', '2000-01-02']), [1, 2]])
)

ref = pd.DataFrame({1:[2,1],2:[1,2]}, index=pd.Index([1, 2], name='id'))
</code>```

Body:
I want to multiplicate the following two DataFrames with respect to the MultiIndex foreach dimension of the second DataFrame

base = pd.DataFrame({'date':pd.date_range('2000-01-01', periods=3),
                    'id':[1,2,1],
                    'V1':[.3,.3,.1]}).set_index(['date','id'])
print (base)
                V1
date       id
2000-01-01 1   0.3
2000-01-01 2   0.1
2000-01-02 1   0.3
2000-01-02 2   0.1

ref = pd.DataFrame({'1':[1,2],'2':[1,2]}, index=[1,2])
ref.index.name = 'id'
print (ref)
    1  2
id
1   2  1
2   1  2

And archive this:

                 V1
date       id
2000-01-01 1   (2*0.3 + 1*0.1)
2000-01-01 2   (2*0.1 + 1*0.3)
2000-01-01 1   (2*0.3 + 1*0.1)
2000-01-01 2   (2*0.1 + 1*0.3)

I tried it with this code snipped (foreach id):

base.unstack(level='id').apply(lambda x: np.asarray(x) * np.asarray(ref.loc[??]), axis=1).stack().groupby(level='date').sum()

Body:
Since you want products and sums... I think dot product.

base.V1.unstack().dot(ref).stack()

date
2000-01-01  1    0.7
            2    0.5
2000-01-02  1    0.7
            2    0.5
dtype: float64

setup

This provides the data the OP shows

base = pd.DataFrame(
    dict(V1=[.3, .1] * 2),
    pd.MultiIndex.from_product(
        [pd.to_datetime(['2000-01-01', '2000-01-02']), [1, 2]])
)

ref = pd.DataFrame({1:[2,1],2:[1,2]}, index=pd.Index([1, 2], name='id'))


问:
Reducing repeated information in database design
I am designing an application that when users create a new account, their account is populated with several hundred rows of data (predefined options, settings, etc). Most of the users will rarely, if ever, change the information contained in these tables. Are there any good design patterns to reduce the amount of duplicated data in the database tables?

Some ideas I had so far:

Keep the predefined options in their
own tables, and only save custom
options to the user tables. This
would seem to reduce the overhead,
but I can see the database calls
getting really tricky.

Create a new
database for every 100 users or so,
with a separate database for accounts
that points to the users database.
This is, well, not optimal.

Idea 3?

答:
NO, dont create a new Database per any number of users.

Stick to option 1.

Or even setup UserGroups with selected options activated/rules applied.

UserRoles/Rules can get tricky, but you dont want to shoot yourself in the foot by maintaining multiple tables/databases for new users.

You need to implement a Users to UserGroups to UserRoles and UserRules

Also, If you ever see duplicated values per row, you need to look at Database normalization


问:
How to connect to a Gmail inbox
I am currently trying to connect to a gmail inbox using Perl and
Net::IMAP::Client
with the following code

```<code>use strict;
use warnings;

use Net::IMAP::Client;

my $user = '[address]@gmail.com';
my $pwd = '[password]';

my $imap = Net::IMAP::Client->new(
    server          => 'imap.gmail.com',
    user            => $user,
    pass            => $pwd,
    ssl             => 1,                     # (use SSL? default no)
    ssl_verify_peer => 0,                     # (use ca to verify server, default yes)
    port            => 993                    # (but defaults are sane)
) or die "Could not connect to IMAP server: $_";

$imap->login or
  die('Login failed: ' . $imap->last_error)
</code>```

But the $imap variable is undef and I am getting this error:

Use of uninitialized value $_ in concatenation (.) or string at testIMAP.pl line 9.

  Could not connect to IMAP server:  at testIMAP.pl line 9.

I have successfully connected to the mailbox using Outlook, but as I'm not getting an error message I'm not sure where to look. Does anyone know what I'm doing wrong here?

答:
A big thanks to zdim for help troubleshooting.

Firstly, zdim pointed out that I had the incorrect error variable. $_ should have been $!

This revealed the error message "Network is unreachable", however I was able to pint and telnet to 'imap.gmail.com' successfully.

The solution to this was found here
Perl IO::Socket::SSL: connect: Network is unreachable .

Changing the use statement in the Net::IMAP::Client module to the following worked:

```<code>use IO::Socket::SSL 'inet4';
</code>```

After this, the connection was established, but the login would fail with

```<code>Login failed: [ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)
</code>```

This is due to Gmail's security features. I received an email that allowed me to confirm that the connection was not malicious, and then subsequent logins were successful.

For others, there may be a few solutions to this last one. You may need to issue an 'app password' If two-step authentication is activated, or you might need to toggle on 'allow less secure apps'

Title: How to connect to a Gmail inbox

Body:
I am currently trying to connect to a gmail inbox using Perl and
Net::IMAP::Client
with the following code

use strict;
use warnings;

use Net::IMAP::Client;

my $user = '[address]@gmail.com';
my $pwd = '[password]';

my $imap = Net::IMAP::Client->new(
    server          => 'imap.gmail.com',
    user            => $user,
    pass            => $pwd,
    ssl             => 1,                     # (use SSL? default no)
    ssl_verify_peer => 0,                     # (use ca to verify server, default yes)
    port            => 993                    # (but defaults are sane)
) or die "Could not connect to IMAP server: $_";

$imap->login or
  die('Login failed: ' . $imap->last_error)

But the $imap variable is undef and I am getting this error:

Use of uninitialized value $_ in concatenation (.) or string at testIMAP.pl line 9.

  Could not connect to IMAP server:  at testIMAP.pl line 9.

I have successfully connected to the mailbox using Outlook, but as I'm not getting an error message I'm not sure where to look. Does anyone know what I'm doing wrong here?

Body:
A big thanks to zdim for help troubleshooting.

Firstly, zdim pointed out that I had the incorrect error variable. $_ should have been $!

This revealed the error message "Network is unreachable", however I was able to pint and telnet to 'imap.gmail.com' successfully.

The solution to this was found here
Perl IO::Socket::SSL: connect: Network is unreachable .

Changing the use statement in the Net::IMAP::Client module to the following worked:

use IO::Socket::SSL 'inet4';

After this, the connection was established, but the login would fail with

Login failed: [ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)

This is due to Gmail's security features. I received an email that allowed me to confirm that the connection was not malicious, and then subsequent logins were successful.

For others, there may be a few solutions to this last one. You may need to issue an 'app password' If two-step authentication is activated, or you might need to toggle on 'allow less secure apps'


问:
How is the linking done for string functions in C?
I tried to using two different functions from sting.h header file (without including it) strlen() and strtok(). Strlen executed successfully without any error (but some warnings), strtok failed at runtime. Why is it that strlen() function worknig gine but not strtok() if I don't include the header file? I suppose there is something in the linking process that I don't understand. Please clarify for such behavior. However, the program terminates successfully if I print a as '%c' instead of '%s' (strtok returns a garbage value).

CODE:

```<code>int main()
{
    char string[] = "This is a String";
    printf("\nLength of sting is %d\n",strlen(string));
}
</code>```

WARNINGS:
hello.c: In function ‘main’:
hello.c:4:2: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
hello.c:4:37: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default]
hello.c:4:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]

OUTPUT:
$ ./a.out

```<code>Length of sting is 16
</code>```

CODE:

```<code>int main()
{
    char string[] = "This is a String";
    printf("\nLength of sting is %d\n",strlen(string));
    char *a = strtok(string," ");
    printf("%s",a);
}
</code>```

WARNINGS:
$ gcc hello.c
hello.c: In function ‘main’:
hello.c:4:2: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
hello.c:4:37: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default]
hello.c:4:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]
hello.c:5:12: warning: initialization makes pointer from integer without a cast [enabled by default]

OUTPUT:
$ ./a.out

```<code>Length of sting is 16
Segmentation fault (core dumped)
</code>```

答:
The linking is done implicitly for most of the C standard library. You just have to include the headers of what you use (that's the warnings).

When you don't, your compiler (which is compiling your code as ANSI C) assumes the functions return int, instead of their documented return types. Your program has undefined behavior because of that. Always heed warnings!

You must include the headers string.h and stdio.h.

The first program works because you were lucky enough in that strlen is supposed to return an integer (a size_t to be exact, but it appears on your system the value representation for integers and size_t lets the program slide through).

The second fails because strtok returns a char* but it's assumed an int due to your missing include directives. int and char* are not compatible types, so the "pointer" you get isn't valid.

Body:
I tried to using two different functions from sting.h header file (without including it) strlen() and strtok(). Strlen executed successfully without any error (but some warnings), strtok failed at runtime. Why is it that strlen() function worknig gine but not strtok() if I don't include the header file? I suppose there is something in the linking process that I don't understand. Please clarify for such behavior. However, the program terminates successfully if I print a as '%c' instead of '%s' (strtok returns a garbage value).

CODE:

int main()
{
    char string[] = "This is a String";
    printf("\nLength of sting is %d\n",strlen(string));
}

WARNINGS:
hello.c: In function ‘main’:
hello.c:4:2: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
hello.c:4:37: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default]
hello.c:4:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]

OUTPUT:
$ ./a.out

Length of sting is 16

CODE:

int main()
{
    char string[] = "This is a String";
    printf("\nLength of sting is %d\n",strlen(string));
    char *a = strtok(string," ");
    printf("%s",a);
}

WARNINGS:
$ gcc hello.c
hello.c: In function ‘main’:
hello.c:4:2: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
hello.c:4:37: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default]
hello.c:4:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]
hello.c:5:12: warning: initialization makes pointer from integer without a cast [enabled by default]

OUTPUT:
$ ./a.out

Length of sting is 16
Segmentation fault (core dumped)


问:
Passing two values in select dropdown using angularjs
I want to pass two values in select dropdown.
Here is my code.

```<code><tbody>
    <tr ng-repeat="x in studyTeamObj" align="center">
        <td>
            <select class="form-control" ng-model="x.Designation">
                <option value=""></option>
                <option ng-repeat="x in createStudyObj.Study_User"
                        value="{{x.Designation}}">{{x.Emp_Name}}
                </option>
            </select>
        </td>
        <td>
            {{x.Emp_Id}}
        </td>
        <td>
            {{x.Designation}}
        </td>
        <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
        </td>
    </tr>
</tbody>
</code>```

This is what the data I am getting from {{createStudyObj.Study_User}}

```<code>[{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]
</code>```

when I click on emp name from the dropdown,it should fetch Emp_Id and Designation.But I am getting only the Designation.Plz help

答:
Assign object to value instead of one property. That's way whole object bind to ng-model and you can filter relevant properties from that.

```<code><option ng-repeat="x in createStudyObj.Study_User"value="{{x}}">{{x.Emp_Name}}
</option>
</code>```

The downfall of this is when u access the model variable from the controller value assign as string. so you need to parse the value to object using JSON.parse()

$scope.designation = JSON.parse($scope.designation)

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.createStudyObj = {};
 $scope.createStudyObj.Study_User = [{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <table>
   <tbody>
      <tr >
         <td>
            <select class="form-control" ng-model="designation">
               <option value=""></option>
               <option ng-repeat="x in createStudyObj.Study_User"
                  value="{{x}}">{{x.Emp_Name}}
               </option>
            </select>
         </td>
         <td>
            {{designation}}
         </td>
         <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
         </td>
      </tr>
   </tbody>
</table>
</div></code>```

But I recommend to use ng-options instead of the ng-repeat

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.createStudyObj = {};
 $scope.createStudyObj.Study_User = [{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <table>
   <tbody>
      <tr >
         <td>
            <select class="form-control" ng-model="designation" ng-options="item as item.Emp_Name for item in createStudyObj.Study_User">
               <option value=""></option>

            </select>
         </td>
         <td>
            {{designation}}
         </td>
         <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
         </td>
      </tr>
   </tbody>
</table>
</div></code>```

Body:
I want to pass two values in select dropdown.
Here is my code.

            <select class="form-control" ng-model="x.Designation">
                <option value=""></option>
                <option ng-repeat="x in createStudyObj.Study_User"
                        value="{{x.Designation}}">{{x.Emp_Name}}
                </option>
            </select>

            {{x.Emp_Id}}

            {{x.Designation}}

This is what the data I am getting from {{createStudyObj.Study_User}}

[{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

when I click on emp name from the dropdown,it should fetch Emp_Id and Designation.But I am getting only the Designation.Plz help

Body:
Assign object to value instead of one property. That's way whole object bind to ng-model and you can filter relevant properties from that.

<option ng-repeat="x in createStudyObj.Study_User"value="{{x}}">{{x.Emp_Name}}
</option>

The downfall of this is when u access the model variable from the controller value assign as string. so you need to parse the value to object using JSON.parse()

$scope.designation = JSON.parse($scope.designation)

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.createStudyObj = {};
 $scope.createStudyObj.Study_User = [{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <table>
   <tbody>
      <tr >
         <td>
            <select class="form-control" ng-model="designation">
               <option value=""></option>
               <option ng-repeat="x in createStudyObj.Study_User"
                  value="{{x}}">{{x.Emp_Name}}
               </option>
            </select>
         </td>
         <td>
            {{designation}}
         </td>
         <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
         </td>
      </tr>
   </tbody>
</table>
</div>

But I recommend to use ng-options instead of the ng-repeat

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.createStudyObj = {};
 $scope.createStudyObj.Study_User = [{"Emp_Name":"mdrf","Emp_Id":2,"Designation":"Research Dietitian","DesignationID":20},{"Emp_Name":"Sudha","Emp_Id":1045,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1046,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1047,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1048,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"kavyad","Emp_Id":1049,"Designation":"MDRF HOD","DesignationID":16},{"Emp_Name":"fdgedd","Emp_Id":1050,"Designation":"MDRF HOD","DesignationID":16}]

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <table>
   <tbody>
      <tr >
         <td>
            <select class="form-control" ng-model="designation" ng-options="item as item.Emp_Name for item in createStudyObj.Study_User">
               <option value=""></option>

            </select>
         </td>
         <td>
            {{designation}}
         </td>
         <td class="mdrf-add-row-col">
            <i class="fa  fa-minus-circle"
               data-ng-click="deleteMem($index)"></i>
         </td>
      </tr>
   </tbody>
</table>
</div>


问:
JS Equivalent of Linking to a Font File
I have used css to link to font files in the conventional way, as seen here:

How can I use Google's Roboto font on a website?

However there are a few instances where I may need more complicated style rules, and I use javascript in such cases. Strangely google searches only returned css font link methods, but I'm suspecting js has a way. I got as far as:

```<code>d3.select('body').append('text').text('my text')
    .attr('font-family', 'Roboto')
    .attr('src', 'url(my_url) format('truetype')');
</code>```

However I'm not sure if it's supposed to look like that. Given that it's not working, my hunch is no. Any ideas?

答:
As long as your referencing your google font in your document like the following:

```<code><link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
</code>```

All you have to do is specify the name when selecting font-family to apply it to any text element:

```<code>d3.select('body').append('text').text('my text')
    .style('font-family', "'Montserrat', sans-serif");
</code>```

Fiddle - https://jsfiddle.net/7jLgpx68/

# For .ttf files, I would suggest setting it in css first like the following:

```<code>@font-face {
  font-family: "Super Sans";
  src: url(#url_to_ttf);
}
</code>```

and then using it in your js code like

```<code>d3.select('body').append('text').text('my text')
    .style('font-family', "Super Sans");
</code>```

Title: JS Equivalent of Linking to a Font File

Body:
I have used css to link to font files in the conventional way, as seen here:

How can I use Google's Roboto font on a website?

However there are a few instances where I may need more complicated style rules, and I use javascript in such cases. Strangely google searches only returned css font link methods, but I'm suspecting js has a way. I got as far as:

d3.select('body').append('text').text('my text')
    .attr('font-family', 'Roboto')
    .attr('src', 'url(my_url) format('truetype')');

However I'm not sure if it's supposed to look like that. Given that it's not working, my hunch is no. Any ideas?

Body:
As long as your referencing your google font in your document like the following:

<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

All you have to do is specify the name when selecting font-family to apply it to any text element:

d3.select('body').append('text').text('my text')
    .style('font-family', "'Montserrat', sans-serif");

Fiddle - https://jsfiddle.net/7jLgpx68/

# For .ttf files, I would suggest setting it in css first like the following:

@font-face {
  font-family: "Super Sans";
  src: url(#url_to_ttf);
}

and then using it in your js code like

d3.select('body').append('text').text('my text')
    .style('font-family', "Super Sans");


答: It really depends on how many tables are being populated by user options, but if the great majority of the time, the user options are just the same, default value, then you could just put them in their own tables, and just use views to make pulling the data out seamless.  (so option 1)</p>

Title: Reducing repeated information in database design

Body:
I am designing an application that when users create a new account, their account is populated with several hundred rows of data (predefined options, settings, etc). Most of the users will rarely, if ever, change the information contained in these tables. Are there any good design patterns to reduce the amount of duplicated data in the database tables?

Some ideas I had so far:

Keep the predefined options in their
own tables, and only save custom
options to the user tables. This
would seem to reduce the overhead,
but I can see the database calls
getting really tricky.

Create a new
database for every 100 users or so,
with a separate database for accounts
that points to the users database.
This is, well, not optimal.

Idea 3?


问:
How to parse json when collectionView is tap
Hello I'm just wondering if there is another way to parse json data when a collection view is click and pass it to another view. This is the API im using. This is how I do it at the moment. This is how my class looks. First I create a closure. Then I created my hero class. Then I have my json parse function.

This is how my collectionView didSelectItemAt func looks. This is where im trying to put my json parse function, or is it better to put it in the hero class. Im new to this so I don't really know.

Not sure if I explained it well. So I'll include my viewcontroller code if needed. Would appreciate any help :)

答: You should create variable for another viewcontroller and pass the data to that variable by using didselect method</p>


问:
how to Show/Hide button C# ASP.Net <No Panel>
I have below code

```<code><div class="modal‐footer">
<div class="row">
  <div class="col-md-6" runat="server" id="d1">
    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
  </div>
  <div class="col-md-6" runat="server" id="d2">
    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />
  </div>
  <div class="col-md-6" runat="server" id="d3">
    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />
  </div>
  <div class="col-md-6" runat="server" id="d4">
    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />
  </div>
</div>
</div>
</code>```

I need to show only Update Button, under condition. Example,

```<code>if a=="Pending"; only UpdateBtn will be shown.
</code>```

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

```<code>namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }
</code>```

答:
This is very simple. Make sure you declare 'a' as a public variable in the code behind and use the code like below. sorry for the formatting..

```<code><%
    if (a== 1)
    { %>
  <div class="col-md-6" runat="server" id="d1">
<asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
</code>```

```<code><%} %><div class="col-md-6" runat="server" id="d2">
<asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />
</code>```

EDIT

Code behind

```<code>public partial class _default : System.Web.UI.Page
{
    public string rfcStatus;

    protected void Page_Load (object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            rfcStatus = "1";
        }

    }
}
</code>```

Mark up

```<code><div class="modal‐footer">
<div class="row">
<%
    if (!string.IsNullOrEmpty(rfcStatus))
    {
        if (rfcStatus== "1")
        { %>
        <div class="col-md-6" runat="server" id="d1">
        <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
        </div>
        <%
        }
    } %>
</code>```

Body:
I have below code

    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />

    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />

    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />

    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />

I need to show only Update Button, under condition. Example,

if a=="Pending"; only UpdateBtn will be shown.

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }

Body:
This is very simple. Make sure you declare 'a' as a public variable in the code behind and use the code like below. sorry for the formatting..

<%
    if (a== 1)
    { %>
  <div class="col-md-6" runat="server" id="d1">
<asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />

<%} %><div class="col-md-6" runat="server" id="d2">
<asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />

EDIT

Code behind

public partial class _default : System.Web.UI.Page
{
    public string rfcStatus;

    protected void Page_Load (object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            rfcStatus = "1";
        }

    }
}

Mark up

<div class="modal‐footer">
<div class="row">
<%
    if (!string.IsNullOrEmpty(rfcStatus))
    {
        if (rfcStatus== "1")
        { %>
        <div class="col-md-6" runat="server" id="d1">
        <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
        </div>
        <%
        }
    } %>


问:
State of the art webpack / React configuration
I'm trying to setup a webpack 2, babel, and React configuration for achieving:

Native ES6/ES7 features

Tree shaking builds

Hot reloading

I had a demo repo but it has distinct stuff mixed, like even JSHint and ESLint at the same time.

I'd like to get my setup up and running and get suggestions for best practices

So, as first option I tried to use babel-preset-env. Then after some dependencies being installed. I ran into this issue:

ERROR in ./src/main.jsx
Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level (3:0)

However, the first line in my code is import 'babel-polyfill'; then just import's.

This is how my Babel config file looks like:

```<code>{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": ["last 2 versions"]
        }
      }
    ],
    "react"
  ],
  "plugins": [
    "babel-plugin-transform-class-properties",
    "transform-react-require"
  ]
}
</code>```

This is what my development webpack config file looks like:

```<code>const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const config = {
    //Entry points to the project
    entry: [
        'babel-polyfill',
        'webpack/hot/dev-server',
        'webpack/hot/only-dev-server',
        path.join(__dirname, '../src/main.jsx')
    ],
    //Config options on how to interpret requires imports
    resolve: {
        extensions: [".js", ".jsx"]
    },
    //Server Configuration options
    devServer:{
        contentBase: 'build',  //Relative directory for base of server
        devtool: 'eval',
        hot: true,        //Live-reload
        inline: true,
        port: 3000,        //Port Number
        host: 'localhost', //Change to '0.0.0.0' for external facing server
        proxy: {
            '^\/api': {
                target: 'http://127.0.0.1:9090'
            }
        },
        historyApiFallback: true
    },
    devtool: 'eval',
    output: {
        path: buildPath,    //Path of output file
        filename: 'app.js'
    },
    plugins: [
        new webpack.DefinePlugin({
            API_BASE: '""',
            PRODUCTION: false,
            'process.env.NODE_ENV': '"development"'
        }),
        //Enables Hot Modules Replacement
        new webpack.HotModuleReplacementPlugin(),
        //Allows error warnings but does not stop compiling. Will remove when eslint is added
        new webpack.NoEmitOnErrorsPlugin(),
        //Moves files
        new TransferWebpackPlugin([
            {from: 'www'}
        ], path.resolve(__dirname, "src")),
        new ExtractTextPlugin("main.css")
    ],
    module: {
        rules: [
            {
                //React-hot loader and
                test: /\.(js|jsx)$/,  //All .js and .jsx files
                loaders: [ 'babel-loader', 'react-hot-loader'],
                //react-hot is like browser sync and babel loads jsx and es6-7
                exclude: [nodeModulesPath]
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style',
                    use: 'css'
                })
            },
            {
                test: /\.svg$/,
                loader: 'svg-sprite?' + JSON.stringify({
                    name: '[name]_[hash]',
                    prefixize: true
                })
            }
        ]
    }
};

module.exports = config;
</code>```

And this below is package.json

```<code>{
  "name": "LumaHealth",
  "version": "1.0.0",
  "description": "LumaHealth",
  "main": "start.js",
  "scripts": {
    "start": "webpack --config ./webpack/webpack.config.development.js",
    "build": "webpack --config ./webpack/webpack.config.production.js",
    "clean": "rm build/app.js"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:lumahealthhq/web-app.git"
  },
  "keywords": [],
  "author": "Marcelo Oliveira",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-eslint": "^7.2.1",
    "babel-plugin-react-require": "^3.0.0",
    "babel-plugin-transform-class-properties": "^6.23.0",
    "babel-preset-env": "^1.2.2",
    "babel-preset-react": "^6.23.0",
    "css-loader": "^0.26.4",
    "enzyme": "^2.0.0",
    "eslint": "^3.7.1",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-loader": "^1.7.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.4.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "html-webpack-plugin": "^2.28.0",
    "nyc": "^10.1.2",
    "postcss-loader": "^1.3.3",
    "postcss-nested": "^1.0.0",
    "react-addons-test-utils": "^15.4.1",
    "sinon": "^1.17.2",
    "style-loader": "^0.13.2",
    "sw-precache": "^5.0.0",
    "transfer-webpack-plugin": "^0.1.4",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "dependencies": {
    "babel-core": "^6.5.2",
    "babel-eslint": "^7.0.0",
    "babel-plugin-transform-react-require": "^1.0.1",
    "babel-polyfill": "^6.23.0",
    "co": "^4.6.0",
    "express": "^4.12.3",
    "file-loader": "^0.10.1",
    "humps": "^2.0.0",
    "isomorphic-fetch": "^2.2.1",
    "local-storage": "^1.4.2",
    "lodash": "^4.16.4",
    "material-ui": "^0.17.0",
    "moment": "^2.15.2",
    "q": "^1.4.1",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.3",
    "react-router": "^3.0.2",
    "react-router-redux": "^4.0.6",
    "react-slick": "^0.14.4",
    "react-tap-event-plugin": "^2.0.0",
    "react-web-notification": "^0.2.3",
    "redux": "^3.6.0",
    "redux-form": "^6.1.1",
    "redux-logger": "^2.7.0",
    "redux-socket.io": "^1.3.1",
    "redux-thunk": "^2.1.0",
    "socket.io-client": "^1.7.2",
    "url-loader": "^0.5.7",
    "vanilla-masker": "^1.0.9"
  }
}
</code>```

答:
I recently upgraded my boilerplate from webpack 1 to webpack 2, feel free to get any information / concept from the webpack config file there, hope it helps.

https://github.com/iroy2000/react-redux-boilerplate

Body:
I'm trying to setup a webpack 2, babel, and React configuration for achieving:

Native ES6/ES7 features

Tree shaking builds

Hot reloading

I had a demo repo but it has distinct stuff mixed, like even JSHint and ESLint at the same time.

I'd like to get my setup up and running and get suggestions for best practices

So, as first option I tried to use babel-preset-env. Then after some dependencies being installed. I ran into this issue:

ERROR in ./src/main.jsx
Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level (3:0)

However, the first line in my code is import 'babel-polyfill'; then just import's.

This is how my Babel config file looks like:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": ["last 2 versions"]
        }
      }
    ],
    "react"
  ],
  "plugins": [
    "babel-plugin-transform-class-properties",
    "transform-react-require"
  ]
}

This is what my development webpack config file looks like:

const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const config = {
    //Entry points to the project
    entry: [
        'babel-polyfill',
        'webpack/hot/dev-server',
        'webpack/hot/only-dev-server',
        path.join(__dirname, '../src/main.jsx')
    ],
    //Config options on how to interpret requires imports
    resolve: {
        extensions: [".js", ".jsx"]
    },
    //Server Configuration options
    devServer:{
        contentBase: 'build',  //Relative directory for base of server
        devtool: 'eval',
        hot: true,        //Live-reload
        inline: true,
        port: 3000,        //Port Number
        host: 'localhost', //Change to '0.0.0.0' for external facing server
        proxy: {
            '^\/api': {
                target: 'http://127.0.0.1:9090'
            }
        },
        historyApiFallback: true
    },
    devtool: 'eval',
    output: {
        path: buildPath,    //Path of output file
        filename: 'app.js'
    },
    plugins: [
        new webpack.DefinePlugin({
            API_BASE: '""',
            PRODUCTION: false,
            'process.env.NODE_ENV': '"development"'
        }),
        //Enables Hot Modules Replacement
        new webpack.HotModuleReplacementPlugin(),
        //Allows error warnings but does not stop compiling. Will remove when eslint is added
        new webpack.NoEmitOnErrorsPlugin(),
        //Moves files
        new TransferWebpackPlugin([
            {from: 'www'}
        ], path.resolve(__dirname, "src")),
        new ExtractTextPlugin("main.css")
    ],
    module: {
        rules: [
            {
                //React-hot loader and
                test: /\.(js|jsx)$/,  //All .js and .jsx files
                loaders: [ 'babel-loader', 'react-hot-loader'],
                //react-hot is like browser sync and babel loads jsx and es6-7
                exclude: [nodeModulesPath]
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style',
                    use: 'css'
                })
            },
            {
                test: /\.svg$/,
                loader: 'svg-sprite?' + JSON.stringify({
                    name: '[name]_[hash]',
                    prefixize: true
                })
            }
        ]
    }
};

module.exports = config;

And this below is package.json

{
  "name": "LumaHealth",
  "version": "1.0.0",
  "description": "LumaHealth",
  "main": "start.js",
  "scripts": {
    "start": "webpack --config ./webpack/webpack.config.development.js",
    "build": "webpack --config ./webpack/webpack.config.production.js",
    "clean": "rm build/app.js"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:lumahealthhq/web-app.git"
  },
  "keywords": [],
  "author": "Marcelo Oliveira",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-eslint": "^7.2.1",
    "babel-plugin-react-require": "^3.0.0",
    "babel-plugin-transform-class-properties": "^6.23.0",
    "babel-preset-env": "^1.2.2",
    "babel-preset-react": "^6.23.0",
    "css-loader": "^0.26.4",
    "enzyme": "^2.0.0",
    "eslint": "^3.7.1",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-loader": "^1.7.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.4.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "html-webpack-plugin": "^2.28.0",
    "nyc": "^10.1.2",
    "postcss-loader": "^1.3.3",
    "postcss-nested": "^1.0.0",
    "react-addons-test-utils": "^15.4.1",
    "sinon": "^1.17.2",
    "style-loader": "^0.13.2",
    "sw-precache": "^5.0.0",
    "transfer-webpack-plugin": "^0.1.4",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "dependencies": {
    "babel-core": "^6.5.2",
    "babel-eslint": "^7.0.0",
    "babel-plugin-transform-react-require": "^1.0.1",
    "babel-polyfill": "^6.23.0",
    "co": "^4.6.0",
    "express": "^4.12.3",
    "file-loader": "^0.10.1",
    "humps": "^2.0.0",
    "isomorphic-fetch": "^2.2.1",
    "local-storage": "^1.4.2",
    "lodash": "^4.16.4",
    "material-ui": "^0.17.0",
    "moment": "^2.15.2",
    "q": "^1.4.1",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.3",
    "react-router": "^3.0.2",
    "react-router-redux": "^4.0.6",
    "react-slick": "^0.14.4",
    "react-tap-event-plugin": "^2.0.0",
    "react-web-notification": "^0.2.3",
    "redux": "^3.6.0",
    "redux-form": "^6.1.1",
    "redux-logger": "^2.7.0",
    "redux-socket.io": "^1.3.1",
    "redux-thunk": "^2.1.0",
    "socket.io-client": "^1.7.2",
    "url-loader": "^0.5.7",
    "vanilla-masker": "^1.0.9"
  }
}


问:
In VLOOKUP, if I get an error, I want to do another search using a different search value
I have several similar, but not exact, names in a worksheet in subsequent rows. They all refer to the same "item". In creating a VLOOKUP, if I receive an error I want to do another VLOOKUP using an different, similar value across the same table array. I'm using

```<code>=IFERROR(VLOOKUP(B1,Sheet1!A:AZ,2,FALSE),VLOOKUP(C1,Sheet1!A:AZ,2,FALSE))
</code>```

I've tried many variations without any luck.

答:
Your formula has the correct format to try finding B1 in column A of Sheet1 and, if it can't find anything, then try finding C1 in column A of Sheet1 instead. If it can't find C1 either, then it will still return an error.

If you have a value in B1 or C1 that you expect to be found in column A of Sheet1 but the formula is returning an error, you'll need to check some common vlookup issues:

The value isn't an exact match (even an extra space will cause a mismatch)

The value of B1 or C1 is being found, but the vlookup value from column B in Sheet1 has an error value and it's actually that error value being returned (rather than being any issue with the vlookup itself)

The value your searching for isn't in column A. (If you're only looking up the 2nd column in the lookup range, i.e. Column B, why do you include all columns from A to AZ in the lookup table? Are you sure your lookup value is in column A of Sheet1?)

A number is stored as text in one location but not the other.

Also, if it helps, note that you can use wildcards in Vlookups as well. The following is a valid formula to find the first row that has the word "test" anywhere in Column A of Sheet1:

```<code>=VLOOKUP("*test*",Sheet1!A:B:,2,0)
</code>```

Body:
I have several similar, but not exact, names in a worksheet in subsequent rows. They all refer to the same "item". In creating a VLOOKUP, if I receive an error I want to do another VLOOKUP using an different, similar value across the same table array. I'm using

=IFERROR(VLOOKUP(B1,Sheet1!A:AZ,2,FALSE),VLOOKUP(C1,Sheet1!A:AZ,2,FALSE))

I've tried many variations without any luck.

Body:
Your formula has the correct format to try finding B1 in column A of Sheet1 and, if it can't find anything, then try finding C1 in column A of Sheet1 instead. If it can't find C1 either, then it will still return an error.

If you have a value in B1 or C1 that you expect to be found in column A of Sheet1 but the formula is returning an error, you'll need to check some common vlookup issues:

The value isn't an exact match (even an extra space will cause a mismatch)

The value of B1 or C1 is being found, but the vlookup value from column B in Sheet1 has an error value and it's actually that error value being returned (rather than being any issue with the vlookup itself)

The value your searching for isn't in column A. (If you're only looking up the 2nd column in the lookup range, i.e. Column B, why do you include all columns from A to AZ in the lookup table? Are you sure your lookup value is in column A of Sheet1?)

A number is stored as text in one location but not the other.

Also, if it helps, note that you can use wildcards in Vlookups as well. The following is a valid formula to find the first row that has the word "test" anywhere in Column A of Sheet1:

=VLOOKUP("*test*",Sheet1!A:B:,2,0)


答:
Sting is a singer, not a C header... Still, the problem is that in C, when you use functions that were not declared, the compiler guesses them to have the types of the arguments you first pass to them and returning an int.

That's the reason why you get all these warnings: several undeclared functions you use don't actually have the deduced signature (although they are not too wrong, and end up working), and the real strtok returns a pointer, not an int (the warning in facts says that you are assigning an int to a pointer without a cast). The crash you are getting most probably comes from the fact that the original pointer is 64 bit, but is truncated to 32 bit when is erroneously considered an int before being assigned to a.

Still, the point to take home is: include headers and don't ever rely on implicit function declaration. It's a dangerous mess that exists only for backward compatibility reasons.

Title: How is the linking done for string functions in C?


答:
you save the urls to an array and then pick an index with a random function between 0-9 and your done

function:

```<code>var rand_no = Math.ceil(10*Math.random())
</code>```

array

```<code>var image=new Array();
image[0]="image.jpg";
image[1]="image.jpg";
image[2]="image.jpg";
</code>```

etc

```<code>alert(image[rand_no]);
</code>```

Title: Very simple Javascript ad placement engine

Body: I have ten different banner ads uploaded on my site. I want to make a Javascript program that will randomly show one each time a page is loaded. How would I do this?

Body:
you save the urls to an array and then pick an index with a random function between 0-9 and your done

function:

var rand_no = Math.ceil(10*Math.random())

array

var image=new Array();
image[0]="image.jpg";
image[1]="image.jpg";
image[2]="image.jpg";

etc

alert(image[rand_no]);


问:
How to format date from database in Yii2
If I have function like this

protected function getAreaValues($model)
 {
  return
  [
   [
    $model->getAttributeLabel('EXPDATE'),TbArea::findOne($model->KODE)->EXPDATE
   ],

  ];
 }```
</div>
</div>
</p>

<p>where EXPDATE IS date data</p>

<p>How to format it in d-M-Y ?</p>

<p>I add formatter in web.php in config like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  'formatter' => [
   'class' => 'yii\i18n\Formatter',
   'nullDisplay' => '-',
   'dateFormat' => 'd-M-Y',
   'datetimeFormat' => 'd-M-Y H:i:s',
   'timeFormat' => 'H:i:s',
  ],</code>```

But still not working

答:
You can format date like below.

```<code>echo Yii::$app->formatter->asDate('2017-03-30', 'd-M-Y'); // 30-Mar-2017
</code>```

try this.

and you can check Yii2 doc

Yii2 Formatters

Body:
If I have function like this

protected function getAreaValues($model)
 {
  return
  [
   [
    $model->getAttributeLabel('EXPDATE'),TbArea::findOne($model->KODE)->EXPDATE
   ],

  ];
 }

where EXPDATE IS date data

How to format it in d-M-Y ?

I add formatter in web.php in config like this

  'formatter' => [
   'class' => 'yii\i18n\Formatter',
   'nullDisplay' => '-',
   'dateFormat' => 'd-M-Y',
   'datetimeFormat' => 'd-M-Y H:i:s',
   'timeFormat' => 'H:i:s',
  ],

But still not working

Body:
You can format date like below.

echo Yii::$app->formatter->asDate('2017-03-30', 'd-M-Y'); // 30-Mar-2017

try this.

and you can check Yii2 doc

Yii2 Formatters


问:
cURL POST request to Node.js express server hosted on NGINX server returns a 502 error
I'm trying to make a POST request to one of my node api routes. I have several routes, but only one of them work. I'm not sure if this is a problem with NGINX or node or some combination. Everything looks right, I even enabled CORS! The node application is hosted on a DigitalOcean droplet.

cURL POST request: curl -H "Content-Type: application/json; charset=UTF-8" -i -X POST -d '{"text":"test reply from curl","_id":"123"}' "https://example.com/api/reply/test"

My nginx configuration:

```<code>    server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example/public;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;

    server_name example.com www.example.com;
    root /var/www/example/public;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;
    add_header Content-Security-Policy-Report-Only "default-src 'self'";
    location ~ /.well-know {
        allow all;
    }

    location / {
        proxy_pass http://localhost:3210;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    }

}
</code>```

my node.js express server:

```<code>"use strict";
var express = require('express');
var request = require('request');
var url = 'mongodb://localhost:27017/';
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express();
app.set('port', process.env.PORT || 3210);
app.set('host', process.env.HOST || '127.0.0.1');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())

app.use(express.static('./public'));

app.post('/api/reply/:board', (req,res) => {
  MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
  if(err) { return console.dir(err) }
  var collection = db.collection(req.params.board);
  var reply = {'text':req.params.text}
  collection.update(
   {"_id":ObjectId(req.params._id)},
   {$push:reply}
  )
  });
});

app.post('/api/post/:board', (req, res) => {
  MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
  if (err) {return console.dir(err);}
    console.log(req);
    var collection = db.collection(req.params.board);
    var post = {'text':req.body.text,'time':timestamp(),     'comments':[]}
    collection.insert(post);
    res.sendStatus(200);
  })
});

app.get('/api/posts/:board', (req,res)=> {
  MongoClient.connect(`${url}${req.params.board}`, (err,db) => {
   if(err) {return console.dir(err)}
   var collection = db.collection(req.params.board)
   collection.find().toArray( (err,posts) => {
    res.send({...posts})
   })
  })
});

app.listen(app.get('port'), app.get('host'), () => {
  console.log('express listening on port ' + app.get('port'));
});
</code>```

My cURL POST request to example.com/api/reply/test returns:

```<code>HTTP/1.1 502 Bad Gateway
Server: nginx/1.4.6 (Ubuntu)
Date: Thu, 30 Mar 2017 03:15:02 GMT
Content-Type: text/html
Content-Length: 181
Connection: keep-alive

<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>
</code>```

HOWEVER, my GET request to https://example.com/api/posts/test is successful as well as my POST request to https://example.com/api/post/test

Why is nginx refusing my other POST requests??

答:
There route defined for /api/reply/test does send back any response:

```<code>app.post('/api/reply/:board', (req, res) => {
    MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
        if (err) {
            return console.dir(err)
        }
        var collection = db.collection(req.params.board);
        var reply = {
            'text': req.params.text
        }
        collection.update({
            "_id": ObjectId(req.params._id)
        }, {
            $push: reply
        })
    });
});
</code>```

Probably you wish to add res.sendStatus(200); just after collection.update() ?

Body:
I'm trying to make a POST request to one of my node api routes. I have several routes, but only one of them work. I'm not sure if this is a problem with NGINX or node or some combination. Everything looks right, I even enabled CORS! The node application is hosted on a DigitalOcean droplet.

cURL POST request: curl -H "Content-Type: application/json; charset=UTF-8" -i -X POST -d '{"text":"test reply from curl","_id":"123"}' "https://example.com/api/reply/test"

My nginx configuration:

    server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example/public;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;

    server_name example.com www.example.com;
    root /var/www/example/public;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;
    add_header Content-Security-Policy-Report-Only "default-src 'self'";
    location ~ /.well-know {
        allow all;
    }

    location / {
        proxy_pass http://localhost:3210;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    }

}

my node.js express server:

"use strict";
var express = require('express');
var request = require('request');
var url = 'mongodb://localhost:27017/';
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express();
app.set('port', process.env.PORT || 3210);
app.set('host', process.env.HOST || '127.0.0.1');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())

app.use(express.static('./public'));

app.post('/api/reply/:board', (req,res) => {
  MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
  if(err) { return console.dir(err) }
  var collection = db.collection(req.params.board);
  var reply = {'text':req.params.text}
  collection.update(
   {"_id":ObjectId(req.params._id)},
   {$push:reply}
  )
  });
});

app.post('/api/post/:board', (req, res) => {
  MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
  if (err) {return console.dir(err);}
    console.log(req);
    var collection = db.collection(req.params.board);
    var post = {'text':req.body.text,'time':timestamp(),     'comments':[]}
    collection.insert(post);
    res.sendStatus(200);
  })
});

app.get('/api/posts/:board', (req,res)=> {
  MongoClient.connect(`${url}${req.params.board}`, (err,db) => {
   if(err) {return console.dir(err)}
   var collection = db.collection(req.params.board)
   collection.find().toArray( (err,posts) => {
    res.send({...posts})
   })
  })
});

app.listen(app.get('port'), app.get('host'), () => {
  console.log('express listening on port ' + app.get('port'));
});

My cURL POST request to example.com/api/reply/test returns:

HTTP/1.1 502 Bad Gateway
Server: nginx/1.4.6 (Ubuntu)
Date: Thu, 30 Mar 2017 03:15:02 GMT
Content-Type: text/html
Content-Length: 181
Connection: keep-alive

<title>502 Bad Gateway</title>

502 Bad Gateway

nginx/1.4.6 (Ubuntu)

HOWEVER, my GET request to https://example.com/api/posts/test is successful as well as my POST request to https://example.com/api/post/test

Why is nginx refusing my other POST requests??

Body:
There route defined for /api/reply/test does send back any response:

app.post('/api/reply/:board', (req, res) => {
    MongoClient.connect(`${url}${req.params.board}`, (err, db) => {
        if (err) {
            return console.dir(err)
        }
        var collection = db.collection(req.params.board);
        var reply = {
            'text': req.params.text
        }
        collection.update({
            "_id": ObjectId(req.params._id)
        }, {
            $push: reply
        })
    });
});

Probably you wish to add res.sendStatus(200); just after collection.update() ?


问:
Use gulp to select and move directories and their files
I'm currently using gulp to call a bash script that cleans my dist/ directory and moves the appropriate files to the clean directory. I would like this to be done with gulp because I am not sure the script would work on a non *nix file system.

So far, I'm using the gulp-clean module to clean the dist/ directory but when I try to move the required directories and their files to the dist folder, the directories are empty.

```<code>var gulp = require('gulp'),
    clean = require('gulp-clean');

gulp.task('clean', function(){
  return gulp.src(['dist/*'], {read:false})
  .pipe(clean());
});

gulp.task('move',['clean'], function(){
  gulp.src(['_locales', 'icons', 'src/page_action', 'manifest.json'])
  .pipe(gulp.dest('dist'));
});

gulp.task('dist', ['move']);
</code>```

calling gulp dist results in the the dist/ directory being populated with the correct directories but they are all empty

```<code>$ ls dist/*
dist/manifest.json

dist/_locales:

dist/icons:

dist/page_action:
</code>```

How do I copy the directories and their contents to the dist/ folder?

答:
The original question targets only directories  (a.k.a. folders) in its gulp.src, i.e. gulp.src(['_locales', ... in this example, _locales is the name of a directory.

The accepted answer uses a glob pattern  in its gulp.src to target files anywhere in those directories, i.e. gulp.src(['./_locales/**/*.*', ..., (notice the double-asterisks, and the filename.extension asterisks). The accepted answer works...

...but the accepted answer only emphasizes the base option:

You need to include the base option to src...

I experimented and found:

Strictly speaking, it is unnecessary to use the base option to achieve what the OP asked:  "...and moves the appropriate files to the clean directory." The base option does indeed preserve the folder+file structure (as described in the accepted answer), but the base option is not sufficient to move the files as the OP asked. Preserving the folder+file structure is probably what the OP expects, so the accepted answer is good, but...

Just to reiterate what does move the files, it's the glob patterns:

Double-asterisk (.../**/...) searches recursively throughout all subfolders, and subfolders' subfolders', etc.

Filename.extension asterisks (.../*.*) finds files of all names, and all extensions. So I think this part deserves the most emphasis!

The accepted answer changes something else; it adds a prefix of ./ to each path arguments passed to gulp.src. I think that's unnecessary/redundant; if there is no ./, (as in the OP question), the paths are resolved relative to the current directory -- resulting in the same behavior. But maybe it's good practice to be explicit with the ./

Let me know if I'm mistaken...

Body:
I'm currently using gulp to call a bash script that cleans my dist/ directory and moves the appropriate files to the clean directory. I would like this to be done with gulp because I am not sure the script would work on a non *nix file system.

So far, I'm using the gulp-clean module to clean the dist/ directory but when I try to move the required directories and their files to the dist folder, the directories are empty.

var gulp = require('gulp'),
    clean = require('gulp-clean');

gulp.task('clean', function(){
  return gulp.src(['dist/*'], {read:false})
  .pipe(clean());
});

gulp.task('move',['clean'], function(){
  gulp.src(['_locales', 'icons', 'src/page_action', 'manifest.json'])
  .pipe(gulp.dest('dist'));
});

gulp.task('dist', ['move']);

calling gulp dist results in the the dist/ directory being populated with the correct directories but they are all empty

$ ls dist/*
dist/manifest.json

dist/_locales:

dist/icons:

dist/page_action:

How do I copy the directories and their contents to the dist/ folder?


问:
Get the user ID in WooCommerce Subscriptions
I am using WooCommerce Subscriptions plugin and I am trying to get the customer or userid of a given wc_subscription.

Here is the code I have been using but fails:

```<code>add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
...
}
</code>```

I thought $wc_subscription->customer_user will have the userid but it is empty. In fact stops the code from continuing.

How can I get the user ID with $wc_subscription?

答:
Retrieve the current user object (WP_User).
Wrapper of get_currentuserinfo() using the global variable $current_user.

```<code>wp_get_current_user();
</code>```

But it may be deprecated so You can derived from

```<code>$userdata = WP_User::get_data_by( $field, $value );
</code>```

Body:
I am using WooCommerce Subscriptions plugin and I am trying to get the customer or userid of a given wc_subscription.

Here is the code I have been using but fails:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
...
}

I thought $wc_subscription->customer_user will have the userid but it is empty. In fact stops the code from continuing.

How can I get the user ID with $wc_subscription?

Body:
Retrieve the current user object (WP_User).
Wrapper of get_currentuserinfo() using the global variable $current_user.

wp_get_current_user();

But it may be deprecated so You can derived from

$userdata = WP_User::get_data_by( $field, $value );