问:
Spring Boot OAuth2 Single Sign Off (Logout)
I'm considering to use OAuth2 for my application. The architecture I'm trying to implement is as follows:

I will have my own (and only this) Authorization Server

Some Resource Apps validating access to their resources using the Authorization Server

Some client apps (web, mobile) which will redirect the user to the Authorization Server for authentication and on success will consume the api's on the Resource Apps.

So far I have managed to implement this interaction between 3 basic apps (1 auth server, 1 resource server and 1 client). The thing I don't get working is the logout functionality. I have read of the "notoriously tricky problem" that Dave Syer describes in his tutorial, but in this case I really need the user to re-login after loging out. I have tried giving few seconds to the access token and the refresh token, but instead of being prompted to login again when the expiration arrives, I'm getting a NPE on the client app. I have also tried the solutions proposed in this post to remove the token from the token store, but it doesn't work. The single sign off is for me the desirable behaviour for this implementation. How can I achieve this using Spring Boot Oauth2. If it is not possible for some reason, which alternatives I could use to implement a centralized security using Spring Boot?

Thanks in advance.

答:
After a lot of tests I have realized that this can be solved just with a redirect to the AuthServer and doing logout programmatically like this:

In the client app (WebSecurityConfigurerAdapter):

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .logout()
            .logoutSuccessUrl("http://your-auth-server/exit");
}
</code>```

In the authorization server:

```<code>@Controller
public class LogoutController {

    @RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        // token can be revoked here if needed
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            //sending back to client app
            response.sendRedirect(request.getHeader("referer"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I have posted a sample app on github with a full example of this implementation.

Body:
After a lot of tests I have realized that this can be solved just with a redirect to the AuthServer and doing logout programmatically like this:

In the client app (WebSecurityConfigurerAdapter):

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .logout()
            .logoutSuccessUrl("http://your-auth-server/exit");
}

In the authorization server:

@Controller
public class LogoutController {

    @RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        // token can be revoked here if needed
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            //sending back to client app
            response.sendRedirect(request.getHeader("referer"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I have posted a sample app on github with a full example of this implementation.


来源: stackexchange

问:
C# SqlCacheDependency - Should I have to EnableNotifications and EnableTableForNotifications Whenever my application is ran?
I'm wondering if I have to execute this code whenever my application is ran or once I ran it, my database is now set to clean my cache whenever determined table specified is changed.</p>

```<code>System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(cs);

System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(cs, "TABLENAME");
</code>```

答:
You can EnableNotifications and EnableTableForNotifications in the place that sets up the SqlCacheDependency.

Don't forget that if you want to disable this, you will have to call DisableNotifications and / or DisableTableForNotifications.

That being said, you should start and stop the listener in the Application_Start and Application_End methods.

```<code>protected void Application_Start(object sender, EventArgs e)
{
    SqlDependency.Start("YOUR CONNECTION STRING");
}

protected void Application_End(object sender, EventArgs e)
{
    SqlDependency.Stop("YOUR CONNECTION STRING");
}
</code>```

More info here.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if I have to execute this code whenever my application is ran or once I ran it, my database is now set to clean my cache whenever determined table specified is changed.

System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(cs);

System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(cs, "TABLENAME");

Body:
You can EnableNotifications and EnableTableForNotifications in the place that sets up the SqlCacheDependency.

Don't forget that if you want to disable this, you will have to call DisableNotifications and / or DisableTableForNotifications.

That being said, you should start and stop the listener in the Application_Start and Application_End methods.

protected void Application_Start(object sender, EventArgs e)
{
    SqlDependency.Start("YOUR CONNECTION STRING");
}

protected void Application_End(object sender, EventArgs e)
{
    SqlDependency.Stop("YOUR CONNECTION STRING");
}

More info here.


问:
can't create simple image from php exec , can create with the same command as standalone
I have this code running in CentOS 5.5 ,PHP 5.1.6 ,Apache/2.2.3 ,ImageMagick 6.2.8

```<code>$convert = "/usr/bin/convert";
$command = "$convert -size 100x100 xc:blue mytest.jpg";
$test_image = exec($command);
echo "<img src=\"mytest.jpg\">";
</code>```

when i run the php tester i dont get the image created , only the echo string printed on page as html.

but when i run the same command as onliner the image does created just fine.

```<code>/usr/bin/convert -size 100x100 xc:blue mytest.jpg
</code>```

what is wrong here i can't tell.

答: Does PHP, the user, have permission to do that?</p>

ContentLicense: CC BY-SA 2.5

Body:
I have this code running in CentOS 5.5 ,PHP 5.1.6 ,Apache/2.2.3 ,ImageMagick 6.2.8

$convert = "/usr/bin/convert";
$command = "$convert -size 100x100 xc:blue mytest.jpg";
$test_image = exec($command);
echo "";

when i run the php tester i dont get the image created , only the echo string printed on page as html.

but when i run the same command as onliner the image does created just fine.

/usr/bin/convert -size 100x100 xc:blue mytest.jpg

what is wrong here i can't tell.


问:
How to update specific rows by comparing timestamps?
Hey I have an online database which needs to be populated with sensor values periodically. There are 7 variables(columns) coupled with a timestamp column to make each row of the table. Problem is these variables are pushed a few at a time with the rest as 0. Now I'm coding an algo which will only insert a row if all values of latest row (by timestamp) are filled completely(not 0), else it will update the latest row.
Here's my PHP code for one of the insert php files which inserts 3 variables at a time - temp, pressure and altitude.

```<code><?php

// Prepare variables for database connection

$dbusername = "uxpertla_terr";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";

// Connect to your database

$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);

// Prepare the SQL statement
    $sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
    $snd=mysqli_query($sdl);
    $row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
    if($row)
    {
    if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
    {
    $sql = "UPDATE uxpertla_test_db.testt
    SET temp='".$_GET["value"]."',
    pressure='".$_GET["value2"]."',
    altitude='".$_GET["value3"]."'
    WHERE time=".strtotime($row['time'])."";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";

// Execute SQL statement

mysqli_query($sql);
</code>```

?>

Sorry if the code's not pretty, but I need help with the where clause of update query in the second if block..

答:
Figured out the answer.. :p

```<code><?php

// Prepare variables for database connection

$dbusername = "uxpertla_terr";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";

// Connect to your database

$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);

    $sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
    $snd=mysqli_query($dbconnect,$sdl);
    $row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
    if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
    {
    $sql = "UPDATE uxpertla_test_db.testt
    SET temp='".$_GET["value"]."',
    pressure='".$_GET["value2"]."',
    altitude='".$_GET["value3"]."'
    ORDER BY time DESC LIMIT 1";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";

// Execute SQL statement

mysqli_query($dbconnect,$sql);
</code>```

?>

Body:
Hey I have an online database which needs to be populated with sensor values periodically. There are 7 variables(columns) coupled with a timestamp column to make each row of the table. Problem is these variables are pushed a few at a time with the rest as 0. Now I'm coding an algo which will only insert a row if all values of latest row (by timestamp) are filled completely(not 0), else it will update the latest row.
Here's my PHP code for one of the insert php files which inserts 3 variables at a time - temp, pressure and altitude.

<?php

// Prepare variables for database connection

$dbusername = "uxpertla_terr";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";

// Connect to your database

$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);

// Prepare the SQL statement
    $sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
    $snd=mysqli_query($sdl);
    $row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
    if($row)
    {
    if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
    {
    $sql = "UPDATE uxpertla_test_db.testt
    SET temp='".$_GET["value"]."',
    pressure='".$_GET["value2"]."',
    altitude='".$_GET["value3"]."'
    WHERE time=".strtotime($row['time'])."";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";

// Execute SQL statement

mysqli_query($sql);

?>

Sorry if the code's not pretty, but I need help with the where clause of update query in the second if block..

Body:
Figured out the answer.. :p

<?php

// Prepare variables for database connection

$dbusername = "uxpertla_terr";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";

// Connect to your database

$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);

    $sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
    $snd=mysqli_query($dbconnect,$sdl);
    $row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
    if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
    {
    $sql = "UPDATE uxpertla_test_db.testt
    SET temp='".$_GET["value"]."',
    pressure='".$_GET["value2"]."',
    altitude='".$_GET["value3"]."'
    ORDER BY time DESC LIMIT 1";
    }
    else
    $sql = "INSERT INTO uxpertla_test_db.testt
    (temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";

// Execute SQL statement

mysqli_query($dbconnect,$sql);

?>


问:
Bootstrap 4 - put small element between two long in a row without gaps
I want to make it look similar to this.

```<code>hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

  <div class="row code-line">
    <div class="col-5">
      <div class="line-left">
        <hr>
      </div>
    </div>
    <div class="col-1">
      <i class="fa fa-code fa-2x" aria-hidden="true"></i>
    </div>
    <div class="col-5">
     <div class="line-right">
        <hr>
      </div>
    </div>
  </div>
</code>```

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

答:
I'd go for a simpler markup:

```

<p>Just place it the container of your choice and it will stretch.
Here's how:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.centered-separator {
  display: flex;
  align-items: center;
  color: #999;
}
.centered-separator > * {
  margin: 0 1rem;
}
.centered-separator::before,
.centered-separator::after {
  height: 2px;
  width: 100%;
  display: block;
  background-color: #999;
  content: '';
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

 ```

Body:
I want to make it look similar to this.

hr  {
  border: none;
  color: black;
  background-color: black;
  height: 5px;
  margin-top: 10px;
}

(fa-code is Font-Awesome icon)

Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100

I don't know how to make it symmetric and responsive(long lines should become smaller while resizing). Probably, using flexbox could help?

Body:
I'd go for a simpler markup:

 <div class="centered-separator">
   <i class="fa fa-code fa-2x"></i>
 </div>

Just place it the container of your choice and it will stretch.
Here's how:

.centered-separator {
  display: flex;
  align-items: center;
  color: #999;
}
.centered-separator > * {
  margin: 0 1rem;
}
.centered-separator::before,
.centered-separator::after {
  height: 2px;
  width: 100%;
  display: block;
  background-color: #999;
  content: '';
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="centered-separator">
    <i class="fa fa-code fa-2x"></i>
</div>


问:
How to call ListView adapter's getItem(i) from Activity
I have a ListView adapter:

```<code>public class CartList extends BaseAdapter {
    // ...
    @Override
    public long getItemId(int i) { return i; }
    // ...

}
</code>```

And I have this activity:

```<code>public class ListActivity extends AppCompatActivity {
    ListView lv_list;
    static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // my_code;
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int pos = position;
                CartEntity item = CartList.getItem(pos);
            }
        });
    }
</code>```

That shows this error:

Non-static method 'getItem(int)' cannot be referenced from a static
  context

How Can i call the method to get selected item?
Without 'getItem' line works fine, but i need the object.

答:
learn about access modifier in java. You can get the item from lista1 call get() method from ArrayList like this CartEntity item = lista1.get(pos)

or if you still want CartEntity from the adapter make the adapter as local variable or instance variable and you can call getItem() because it's public

```<code>public class ListActivity extends AppCompatActivity {
ListView lv_list;
static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Create object from Adapter Class
    CartList cartAdapter = new CartList();

    // my_code;
    lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final int pos = position;
            CartEntity item = cartAdapter.getItem(pos);
        }
    });
}
</code>```

Body:
I have a ListView adapter:

public class CartList extends BaseAdapter {
    // ...
    @Override
    public long getItemId(int i) { return i; }
    // ...

}

And I have this activity:

public class ListActivity extends AppCompatActivity {
    ListView lv_list;
    static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // my_code;
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int pos = position;
                CartEntity item = CartList.getItem(pos);
            }
        });
    }

That shows this error:

Non-static method 'getItem(int)' cannot be referenced from a static
  context

How Can i call the method to get selected item?
Without 'getItem' line works fine, but i need the object.

Body:
learn about access modifier in java. You can get the item from lista1 call get() method from ArrayList like this CartEntity item = lista1.get(pos)

or if you still want CartEntity from the adapter make the adapter as local variable or instance variable and you can call getItem() because it's public

public class ListActivity extends AppCompatActivity {
ListView lv_list;
static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Create object from Adapter Class
    CartList cartAdapter = new CartList();

    // my_code;
    lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final int pos = position;
            CartEntity item = cartAdapter.getItem(pos);
        }
    });
}


问:
"ArgumentOutOfRangeException" loading any razor page
So I've been having some strange issues with an ASP.NET Core app of mine, whenever I load any Razor page, or do anything in relation to Razor code, I get an ArgumentOutOfRangeException thrown at me.

```<code>ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: version
Microsoft.CodeAnalysis.CSharp.CSharpParseOptions.WithLanguageVersion(LanguageVersion version)
</code>```

Despite intense Googling, I've not been able to find anything related to the issue I'm having. No amounts of moving files around, reinstalling or restoring of nuget packages has helped.

I've also tried re-targeting different C# and .NET Framework versions, to no avail.

Here's the basic stack trace, I don't really see it being of much use, but hey.

```<code>System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: version
   at Microsoft.CodeAnalysis.CSharp.CSharpParseOptions.WithLanguageVersion(LanguageVersion version)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DependencyContextRazorViewEngineOptionsSetup.SetParseOptions(RazorViewEngineOptions options, CompilationOptions compilationOptions)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DependencyContextRazorViewEngineOptionsSetup.Configure(RazorViewEngineOptions options)
   at Microsoft.Extensions.Options.OptionsCache`1.CreateOptions()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.Extensions.Options.OptionsCache`1.get_Value()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager..ctor(ApplicationPartManager partManager, IOptions`1 optionsAccessor)
--- End of stack trace from previous location where exception was thrown ---
</code>```

答: Update the Microsoft.CodeAnalysis.CSharp to the latest version.

Body:
So I've been having some strange issues with an ASP.NET Core app of mine, whenever I load any Razor page, or do anything in relation to Razor code, I get an ArgumentOutOfRangeException thrown at me.

ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: version
Microsoft.CodeAnalysis.CSharp.CSharpParseOptions.WithLanguageVersion(LanguageVersion version)

Despite intense Googling, I've not been able to find anything related to the issue I'm having. No amounts of moving files around, reinstalling or restoring of nuget packages has helped.

I've also tried re-targeting different C# and .NET Framework versions, to no avail.

Here's the basic stack trace, I don't really see it being of much use, but hey.

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: version
   at Microsoft.CodeAnalysis.CSharp.CSharpParseOptions.WithLanguageVersion(LanguageVersion version)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DependencyContextRazorViewEngineOptionsSetup.SetParseOptions(RazorViewEngineOptions options, CompilationOptions compilationOptions)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DependencyContextRazorViewEngineOptionsSetup.Configure(RazorViewEngineOptions options)
   at Microsoft.Extensions.Options.OptionsCache`1.CreateOptions()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.Extensions.Options.OptionsCache`1.get_Value()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorReferenceManager..ctor(ApplicationPartManager partManager, IOptions`1 optionsAccessor)
--- End of stack trace from previous location where exception was thrown ---


问:
Seam Logger inside a Servlet?
Is there a way to use a Seam Logger inside of a standard Java Servlet?  I have one servlet that I use to serve up content, while the rest of my application is developed using Seam.  I'd like to be able to make use of Seam's built-in Log functionality in my servlet, the same way I do with the rest of my Seam-based classes.  In my Servlet constructor, I tried calling

```<code>Log logger = (Log)Component.getInstance(Log.class);
</code>```

...but I'm getting an exception.  Is there a better way to "inject" a Logger into the servlet?  Something I'm missing?  Thanks!!

答:
To use a Seam context you can wrap the doPost or doGet methods with ContextualHttpServletRequest which allows you to do Component lookups.

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpServletRequest req = request;
        new ContextualHttpServletRequest( req ) {
            public void process() throws Exception {
                wrappedPost( req );
            }
        }.run();
    }

// you renamed original doPost method
private void wrappedPost(HttpServletRequest request) {
...
}
</code>```

The above example code allows you to access components by name, which are declared using the name annotation:

```<code>@Name("MyCcomponent")
</code>```

The Logger is usually injected by the @Logger annotation, I checked logs the source package, there is no component with a @Name annotation that could be looked up. If you call a component (with @Logger) from the wrapped context, a logger will be injected (into the called compontent).

Seam uses in its components:

```<code>private static final LogProvider log = Logging
            .getLogProvider(MailSession.class);
</code>```

Title: Seam Logger inside a Servlet?

Body:
Is there a way to use a Seam Logger inside of a standard Java Servlet?  I have one servlet that I use to serve up content, while the rest of my application is developed using Seam.  I'd like to be able to make use of Seam's built-in Log functionality in my servlet, the same way I do with the rest of my Seam-based classes.  In my Servlet constructor, I tried calling

Log logger = (Log)Component.getInstance(Log.class);

...but I'm getting an exception.  Is there a better way to "inject" a Logger into the servlet?  Something I'm missing?  Thanks!!

Body:
To use a Seam context you can wrap the doPost or doGet methods with ContextualHttpServletRequest which allows you to do Component lookups.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpServletRequest req = request;
        new ContextualHttpServletRequest( req ) {
            public void process() throws Exception {
                wrappedPost( req );
            }
        }.run();
    }

// you renamed original doPost method
private void wrappedPost(HttpServletRequest request) {
...
}

The above example code allows you to access components by name, which are declared using the name annotation:

@Name("MyCcomponent")

The Logger is usually injected by the @Logger annotation, I checked logs the source package, there is no component with a @Name annotation that could be looked up. If you call a component (with @Logger) from the wrapped context, a logger will be injected (into the called compontent).

Seam uses in its components:

private static final LogProvider log = Logging
            .getLogProvider(MailSession.class);


问:
merging columns when column name is an integer
this is my dataframe:

```<code>A   B     1    2    5

1   1     26    5   5
2   6     4     2   2
2   3     8     7   7
2   4     3    10   19
</code>```

So here you can see that columns are 'A' 'B' '1' '2' '5'
I want to create a function that accepts one argument as int and then creates a new dataframe that has 'A' 'B' columns and column which was passed as arugment.
so it would go like this, however im not sure how to get the column when its name is an int any ideas ? Thanks!:

```<code>def merge(arg):
    new_df=pd.concat([df.A, df.B, df.arg], axis=1 )
merge(5)

A   B     5

1   1     5
2   6     2
2   3     7
2   4     19
</code>```

答:
```<code>def merge(arg):
    return df.loc[:, ['A', 'B', str(arg)]]

merge(2)

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10
</code>```

You could also imbed if/else logic to make it more robust

```<code>def merge(arg):
    arg = arg if arg in df.columns else str(arg)
    return df.loc[:, ['A', 'B', arg]]

print(merge(2))

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10
</code>```

Or with a bit of clever intersection

```<code>def merge(arg):
    cols = df.columns.intersection(['A', 'B', arg, str(arg)])
    return df.loc[:, cols]

print(merge(2))

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10
</code>```

Body:
this is my dataframe:

A   B     1    2    5

1   1     26    5   5
2   6     4     2   2
2   3     8     7   7
2   4     3    10   19

So here you can see that columns are 'A' 'B' '1' '2' '5'
I want to create a function that accepts one argument as int and then creates a new dataframe that has 'A' 'B' columns and column which was passed as arugment.
so it would go like this, however im not sure how to get the column when its name is an int any ideas ? Thanks!:

def merge(arg):
    new_df=pd.concat([df.A, df.B, df.arg], axis=1 )
merge(5)

A   B     5

1   1     5
2   6     2
2   3     7
2   4     19

Body:
def merge(arg):
    return df.loc[:, ['A', 'B', str(arg)]]

merge(2)

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10

You could also imbed if/else logic to make it more robust

def merge(arg):
    arg = arg if arg in df.columns else str(arg)
    return df.loc[:, ['A', 'B', arg]]

print(merge(2))

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10

Or with a bit of clever intersection

def merge(arg):
    cols = df.columns.intersection(['A', 'B', arg, str(arg)])
    return df.loc[:, cols]

print(merge(2))

   A  B   2
0  1  1   5
1  2  6   2
2  2  3   7
3  2  4  10


问:
php session variables on multiple pages not working

<?php
//page 1
session_start();
...
$_SESSION['user_name_loggedin'] = $user;
header("Location: profile.php");
...
?>```
</div>
</div>
</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><?php
//page2
session_start();
...
if(isset($_SESSION['user_name_loggedin'])){
 echo $_SESSION['user_name_loggedin'];
}else{
 echo 'not set<br>';
}
...
?></code>```

I am trying to get a login working on my site using sessions. Above shows examples of the two pages I wish to transfer information between using a session. $user is taken from the login form on the login page. On the profile page, after logging in, it only shows 'not set'. Is there anything I am missing?

Thanks in advance

答:
Tried it locally using the following code:

1 test.php

```<code>`<?php
//page 1
session_start();
$user="dvjnvki";
$_SESSION['user_name_loggedin'] = $user;
header("Location: b.php");
?>`
</code>```

2 b.php

```<code><?php
//page2
session_start();
if(isset($_SESSION['user_name_loggedin'])){
echo $_SESSION['user_name_loggedin'];
}else{
echo 'not set<br>';
}
?>
</code>```

and it does work perfectly. So the issue with your code might be that you might not be getting a value for the variable called $user. Try to echo that first and see if you get an output.

Body:
<?php
//page 1
session_start();
...
$_SESSION['user_name_loggedin'] = $user;
header("Location: profile.php");
...
?>

<?php
//page2
session_start();
...
if(isset($_SESSION['user_name_loggedin'])){
 echo $_SESSION['user_name_loggedin'];
}else{
 echo 'not set
';
}
...
?>

I am trying to get a login working on my site using sessions. Above shows examples of the two pages I wish to transfer information between using a session. $user is taken from the login form on the login page. On the profile page, after logging in, it only shows 'not set'. Is there anything I am missing?

Thanks in advance

Body:
Tried it locally using the following code:

1 test.php

`<?php
//page 1
session_start();
$user="dvjnvki";
$_SESSION['user_name_loggedin'] = $user;
header("Location: b.php");
?>`

2 b.php

<?php
//page2
session_start();
if(isset($_SESSION['user_name_loggedin'])){
echo $_SESSION['user_name_loggedin'];
}else{
echo 'not set<br>';
}
?>

and it does work perfectly. So the issue with your code might be that you might not be getting a value for the variable called $user. Try to echo that first and see if you get an output.


问:
Custom drupal form with predetermined values
I need to customise my forms in drupal so that each  field has a value placed in it using a php script.

I have a php script which takes a url and gets a page title and meta description. It's easy enough to pass these values into a form by placing the required php in the input value. I can do this on a static 'test' form.

However, I'm not sure how to do this with a node form as I don't directly have access to the input value.

Any ideas or solutions would be greatly appreciated.

答: I'd suggest using JavaScript to accomplish this since it's very good at manipulating form values (in Drupal too).  If you can get the variables in JavaScript then it would be as simple as setting the input id value on page load.</p>


问:
Inserting DATETIME to SQL from PHP
I can't seem to store the datetime to the database.

```<code>public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}
</code>```

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table

答: MySQL time-stamp has a fixed pattern for date time input i.e. "Y-m-d H:i:s", If you want to insert date time into database then convert the pattern to the above mentioned one and then try. It'll work

Title: Inserting DATETIME to SQL from PHP

Body:
I can't seem to store the datetime to the database.

public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table


问:
Comparitive if statement not working?
This code is not working, any help?
The main problem is:

```<code>while True:
    x1 = input("what's a?")
    if x1 == a:
        delay("a is correct!")
        x2 = input("what's b?")
        if x2 == b:
            delay("you're correct!")
            delay("bye")
            break
</code>```

Here's the full code for reference:

```<code>from random import randint
from time import sleep
def delay(x):
    print(x)
    sleep(0.4)
delay("Welcome to the adding game")
delay("two numbers will be randomly generated")
delay("we'll call then a and b")
delay("We'll show you a+b first")
delay("then a-b")
delay("use that information to then determine the answer")
input("ready?")
a = randint(1,15)
b = randint(1,15)
print("a+b = ",a+b)
print("a-b = ",a-b)
print(a,b)
while True:
    x1 = input("what's a?")
    if x1 == a:
        delay("a is correct!")
        x2 = input("what's b?")
        if x2 == b:
            delay("you're correct!")
            delay("bye")
            break
        else:
            delay("wrong")
    else:
        delay("you're wrong")
        x3 = input("what's b?")
        if x3 == b:
            delay("that's correct!")
            delay("now use that info to figure out a")
        else:
            delay("wrong again")
            delay("look at the numbers and try again")
</code>```

答:
input() returns a string, and a and b are integers, so comparing them won't work.

x1 = int(input("what's a?")), and likewise for x2 and x3, will make the comparisons work as expected.

Title: Comparitive if statement not working?

Body:
This code is not working, any help?
The main problem is:

while True:
    x1 = input("what's a?")
    if x1 == a:
        delay("a is correct!")
        x2 = input("what's b?")
        if x2 == b:
            delay("you're correct!")
            delay("bye")
            break

Here's the full code for reference:

from random import randint
from time import sleep
def delay(x):
    print(x)
    sleep(0.4)
delay("Welcome to the adding game")
delay("two numbers will be randomly generated")
delay("we'll call then a and b")
delay("We'll show you a+b first")
delay("then a-b")
delay("use that information to then determine the answer")
input("ready?")
a = randint(1,15)
b = randint(1,15)
print("a+b = ",a+b)
print("a-b = ",a-b)
print(a,b)
while True:
    x1 = input("what's a?")
    if x1 == a:
        delay("a is correct!")
        x2 = input("what's b?")
        if x2 == b:
            delay("you're correct!")
            delay("bye")
            break
        else:
            delay("wrong")
    else:
        delay("you're wrong")
        x3 = input("what's b?")
        if x3 == b:
            delay("that's correct!")
            delay("now use that info to figure out a")
        else:
            delay("wrong again")
            delay("look at the numbers and try again")


问:
Why am I having so much trouble submitting my app to Apple?
This is my first time trying to submit an app to Apple, and I'm having a bunch of issues. I'm pretty sure I've generated all my certificates, AppID's, etc... I've been running the app on my phone just fine, then all of a sudden I started getting errors submitting. My first error was this:

But as you can see, the Bundle ID's are the same:

The ID in Xcode:

And the ID in iTunes Connect:

So I tried changing the Bundle ID, and made sure the Bundle ID's were the same across iTunes connect, Xcode, etc. I started out the project with a different name. Should I just start a new project with consistent naming?

Should the Bundle Identifier in Info read com.Kaen.M01eskin ?

It doesn't work with Application Loader either:

答:
Somewhere the bundle identifier is getting M01eskin---prepended to it. As you can see in the dialog. I would check in your info.plist if perhaps there is something in Bundle identifier before the $(PRODUCT_BUNDLE_IDENTIFIER).

You could try hard coding it there and see if that resolves your problems.

Or try looking in your build settings for the target under Product Bundle Identifier and check there as well.


问:
SSH into vagrant with X server set up
I am running into problems with setting up X11 forwarding on vagrant VM.

I am running Xming for X server and PuTTY as my SSH client.

This is what I get when I run vagrant ssh-config:

```<code>Host default
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/Users/MyName/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL
  ForwardAgent yes
  ForwardX11 yes
</code>```

My PuTTY has X11 forwarding enabled and X display location set to 0.0.

When I do echo $DISPLAY I get no response.

I am unsure as to what I configured wrongly. I followed the following advice in setting up my PuTTY client. If there is an easier way to set up VM with X11 forwarding, please, let me know.

For reference these are contents of my Vagrantfile.

```<code>VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.ssh.forward_agent = true
  config.ssh.forward_x11 = true

end
</code>```

答:
Use "startxwin" to run the cygwin X server. Use putty or the cygwin ssh client to ssh to your guest virtual machine.

If using cygwin ssh, do "export DISPLAY=:0" before running ssh (ie "vagrant ssh -- -vvv -X").

For putty: Run "startxwin -- -listen tcp", enable ssh-X11 forwarding in the putty connection config, set "X display location" to "localhost:0" and set the correct path of the .Xauthority file (browse, it is probably in your home directory; startxwin output will tell you where).

Perhaps do not use msys2 ssh (the vagrant default installed environment is msys2 but vagrant also works fine under cygwin) with the cygwin X server. (see details for more info about why)

Details:

If you get "connect /tmp/.X11-unix/X0: No such file or directory" (under ssh verbose mode) or putty error "PuTTY X11 proxy: unable to connect to forwarded X server: Network error: Connection refused", try using tcp sockets rather than the default unix domain sockets.

When you run your Cygwin X server, go "X -listen tcp -multiwindow" (multiwindow is optional - it opens new windows for each app).

If using openssh "ssh" from the command-line: Before going "vagrant ssh -- -vvv -X", go "export DISPLAY=localhost:0" (not ":0" but "localhost:0" so it uses tcp). I am running git bash which uses msys2 which seems to not communicate properly with my cygwin X server over emulated unix domain sockets. But if I use "vagrant ssh -- -X" under my cygwin prompt (with DISPLAY=:0 for unix domain sockets), it works.

Great info source: http://dustwell.com/how-x-over-ssh-really-works.html

Also, you can add "config.ssh.forward_x11 = true" to your Vagrantfile. I think this sets X11Forwarding in /etc/ssh/sshd_config when the guest virtual machine is set up or "vagrant reload" is run. - https://coderwall.com/p/ozhfva/run-graphical-programs-within-vagrantboxes

Update: It is not recommended to run X without xauth security (as shown above). It is not secure. For example, other computers on the same LAN can connect to your x-server via tcp and sniff your keypresses using xkeys. Use "startxwin" instead of running X directly so it uses the "-auth" option of XWin. This makes it difficult for me to get my msys2 ssh to redirect X to my cygwin X server. The ssh log while connecting says it cannot find the xauth command - that is because it is not present in my msys2 environment. Cygwin ssh X-redirection still works fine. Putty works fine as long as you set the .Xauthority file path (it is probably right in your home directory) in the putty session config.

I discovered the tcp/unix-domain socket problem/solution is actually in the cygwin faq (this faq is quite helpful and has a lot of info):

6.7. X sessions forwarded by PuTTY can't connect. Non-cygwin local X clients can't connect.

The X server now uses -nolisten tcp by default, which increases the security of the X server by not opening a TCP/IP socket, only a local (UNIX domain) socket. Non-cygwin applications cannot connect to that socket.

https://x.cygwin.com/docs/faq/cygwin-x-faq.html

Title: SSH into vagrant with X server set up

Body:
I am running into problems with setting up X11 forwarding on vagrant VM.

I am running Xming for X server and PuTTY as my SSH client.

This is what I get when I run vagrant ssh-config:

Host default
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/Users/MyName/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL
  ForwardAgent yes
  ForwardX11 yes

My PuTTY has X11 forwarding enabled and X display location set to 0.0.

When I do echo $DISPLAY I get no response.

I am unsure as to what I configured wrongly. I followed the following advice in setting up my PuTTY client. If there is an easier way to set up VM with X11 forwarding, please, let me know.

For reference these are contents of my Vagrantfile.

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.ssh.forward_agent = true
  config.ssh.forward_x11 = true

end


问:
What are alternatives for Sinon.js (JS mocking library)?
Are there any worthwhile alternatives for Sinon.js?

Thanks.

答:
I just started a new project called candy-wrapper that may be an alternative to Sinon in some instances:
https://www.npmjs.com/package/candy-wrapper

Here are some examples of how to use it, I would love feedback if anyone has any insights as to how to make it better:

var Wrapper = require("candy-wrapper");

// a simple test object
var myDrone = {
    name: "DJI",
    fly: function(direction) {
        return true;
    }
}

new Wrapper(myDrone, "name");
new Wrapper(myDrone, "fly");

myDrone.fly("north");
myDrone.fly("west");

// evaluating previous calls through the 'historyList' and 'Filters'
myDrone.fly.historyList.filterFirst().expectCallArgs("north"); // true
myDrone.fly.historyList.filterSecond().expectCallArgs("east"); // false
myDrone.fly.expectReportAllFailtures(); // throws an error about the "east" expecation failing

// modifying behavior using 'Triggers'
myDrone.fly.triggerOnCallArgs("east").actionReturn(false); // will return 'false' when called with "east"
myDrone.fly("east"); // false
myDrone.fly("west"); // true (the default return value)

// working with properties
myDrone.name.triggerOnSet().actionThrowException(new Error("do not set the name"));
myDrone.name = "Bob"; // throws Error: "do not set the name"
var ret = myDrone.name; // ret = "DJI"
```


问:
Responsive rollover image
I am trying to make a rollover image responsive to browser width and height. Here is the current code:

```<code>'<a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a>'
</code>```

Any thoughts?

答:
A modern better practice to this would be non-JS / pure CSS. There are a few methods to achieving this, here's one:

```<code><a href="#"><div class="myimg"></div></a>
</code>```

```<code>   .myimg {
    width:80%;
    height:200px;
    background: url(https://s-media-cache-ak0.pinimg.com/736x/bc/4e/38/bc4e386f24997b6f8c4c1f8ce96a7cef.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
.myimg:hover {
    background: url(http://img00.deviantart.net/4ec1/i/2013/017/5/b/blue_eyed_huskey_by_ashleysmithphoto-d5rsvt2.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
</code>```

Live Demo. Obviously, you would configure the above CSS properties to your preference / project.

Title: Responsive rollover image

Body:
I am trying to make a rollover image responsive to browser width and height. Here is the current code:

''

Any thoughts?

Body:
A modern better practice to this would be non-JS / pure CSS. There are a few methods to achieving this, here's one:

<a href="#"><div class="myimg"></div></a>

   .myimg {
    width:80%;
    height:200px;
    background: url(https://s-media-cache-ak0.pinimg.com/736x/bc/4e/38/bc4e386f24997b6f8c4c1f8ce96a7cef.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
.myimg:hover {
    background: url(http://img00.deviantart.net/4ec1/i/2013/017/5/b/blue_eyed_huskey_by_ashleysmithphoto-d5rsvt2.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

Live Demo. Obviously, you would configure the above CSS properties to your preference / project.


问:
Nested loop not running correctly inside recruisive function
Outer loop of nested loop not running correctly inside recruisive function.
Simplified example:</p>

```<code>uint max =3;
        void func(uint a,uint b,uint depth){

            for(; a<max; a++){ // problem here after first recrusion , counting but not going inside braces with recruisive function
                for(; b<max; b++){ // inner loop works in recruisive function well
                if(depth<2){
                   func(0,0,depth+1);
                           }

                }
            }
        }
</code>```

答:
With your initially posted code:

Unless max is 0, this code will result in a stack overflow due to infinite recursion: the first iteration in a recursion will immediately call the the function recursively starting with a and b being 0 again.

with your revised code:

The depth limits the recursion and avoids the endless recursion.

However, after the first external iteration, b has reached max. For all the successive iterations in the a loop, as you don't reset b, the inner loop stops immediately

Body:
Outer loop of nested loop not running correctly inside recruisive function.
Simplified example:

uint max =3;
        void func(uint a,uint b,uint depth){

            for(; a<max; a++){ // problem here after first recrusion , counting but not going inside braces with recruisive function
                for(; b<max; b++){ // inner loop works in recruisive function well
                if(depth<2){
                   func(0,0,depth+1);
                           }

                }
            }
        }


问:
Node.js passport sign up
I am building a mobile only back-end with Node.js utilizing Passport version 0.3.2 for native sign up. The user is being saved to MongoDB properly, but I am having trouble sending back the correct response. Here is my code:

```<code>passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        session: false
    },
    function(email, password, done) {
        process.nextTick(function() {
            User.findOne({
                email: email.toLowerCase()
            }, function(err, user) {
                if (err) {
                    return done(err);
                } else {
                    if (user) {
                        return done(null, false);
                    } else {

                        // Create new user if email does not exist
                        var newUser = new User();

                        // set the user's local credentials
                        newUser.email = email;
                        newUser.password = newUser.generateHash(password);

                        // save the user
                        newUser.save(function(err) {
                            if (err) {
                                console.log('throwing error: ' + err);
                                throw err;
                            }
                            console.log('the new user: ' + newUser);
                            return done(null, newUser);
                        });
                    }
                }
            });
        });
    }
));
</code>```

Here is my user model class:

```<code>var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose'),
bcrypt = require('bcrypt-nodejs'),
ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
    id: String,
    email: String,
    password: String,
    dateRegistered: { type: Date, 'default': Date.now }
});

UserSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
UserSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);
</code>```

And, I am receiving a 500 response while saving the user, as follows:

the new user:

```<code>{ __v: 0,
  password: '$2a$08$0GaE32gxf0jdW3vdxDxWeuSjYuwsOzZmHDhrov0ujPgSOl2imoE/C',
  email: 'abcd@gmail.com',
  _id: 58de8e71078555716a76c651,
  dateRegistered: 2017-03-31T17:14:25.407Z }
</code>```

Response

```<code>POST /signup 500 267.022 ms - -
Error: Failed to serialize user into session
    at pass (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/authenticator.js:271:19)
    at Authenticator.serializeUser (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/authenticator.js:289:5)
    at IncomingMessage.req.login.req.logIn (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/http/request.js:50:29)
    at Strategy.strategy.success (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/middleware/authenticate.js:235:13)
    at verified (/Users/abcd/Developer/node-apps/flow/node_modules/passport-local/lib/strategy.js:83:10)
    at /Users/abcd/Developer/node-apps/flow/server/config/passport.js:39:40
    at /Users/abcd/Developer/node-apps/flow/node_modules/mongoose/lib/model.js:3702:16
    at /Users/abcd/Developer/node-apps/flow/node_modules/mongoose/lib/services/model/applyHooks.js:146:20
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
</code>```

答:
The user id is saved as session data and deserializeUser is used to retrieve whole object for future use.serializeUser is used to store user id in session. The result of serializeUser method store as req.session.passport.user = {id : 'abcd'}

On the other side deserializeUser gives a object of user on the basis of argument which is key of use means id.

```<code>// here user id is pass as a id of deserializeUser method to retrieve object
passport.serializeUser(function (user, done) {
    done(null,user.id);
});
passport.deserializeUser(function (id, done) {
    customer.findById(id, function (error, user) {
        done(error, user);
    });
});

 <br />
</code>```

```<code>Add bellow code to your server.js file
</code>```

```<code>var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({
    secret : "secretkey",
    resave : false,
    saveUninitialized : false
}));
app.use(passport.initialize());
app.use(passport.session());

//now add path where your passport authentication file is placed.
require('./customerConfig/passport');
</code>```

Title: Node.js passport sign up

Body:
I am building a mobile only back-end with Node.js utilizing Passport version 0.3.2 for native sign up. The user is being saved to MongoDB properly, but I am having trouble sending back the correct response. Here is my code:

passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        session: false
    },
    function(email, password, done) {
        process.nextTick(function() {
            User.findOne({
                email: email.toLowerCase()
            }, function(err, user) {
                if (err) {
                    return done(err);
                } else {
                    if (user) {
                        return done(null, false);
                    } else {

                        // Create new user if email does not exist
                        var newUser = new User();

                        // set the user's local credentials
                        newUser.email = email;
                        newUser.password = newUser.generateHash(password);

                        // save the user
                        newUser.save(function(err) {
                            if (err) {
                                console.log('throwing error: ' + err);
                                throw err;
                            }
                            console.log('the new user: ' + newUser);
                            return done(null, newUser);
                        });
                    }
                }
            });
        });
    }
));

Here is my user model class:

var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose'),
bcrypt = require('bcrypt-nodejs'),
ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
    id: String,
    email: String,
    password: String,
    dateRegistered: { type: Date, 'default': Date.now }
});

UserSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
UserSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);

And, I am receiving a 500 response while saving the user, as follows:

the new user:

{ __v: 0,
  password: '$2a$08$0GaE32gxf0jdW3vdxDxWeuSjYuwsOzZmHDhrov0ujPgSOl2imoE/C',
  email: 'abcd@gmail.com',
  _id: 58de8e71078555716a76c651,
  dateRegistered: 2017-03-31T17:14:25.407Z }

Response

POST /signup 500 267.022 ms - -
Error: Failed to serialize user into session
    at pass (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/authenticator.js:271:19)
    at Authenticator.serializeUser (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/authenticator.js:289:5)
    at IncomingMessage.req.login.req.logIn (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/http/request.js:50:29)
    at Strategy.strategy.success (/Users/abcd/Developer/node-apps/flow/node_modules/passport/lib/middleware/authenticate.js:235:13)
    at verified (/Users/abcd/Developer/node-apps/flow/node_modules/passport-local/lib/strategy.js:83:10)
    at /Users/abcd/Developer/node-apps/flow/server/config/passport.js:39:40
    at /Users/abcd/Developer/node-apps/flow/node_modules/mongoose/lib/model.js:3702:16
    at /Users/abcd/Developer/node-apps/flow/node_modules/mongoose/lib/services/model/applyHooks.js:146:20
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Body:
The user id is saved as session data and deserializeUser is used to retrieve whole object for future use.serializeUser is used to store user id in session. The result of serializeUser method store as req.session.passport.user = {id : 'abcd'}

On the other side deserializeUser gives a object of user on the basis of argument which is key of use means id.

// here user id is pass as a id of deserializeUser method to retrieve object
passport.serializeUser(function (user, done) {
    done(null,user.id);
});
passport.deserializeUser(function (id, done) {
    customer.findById(id, function (error, user) {
        done(error, user);
    });
});

 <br />

Add bellow code to your server.js file

var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({
    secret : "secretkey",
    resave : false,
    saveUninitialized : false
}));
app.use(passport.initialize());
app.use(passport.session());

//now add path where your passport authentication file is placed.
require('./customerConfig/passport');


问:
Switch statement returning wrong result
I'm trying to run through this function which takes two arguments, income and filer status, and adjusts income to the after tax value using a number of switch statements. I'm clearly making a mistake somewhere because the function consistently returns 0 instead of my expected result.</p>

```<code>    var afterTaxes = function(income, filer) {
    var adjusted = 0;
    if (filer === "single") {
        switch (income) {
            case income < 9325:
                adjusted = (1.00 - 0.10) * income;
                break;
            case income < 37950:
                adjusted = (1.00 - 0.15) * income;
                break;
            case income < 91900:
                adjusted = (1.00 - 0.25) * income;
                break;
            case income < 191650:
                adjusted = (1.00 - 0.33) * income;
                break;
            case income < 416700:
                adjusted = (1.00 - 0.35) * income;
                break;
            case income >= 416700:
                adjusted = (1.00 - 0.40) * income;
                break;
            };
    } else if (filer === "married") {
        var adjusted = 0;
        switch (income) {
            case income < 9325:
                adjusted = (1.00 - 0.10) * income;
                break;
            case income < 37950:
                adjusted = (1.00 - 0.15) * income;
                break;
            case income < 91900:
                adjusted = (1.00 - 0.25) * income;
                break;
            case income < 191650:
                adjusted = (1.00 - 0.33) * income;
                break;
            case income < 416700:
                adjusted = (1.00 - 0.35) * income;
                break;
            case income >= 416700:
                adjusted = (1.00 - 0.40) * income;
                break;
        };
    };
    return adjusted;
};

afterTaxes(150000, "single");
</code>```

答: Assuming this is JS, your switch statement is incorrect. It takes an expression see documentation. Quick fix is to change the statements to switch(true){...}

ContentLicense: CC BY-SA 4.0

Title: Switch statement returning wrong result

Body:
I'm trying to run through this function which takes two arguments, income and filer status, and adjusts income to the after tax value using a number of switch statements. I'm clearly making a mistake somewhere because the function consistently returns 0 instead of my expected result.

    var afterTaxes = function(income, filer) {
    var adjusted = 0;
    if (filer === "single") {
        switch (income) {
            case income < 9325:
                adjusted = (1.00 - 0.10) * income;
                break;
            case income < 37950:
                adjusted = (1.00 - 0.15) * income;
                break;
            case income < 91900:
                adjusted = (1.00 - 0.25) * income;
                break;
            case income < 191650:
                adjusted = (1.00 - 0.33) * income;
                break;
            case income < 416700:
                adjusted = (1.00 - 0.35) * income;
                break;
            case income >= 416700:
                adjusted = (1.00 - 0.40) * income;
                break;
            };
    } else if (filer === "married") {
        var adjusted = 0;
        switch (income) {
            case income < 9325:
                adjusted = (1.00 - 0.10) * income;
                break;
            case income < 37950:
                adjusted = (1.00 - 0.15) * income;
                break;
            case income < 91900:
                adjusted = (1.00 - 0.25) * income;
                break;
            case income < 191650:
                adjusted = (1.00 - 0.33) * income;
                break;
            case income < 416700:
                adjusted = (1.00 - 0.35) * income;
                break;
            case income >= 416700:
                adjusted = (1.00 - 0.40) * income;
                break;
        };
    };
    return adjusted;
};

afterTaxes(150000, "single");


问:
Apple Production Push Notification certificate do not connect after new app version
After We uploaded new version of app on App store, apple push notification certificate for production mode stopped connecting with apple server.

I created new certificate on apple developer account and it started working. Again when we uploaded new version of the app, it stopped connecting with apple server.

Is it default behavior for IOS or I am doing something wrong?

I am using PHP for sending push notification.

答:
According to your comment, if you have used that same distribution certificate then some how in your compatibility section the push notifications entitlement hasn't connected, i have the same situation once, it was showing check mark, but i turn that off and again on then it asks me to select the profile, i did as option populated, and it works, i hadn't created the new certificate again, i use php too for push notification . So you have to make sure before uploading your app.
Thanks</p>


问:
clear javascript console in Google Chrome
I was wondering if I could clear up the console with some command..

console.log(), can print... is there a command to clear up console?..

I've tried to console.log(console); and got this functions below...

```<code>assert: function assert() { [native code] }
constructor: function Console() { [native code] }
count: function count() { [native code] }
debug: function debug() { [native code] }
dir: function dir() { [native code] }
dirxml: function dirxml() { [native code] }
error: function error() { [native code] }
group: function group() { [native code] }
groupEnd: function groupEnd() { [native code] }
info: function info() { [native code] }
log: function log() { [native code] }
markTimeline: function markTimeline() { [native code] }
profile: function profile() { [native code] }
profileEnd: function profileEnd() { [native code] }
time: function time() { [native code] }
timeEnd: function timeEnd() { [native code] }
trace: function trace() { [native code] }
warn: function warn() { [native code] }
__proto__: Object
</code>```

[ I guess there's no way to clear up the console... but I wanted someone to say it to me... ]

答:
Instead of typing command just press:

```<code>CLTRL + L
</code>```

to clear chrome console

Body:
I was wondering if I could clear up the console with some command..

console.log(), can print... is there a command to clear up console?..

I've tried to console.log(console); and got this functions below...

assert: function assert() { [native code] }
constructor: function Console() { [native code] }
count: function count() { [native code] }
debug: function debug() { [native code] }
dir: function dir() { [native code] }
dirxml: function dirxml() { [native code] }
error: function error() { [native code] }
group: function group() { [native code] }
groupEnd: function groupEnd() { [native code] }
info: function info() { [native code] }
log: function log() { [native code] }
markTimeline: function markTimeline() { [native code] }
profile: function profile() { [native code] }
profileEnd: function profileEnd() { [native code] }
time: function time() { [native code] }
timeEnd: function timeEnd() { [native code] }
trace: function trace() { [native code] }
warn: function warn() { [native code] }
__proto__: Object

[ I guess there's no way to clear up the console... but I wanted someone to say it to me... ]

Body:
Instead of typing command just press:

CLTRL + L

to clear chrome console


问:
How to open Microphone properties window
How do I open the microphone properties window when I click a button?</p>

答:
For Windows XP, starting sndvol32.exe will open the mixer. If you pass "-R" in as parameter, it will take you directly to the "Recording View", where you can set microphone gain.

```<code>sndvol32.exe -R
</code>```

Unfortunately this will not work in Windows 7. Win 7 has a program called sndvol.exe but it doesn't seem to have a record settings mode. The best solution I have found is to open up the Sound control panel item with the Recording tab active using the following command:

```<code>control mmsys.cpl,,1
</code>```

Body:
For Windows XP, starting sndvol32.exe will open the mixer. If you pass "-R" in as parameter, it will take you directly to the "Recording View", where you can set microphone gain.

sndvol32.exe -R

Unfortunately this will not work in Windows 7. Win 7 has a program called sndvol.exe but it doesn't seem to have a record settings mode. The best solution I have found is to open up the Sound control panel item with the Recording tab active using the following command:

control mmsys.cpl,,1


问:
How to have every instance of character typed in bold in filter as you type list?
As an example, if I have 'vegetables' in my list and I type a letter 'e', all three letter 'e's in 'vegetables' should become bold. I have played around with the code at the fiddles I found on the web below, but with them, I can only get the beginning of the words bold or the middle of words.

https://jsfiddle.net/ku5zv3dz/

```<code>      var inputId   = 'mytextbox';
var itemsData   = 'value';
var displaySet = false;
var displayArr = [];

function getDisplayType(element) {
    var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
    return elementStyle.display;
}

document.getElementById(inputId).onkeyup = function() {
  var currval = this.value;
    var searchVal = this.value.toLowerCase();
    var filterItems = document.querySelectorAll('[' + itemsData + ']');
    for(var i = 0; i < filterItems.length; i++) {
        if (!displaySet) {
            displayArr.push(getDisplayType(filterItems[i]));
        }
    var textcontent = filterItems[i].textContent;
    var replacedval = "<strong>"+currval+"</strong>"
    var finalval = textcontent.replace(currval, replacedval);
   filterItems[i].innerHTML = finalval;
        filterItems[i].style.display = 'none';
        if(filterItems[i].getAttribute('value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
            filterItems[i].style.display = displayArr[i];
        }
    }
    displaySet = true;
}
</code>```

http://jsfiddle.net/noth1ng/ytYQd/

```<code>      $('#mytextbox').keyup(function () {
    var valThis = this.value.toLowerCase(),
        length  = this.value.length;

    $('#mydropdown>option').each(function () {
        var text  = $(this).text(),
            textL = text.toLowerCase(),
            htmlR = '<b>' + text.substr(0, length) + '</b>' + text.substr(length);
        (textL.indexOf(valThis) == 0) ? $(this).html(htmlR).show() : $(this).hide();
    });

});
</code>```

This is the original code before trying to add the feature for bold:

```<code>jQuery.fn.filterByText = function(mytextbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(mydropdown).find('option').each(function() {
      options.push({
        value: $(this).val(),
        text: $(this).text()
      });
    });
    $(mydropdown).data('options', options);
    $(mytextbox).bind('change keyup', function() {
      var options = $(mydropdown).empty().data('options');
      var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
      var regex = new RegExp(search, "gi");

      $.each(options, function(i) {
        var option = options[i];
        if (option.text.match(regex) !== null) {
          $(mydropdown).append(
            $('<option>').text(option.text).val(option.value)
          );
        }
      });

    });
  });
};
</code>```

答:
I used the valThis to create the RegExp and use the replace method to replace all occurrences with the bold value.

```<code>$('#box').keyup(function () {
var valThis = this.value.toLowerCase(),
    lenght  = this.value.length;

    $('.navList>li').each(function () {
        var text  = $(this).text(),
            textL = text.toLowerCase();

        var replace = "(" + valThis + ")";
        var re = new RegExp(replace,"g");

        textL = textL.replace(re,"<b>" + valThis + "</b>");

        $(this).html(textL);
    });

});
</code>```

http://jsfiddle.net/54rya8p4/

Body:
As an example, if I have 'vegetables' in my list and I type a letter 'e', all three letter 'e's in 'vegetables' should become bold. I have played around with the code at the fiddles I found on the web below, but with them, I can only get the beginning of the words bold or the middle of words.

https://jsfiddle.net/ku5zv3dz/

      var inputId   = 'mytextbox';
var itemsData   = 'value';
var displaySet = false;
var displayArr = [];

function getDisplayType(element) {
    var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
    return elementStyle.display;
}

document.getElementById(inputId).onkeyup = function() {
  var currval = this.value;
    var searchVal = this.value.toLowerCase();
    var filterItems = document.querySelectorAll('[' + itemsData + ']');
    for(var i = 0; i < filterItems.length; i++) {
        if (!displaySet) {
            displayArr.push(getDisplayType(filterItems[i]));
        }
    var textcontent = filterItems[i].textContent;
    var replacedval = ""+currval+""
    var finalval = textcontent.replace(currval, replacedval);
   filterItems[i].innerHTML = finalval;
        filterItems[i].style.display = 'none';
        if(filterItems[i].getAttribute('value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
            filterItems[i].style.display = displayArr[i];
        }
    }
    displaySet = true;
}

http://jsfiddle.net/noth1ng/ytYQd/

      $('#mytextbox').keyup(function () {
    var valThis = this.value.toLowerCase(),
        length  = this.value.length;

    $('#mydropdown>option').each(function () {
        var text  = $(this).text(),
            textL = text.toLowerCase(),
            htmlR = '' + text.substr(0, length) + '' + text.substr(length);
        (textL.indexOf(valThis) == 0) ? $(this).html(htmlR).show() : $(this).hide();
    });

});

This is the original code before trying to add the feature for bold:

jQuery.fn.filterByText = function(mytextbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(mydropdown).find('option').each(function() {
      options.push({
        value: $(this).val(),
        text: $(this).text()
      });
    });
    $(mydropdown).data('options', options);
    $(mytextbox).bind('change keyup', function() {
      var options = $(mydropdown).empty().data('options');
      var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
      var regex = new RegExp(search, "gi");

      $.each(options, function(i) {
        var option = options[i];
        if (option.text.match(regex) !== null) {
          $(mydropdown).append(
            $('<option>').text(option.text).val(option.value)
          );
        }
      });

    });
  });
};

Body:
I used the valThis to create the RegExp and use the replace method to replace all occurrences with the bold value.

$('#box').keyup(function () {
var valThis = this.value.toLowerCase(),
    lenght  = this.value.length;

    $('.navList>li').each(function () {
        var text  = $(this).text(),
            textL = text.toLowerCase();

        var replace = "(" + valThis + ")";
        var re = new RegExp(replace,"g");

        textL = textL.replace(re,"<b>" + valThis + "</b>");

        $(this).html(textL);
    });

});

http://jsfiddle.net/54rya8p4/


问:
Can I give an intermediate string to fetch from mysql table which values has that string in middle?
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

```<code>Select *
from orders
where date = "%03%"
</code>```

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

答:
To fetch the value just by the position of the characters, use something like this:

```<code>SELECT * FROM `orders` WHERE `date` LIKE "__03____"
</code>```

From the docs:

_ matches exactly one character.

Whereas

% matches any number of characters, even zero characters.

The latter would be invalid in your case - as you will have the issue you already experienced in that it will match anywhere in the string.

Body:
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

Select *
from orders
where date = "%03%"

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

Body:
To fetch the value just by the position of the characters, use something like this:

SELECT * FROM `orders` WHERE `date` LIKE "__03____"

From the docs:

_ matches exactly one character.

Whereas

% matches any number of characters, even zero characters.

The latter would be invalid in your case - as you will have the issue you already experienced in that it will match anywhere in the string.


问:
Segmentation fault in C not occuring
Wikipedia gives below example

```<code>#include <stdio.h>
int main()
{
char *p2;
*p2='b';
return 0;

}
</code>```

and says it should cause Segmentation fault ,quoting below reason

Here, p2 may point to anywhere in memory, so performing the assignment *p2 = 'b'; can corrupt an unknown area of memory or trigger a segmentation fault.

But while running this in Atom ,i am not getting any error.I am getting blank command prompt

Any ideas on this

答: as you mentioned, p2 can point anywhere. you get a segmentation fault error when you try to modify the part of memory that does not belong to the memory that the OS has given to you to run your program. so if you don't get a seg fault it means that this pointer is pointing to an address that belongs to your memory. if you repeat running this code, you may get a seg fault.</p>

Title: Segmentation fault in C not occuring

Body:
Wikipedia gives below example

#include <stdio.h>
int main()
{
char *p2;
*p2='b';
return 0;

}

and says it should cause Segmentation fault ,quoting below reason

Here, p2 may point to anywhere in memory, so performing the assignment *p2 = 'b'; can corrupt an unknown area of memory or trigger a segmentation fault.

But while running this in Atom ,i am not getting any error.I am getting blank command prompt

Any ideas on this


问:
Fire a Google DoubleClick tag when a user submits the form
I have a custom web form on my page, I'm trying to fire a Google DoubleClick tag when a user submits the form successfully (next page is a payment gateway so I can't drop a tag on this page unfortunately)

The form has the validation:

```<code>function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
return true;
}
</code>```

I am wondering if anyone has experience of firing a submit rule on this kind of form?

Thanks

答:
Since the validation returns true, a standard GTM Form Submit Trigger should work fine as after the JS is done it still submits the form "normally" as opposed to a JS submit like this.submit.

Alternatively, if you have easy access to that JS, just add this to it before the return true:

```<code>window.dataLayer = window.dataLayer || [];
dataLayer.push({'event':'form_submit'});
</code>```

and then make a Custom Event Trigger that looks for the form_submit event as a firing trigger to your DoubleClick Tag.

Body:
I have a custom web form on my page, I'm trying to fire a Google DoubleClick tag when a user submits the form successfully (next page is a payment gateway so I can't drop a tag on this page unfortunately)

The form has the validation:

function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
return true;
}

I am wondering if anyone has experience of firing a submit rule on this kind of form?

Thanks

Body:
Since the validation returns true, a standard GTM Form Submit Trigger should work fine as after the JS is done it still submits the form "normally" as opposed to a JS submit like this.submit.

Alternatively, if you have easy access to that JS, just add this to it before the return true:

window.dataLayer = window.dataLayer || [];
dataLayer.push({'event':'form_submit'});

and then make a Custom Event Trigger that looks for the form_submit event as a firing trigger to your DoubleClick Tag.


问:
Get rid of foreign git branch
I have a git project where I just have a master branch. Sometime in the past I cloned pandas somewhere in a subfolder and then deleted it. Since then I have a separate branch with plenty of pandas history. How can I get rid of it? It seems to be on a separate branch, but the branch isn't mentioned anywhere.

I tried to see if the specific commits, which I can see in sourcetree, can be assinged to a branch, but no output
it branch --contains 58199c5da263491a26fa6cb26d2ff9d38c4b5dac

Any suggestions how to get rid of that branch is appreciated.

You can see above the pink branch is not from me. How can I delete it? This is my repo: https://github.com/dickreuter/poker

答: is it a tag? git tag -d <tagname> would get rid of it locally. But perhaps it was someone else who created it and you got it from a fetch.

Title: Get rid of foreign git branch


问:
Cordova- Push notification firebase not coming in status bar but Working in android
I m adding firebase to my cordova project. I have problem with push notification, The notification is printed into the console when it is running. but not coming to notification bar..

Any idea about this.. do i need to add any other delegate methods..

I m getting log -> FCM connected and when app enters background log ->
  FCM Disconnected

```<code>- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    self.window.autoresizesSubviews = YES;

    // only set if not already set in subclass
    if (self.viewController == nil) {
        self.viewController = [[CDVViewController alloc] init];
    }

    // Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.
    // If necessary, uncomment the line below to override it.
    // self.viewController.startPage = @"index.html";

    // NOTE: To customize the view's frame size (which defaults to full screen), override
    // [self.viewController viewWillAppear:] in your view controller.

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    // [self saveDeviceTokenAPI:@"83a86eb457edd131a2ace741e1214d988482dd3618f8858e1dba736e1900c733"];

    if  ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        NSLog(@"My token is......: ");

        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [application registerForRemoteNotifications];
    }
    else
    {
        NSLog(@"My token is: ");

        // iOS < 8 Notifications
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

    return YES;
}

#pragma  mark :-  Push Starts here

#pragma mark- Push Notification Delegate Methods

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);

    NSString * deviceTokenString = [[[[deviceToken description]
                                      stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                                    stringByReplacingOccurrencesOfString: @" " withString: @""];

    NSLog(@"the generated device token string is : %@",deviceTokenString);

  //  [self saveDeviceTokenAPI:deviceTokenString];

    [[NSUserDefaults standardUserDefaults]setObject:deviceTokenString forKey:@"deviceToken"];

    NSLog(@"the generated device token from User defaluts : %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"deviceToken"]);

}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

#pragma  mark  for Push End here

// this happens while we are running ( in the background, or from within our own app )
// only valid if 40x-Info.plist specifies a protocol to handle
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    if (!url) {
        return NO;
    }

    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];

    return YES;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#else
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#endif
{
    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
    NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);

    return supportedInterfaceOrientations;
}
</code>```

答:
Try this function:

```<code>- (void)launchRemoteNotificationInForegroundWithUserInfo:(NSDictionary *)userInfo {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date];
    notification.timeZone = [NSTimeZone localTimeZone];
    notification.repeatInterval = 0;
    notification.alertTitle = userInfo[@"aps"][@"alert"][@"body"];
    notification.alertBody = userInfo[@"aps"][@"alert"][@"title"];
    notification.applicationIconBadgeNumber = 1;
    notification.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:userInfo[@"aps"][@"alert"][@"title"]
                              message:userInfo[@"aps"][@"alert"][@"body"]
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];

    [alertView show];
}
</code>```

and call it in

```<code>didReceiveRemoteNotification:
</code>```

Body:
I m adding firebase to my cordova project. I have problem with push notification, The notification is printed into the console when it is running. but not coming to notification bar..

Any idea about this.. do i need to add any other delegate methods..

I m getting log -> FCM connected and when app enters background log ->
  FCM Disconnected

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    self.window.autoresizesSubviews = YES;

    // only set if not already set in subclass
    if (self.viewController == nil) {
        self.viewController = [[CDVViewController alloc] init];
    }

    // Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.
    // If necessary, uncomment the line below to override it.
    // self.viewController.startPage = @"index.html";

    // NOTE: To customize the view's frame size (which defaults to full screen), override
    // [self.viewController viewWillAppear:] in your view controller.

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    // [self saveDeviceTokenAPI:@"83a86eb457edd131a2ace741e1214d988482dd3618f8858e1dba736e1900c733"];

    if  ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        NSLog(@"My token is......: ");

        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [application registerForRemoteNotifications];
    }
    else
    {
        NSLog(@"My token is: ");

        // iOS < 8 Notifications
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

    return YES;
}

#pragma  mark :-  Push Starts here

#pragma mark- Push Notification Delegate Methods

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);

    NSString * deviceTokenString = [[[[deviceToken description]
                                      stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                                    stringByReplacingOccurrencesOfString: @" " withString: @""];

    NSLog(@"the generated device token string is : %@",deviceTokenString);

  //  [self saveDeviceTokenAPI:deviceTokenString];

    [[NSUserDefaults standardUserDefaults]setObject:deviceTokenString forKey:@"deviceToken"];

    NSLog(@"the generated device token from User defaluts : %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"deviceToken"]);

}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

#pragma  mark  for Push End here

// this happens while we are running ( in the background, or from within our own app )
// only valid if 40x-Info.plist specifies a protocol to handle
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    if (!url) {
        return NO;
    }

    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];

    return YES;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#else
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#endif
{
    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
    NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);

    return supportedInterfaceOrientations;
}

Body:
Try this function:

- (void)launchRemoteNotificationInForegroundWithUserInfo:(NSDictionary *)userInfo {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date];
    notification.timeZone = [NSTimeZone localTimeZone];
    notification.repeatInterval = 0;
    notification.alertTitle = userInfo[@"aps"][@"alert"][@"body"];
    notification.alertBody = userInfo[@"aps"][@"alert"][@"title"];
    notification.applicationIconBadgeNumber = 1;
    notification.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:userInfo[@"aps"][@"alert"][@"title"]
                              message:userInfo[@"aps"][@"alert"][@"body"]
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];

    [alertView show];
}

and call it in

didReceiveRemoteNotification:


问:
Echo String dont work properly
I'm using cakePHP 2.x. I'm trying to render a view with an empty layout. The view should contain only a string returned from the action controller with no html code.
Here is the code:

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

     $ref =null;$act=null;$par=null;

     $this->layout = false;
     //$this->render(false);

     //$priceCTP = $this->Session->read('priceCTP');;
     $priceCTP = $this->getPrice();
     //var_dump(session_save_path());

     if (isset($this->params['url']['Reference'])) {
         $ref = $this->params['url']['Reference'];
     }
     if (isset($this->params['url']['Action'])) {
         $act = $this->params['url']['Action'];
     }
     if (isset($this->params['url']['Param'])) {
         $par = $this->params['url']['Param'];//$_GET['Param'];//this->request->params['named']
     }
     switch ($act) {
         case "DETAIL":// accéder à la base et récuperer le montant
             echo "Reference=".$ref."&Action=".$act."&Reponse=".$priceCTP;
             break;
         case "ERREUR": // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "ACCORD": // accéder à la base, enregistrer le numéro d’autorisation (dans param)
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "REFUS":  // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "ANNULATION":  // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
     }
}
</code>```

the result on this url(http://mydomain/orders/checkout?

```<code>Reference=123&Action=DETAIL&Param=)

"Reference=123&Action=DETAIL&Repon"
rather than
"Reference=123&Action=DETAIL&Reponse=121,630" (works fine on localhost).
</code>```

答:
Do not echo data from controllers

As mentioned in the comments, controller actions are not supposed to echo data, even though it might work in some, maybe even most situations. The correct way of outputting data is by using (data) views, by configuring and return the response object, or even returning a string (which however isn't forward compatible with future versions of CakePHP).

Echoing data can lead to all kinds of problems, from the data not being recognized in the test environment, to headers not being able to be sent, and even data being cut off, which is what you are experiencing. The latter can for example happen when the size sent in the Content-Length header doesn't match the actual size of the data being sent, this often happens in situations where the content is being gzipped.

Content-Length mismatch is likely the cause

If you've run into the length mismatch for gzipped responses problem, then you have to figure out where compression is being involved (on server level (for example mod_deflate), on PHP extension level (for example zlib), on PHP code level (for example CakeResponse::compress())), and why it doesn't set the proper length accordingly.

Proper controller action logic

That being said, just pass the required data to the view, and build and echo the reponse data from there. Given that you don't want to respond with HTML, you probably also want to set the response type accordingly:

```<code>public function checkout()
{
    $this->response->type('text'); // = text/plain

    // ...

    $this->set(compact(array('priceCTP', 'ref', 'act', 'par')));
}
</code>```

As mentioned, another option would be to return a proper response object:

```<code>public function checkout()
{
    $this->response->type('text');

    // ...

    $body = "Reference=" . $ref . "&Action=" . $act . "&Reponse=";
    switch ($act) {
        case "DETAIL":
            $body .= $priceCTP;
            break;

        case "ERREUR":
        case "ACCORD":
        case "REFUS":
        case "ANNULATION":
            $body .= "OK";
            break;

        // ...
    }

    // ...

    $this->response->body($body);
    return $this->response;
}
</code>```

ps. do you really want to respond with a key in french? Reponse maybe should be Response.

pps. given that you respond with a query string, you may want/need to URL encode the values accordingly.

See also

Cookbook > Controllers > Controller actions

Cookbook > Controllers > Request > Request and Response objects > CakeResponse > Dealing with content types

Title: Echo String dont work properly

Body:
I'm using cakePHP 2.x. I'm trying to render a view with an empty layout. The view should contain only a string returned from the action controller with no html code.
Here is the code:

 public function checkout(){

     $ref =null;$act=null;$par=null;

     $this->layout = false;
     //$this->render(false);

     //$priceCTP = $this->Session->read('priceCTP');;
     $priceCTP = $this->getPrice();
     //var_dump(session_save_path());

     if (isset($this->params['url']['Reference'])) {
         $ref = $this->params['url']['Reference'];
     }
     if (isset($this->params['url']['Action'])) {
         $act = $this->params['url']['Action'];
     }
     if (isset($this->params['url']['Param'])) {
         $par = $this->params['url']['Param'];//$_GET['Param'];//this->request->params['named']
     }
     switch ($act) {
         case "DETAIL":// accéder à la base et récuperer le montant
             echo "Reference=".$ref."&Action=".$act."&Reponse=".$priceCTP;
             break;
         case "ERREUR": // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "ACCORD": // accéder à la base, enregistrer le numéro d’autorisation (dans param)
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "REFUS":  // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
         case "ANNULATION":  // accéder à la base et mettre à jour l’état de la transaction
             echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
             break;
     }
}

the result on this url(http://mydomain/orders/checkout?

Reference=123&Action=DETAIL&Param=)

"Reference=123&Action=DETAIL&Repon"
rather than
"Reference=123&Action=DETAIL&Reponse=121,630" (works fine on localhost).

Body:
Do not echo data from controllers

As mentioned in the comments, controller actions are not supposed to echo data, even though it might work in some, maybe even most situations. The correct way of outputting data is by using (data) views, by configuring and return the response object, or even returning a string (which however isn't forward compatible with future versions of CakePHP).

Echoing data can lead to all kinds of problems, from the data not being recognized in the test environment, to headers not being able to be sent, and even data being cut off, which is what you are experiencing. The latter can for example happen when the size sent in the Content-Length header doesn't match the actual size of the data being sent, this often happens in situations where the content is being gzipped.

Content-Length mismatch is likely the cause

If you've run into the length mismatch for gzipped responses problem, then you have to figure out where compression is being involved (on server level (for example mod_deflate), on PHP extension level (for example zlib), on PHP code level (for example CakeResponse::compress())), and why it doesn't set the proper length accordingly.

Proper controller action logic

That being said, just pass the required data to the view, and build and echo the reponse data from there. Given that you don't want to respond with HTML, you probably also want to set the response type accordingly:

public function checkout()
{
    $this->response->type('text'); // = text/plain

    // ...

    $this->set(compact(array('priceCTP', 'ref', 'act', 'par')));
}

As mentioned, another option would be to return a proper response object:

public function checkout()
{
    $this->response->type('text');

    // ...

    $body = "Reference=" . $ref . "&Action=" . $act . "&Reponse=";
    switch ($act) {
        case "DETAIL":
            $body .= $priceCTP;
            break;

        case "ERREUR":
        case "ACCORD":
        case "REFUS":
        case "ANNULATION":
            $body .= "OK";
            break;

        // ...
    }

    // ...

    $this->response->body($body);
    return $this->response;
}

ps. do you really want to respond with a key in french? Reponse maybe should be Response.

pps. given that you respond with a query string, you may want/need to URL encode the values accordingly.

See also

Cookbook > Controllers > Controller actions

Cookbook > Controllers > Request > Request and Response objects > CakeResponse > Dealing with content types