问:
mongorestore always returns connection error
I have successfully performed a mongodump command of my Heroku server with an mLab database.
This is the code i used:

```<code>mongodump --host <thehost> -d <thedb> -u <username> -p <password>
--port 27175
</code>```

The dump completed successfully.

Now i am trying to restore this dump on my local server, but no luck.
This error shows

```<code> Failed: error connecting to db server: no reachable servers
</code>```

Restoration Codes That I Have Tried:

```<code>mongorestore --db newdb /path/todump/file

mongorestore --db newdb

mongorestore  /path/todump/file

mongorestore --db newdb (run it inside the dump folder)

--host mongodb://[server-ip] --port [running-port] --db newdb /path/to/dump
</code>```

I have also tried running in from my mac.
i performed the dump on my personal computer.
And then ran.

```<code>mongorestore --host mongodb://[server-real-ip] --port [running-port] --db newdb /path/to/dump
</code>```

Also the weird thing i that performing [mongo] locally or via the internet gives me access to the shell successfully without any error.

```<code>mongo --host mongodb://[server-real-ip] --port [running-port]
</code>```

I searched every where, and tried almost every possible solution i could find.
What am i doing wrong ?

答:
For anyone else who is just trying out and might make a more careless error than this,
I had included the database name in the host input, while leaving the database flag there too. So just make sure the host and database are specified accurately.</p>

Body:
I have successfully performed a mongodump command of my Heroku server with an mLab database.
This is the code i used:

mongodump --host <thehost> -d <thedb> -u <username> -p <password>
--port 27175

The dump completed successfully.

Now i am trying to restore this dump on my local server, but no luck.
This error shows

 Failed: error connecting to db server: no reachable servers

Restoration Codes That I Have Tried:

mongorestore --db newdb /path/todump/file

mongorestore --db newdb

mongorestore  /path/todump/file

mongorestore --db newdb (run it inside the dump folder)

--host mongodb://[server-ip] --port [running-port] --db newdb /path/to/dump

I have also tried running in from my mac.
i performed the dump on my personal computer.
And then ran.

mongorestore --host mongodb://[server-real-ip] --port [running-port] --db newdb /path/to/dump

Also the weird thing i that performing [mongo] locally or via the internet gives me access to the shell successfully without any error.

mongo --host mongodb://[server-real-ip] --port [running-port]

I searched every where, and tried almost every possible solution i could find.
What am i doing wrong ?


来源: stackexchange

问:
Is there a way to make it look like two programs are listening to port 80
I do know that I can't have two programs listening to the same port, but I am wondering if it is possible to fake it somehow, for an example:

My machine has two applications, one listening to port 80 and the other to port 6653.

If I get an incoming connection, let's say mysite.com:80/chat then it would be forwarded internally to the application listening on port 6653 and the data returned from that server would be forwarded back to port 80 somehow.

The reason I want to accomplish this is because there are many firewalls that seem to block connections to ports other than 80.

I have a chat server that I want to run on port 80, perhaps I could get another IP and machine for that, but it feels like too much trouble for a single chat server.

Any helpful feedback would be appreciated. Thanks!

答:
You can probably do this with mod_rewrite if you're running Apache. That link has plenty of examples, including what you want (I think).

EDIT: I see you've updated the tags to say "asp.net". I'm guessing that you're not running Apache, then. I'm sure there is a similar tool for IIS, or you can use a proxy server that does the same thing.

ContentLicense: CC BY-SA 2.5


问:
Opening the youngest file in a folder VBA
Hi I am trying to open the latest file (date modified) in a folder. The code uses a loop to go through the files and find the latest modified which it does however when it comes to open the file using 'Workbooks.Open strFilename' it says the file (which it has already identified as the 'youngest' file could not be found. This doesn't make sense to me as the error message says the file 'test young' - the file name could not be found, but it clearly found it during the loop.

```<code>Sub copynewdata()

Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date

Dim Ref As Object, CheckRefEnabled%
CheckRefEnabled = 0
With ThisWorkbook
    For Each Ref In .VBProject.References
        If Ref.Name = "Scripting" Then
            CheckRefEnabled = 1
            Exit For
        End If
    Next Ref
    If CheckRefEnabled = 0 Then
        .VBProject.References.AddFromGUID "{420B2830-E718-11CF-893D-00A0C9054228}", 1, 0
    End If
End With

'set path for files - change for your folder
Const myDir As String = "\\C:\Test"

'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)

'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
    If objFile.DateLastModified > dteFile Then
        dteFile = objFile.DateLastModified
        strFilename = objFile.Name
    End If
Next objFile
Workbooks.Open strFilename
'Set Source_Workbook = Workbooks(strFilename).Open(Target_Path)

Set FileSys = Nothing
Set myFolder = Nothing
</code>```

End Sub

Can anyone help with this?

答:
In strFilename, you have the name of the file - but without the path. Change the open-command to

Workbooks.Open myDir & "\" & strFilename

ContentLicense: CC BY-SA 3.0

Body:
Hi I am trying to open the latest file (date modified) in a folder. The code uses a loop to go through the files and find the latest modified which it does however when it comes to open the file using 'Workbooks.Open strFilename' it says the file (which it has already identified as the 'youngest' file could not be found. This doesn't make sense to me as the error message says the file 'test young' - the file name could not be found, but it clearly found it during the loop.

Sub copynewdata()

Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date

Dim Ref As Object, CheckRefEnabled%
CheckRefEnabled = 0
With ThisWorkbook
    For Each Ref In .VBProject.References
        If Ref.Name = "Scripting" Then
            CheckRefEnabled = 1
            Exit For
        End If
    Next Ref
    If CheckRefEnabled = 0 Then
        .VBProject.References.AddFromGUID "{420B2830-E718-11CF-893D-00A0C9054228}", 1, 0
    End If
End With

'set path for files - change for your folder
Const myDir As String = "\\C:\Test"

'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)

'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
    If objFile.DateLastModified > dteFile Then
        dteFile = objFile.DateLastModified
        strFilename = objFile.Name
    End If
Next objFile
Workbooks.Open strFilename
'Set Source_Workbook = Workbooks(strFilename).Open(Target_Path)

Set FileSys = Nothing
Set myFolder = Nothing

End Sub

Can anyone help with this?


问:
CakePHP3 After removal of afterFind, where to check if query result empty?
Before i checked in the afterFind callback if the result of the find is empty.
Since the callback was removed in latest versions, where would be the place to check that from a behavior?

Im not realy sure if that is what i need. My use case is, i want to find out if a query has no result. Then i would create a default entry so it has 1 result.

答:
https://book.cakephp.org/3.0/en/appendices/orm-migration.html#no-afterfind-event-or-virtual-fields

Once defined you can access your new property using $user->full_name. Using the Modifying Results with Map/Reduce features of the ORM allow you to build aggregated data from your results, which is another use case that the afterFind callback was often used for.

Call count() on the ResultSet object

https://api.cakephp.org/3.4/class-Cake.ORM.ResultSet.html#_count

No idea why you're not using that and want to do the count manually, but go on.

Using resultFormatter()

https://book.cakephp.org/3.0/en/orm/query-builder.html#adding-calculated-fields

You behavior will have to add the formatter in your beforeFind() to the query. You can add a custom find that adds it as well. Example code (taken from the docs):

```<code>$query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
    return $results->map(function ($row) {
        $row['age'] = $row['birth_date']->diff(new \DateTime)->y;
        return $row;
    });
});
</code>```

Count the results there.

Using map/reduce

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#map-reduce

More often than not, find operations require post-processing the data that is found in the database. While entities’ getter methods can take care of most of the virtual property generation or special data formatting, sometimes you need to change the data structure in a more fundamental way.

You behavior will have to add the mapper/reducer in your beforeFind() to the query. You can add a custom find that adds it as well. Example code (taken from the docs):

```<code>$articlesByStatus = $articles->find()
    ->where(['author_id' => 1])
    ->mapReduce($mapper, $reducer);
</code>```

Check the above link for a detailed explanation including examples of how to create a mapper and reducer.

Body:
https://book.cakephp.org/3.0/en/appendices/orm-migration.html#no-afterfind-event-or-virtual-fields

Once defined you can access your new property using $user->full_name. Using the Modifying Results with Map/Reduce features of the ORM allow you to build aggregated data from your results, which is another use case that the afterFind callback was often used for.

Call count() on the ResultSet object

https://api.cakephp.org/3.4/class-Cake.ORM.ResultSet.html#_count

No idea why you're not using that and want to do the count manually, but go on.

Using resultFormatter()

https://book.cakephp.org/3.0/en/orm/query-builder.html#adding-calculated-fields

You behavior will have to add the formatter in your beforeFind() to the query. You can add a custom find that adds it as well. Example code (taken from the docs):

$query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
    return $results->map(function ($row) {
        $row['age'] = $row['birth_date']->diff(new \DateTime)->y;
        return $row;
    });
});

Count the results there.

Using map/reduce

https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#map-reduce

More often than not, find operations require post-processing the data that is found in the database. While entities’ getter methods can take care of most of the virtual property generation or special data formatting, sometimes you need to change the data structure in a more fundamental way.

You behavior will have to add the mapper/reducer in your beforeFind() to the query. You can add a custom find that adds it as well. Example code (taken from the docs):

$articlesByStatus = $articles->find()
    ->where(['author_id' => 1])
    ->mapReduce($mapper, $reducer);

Check the above link for a detailed explanation including examples of how to create a mapper and reducer.


问:
Javascript RegEx : Match repeating character exactly twice (ignore if it matches 3 times)
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

```<code>\{\{[^\{]([\s\S]+?)[^\}]\}\}
</code>```

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?

答:
You may use the following to extract the matches:

var s = "this is {{{ bad bob triple}}} a triple token {{bob double}} {{bob}} a double token {{{bad token}}  {{bad token}}}";
var rx = /(?:^|[^{]){{([^{}]*)}}(?!})/g;
var m, res=[];
while(m=rx.exec(s)) {
  res.push(m[1]);
}
console.log(res);```

See the regex demo here.

(?:^|[^{]) - either start of string or any char but {

{{ - double {

([^{}]*) - Group 1: any char but { and } zero or more times

}} - double }

(?!}) - not followed immediately with }.

Body:
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

\{\{[^\{]([\s\S]+?)[^\}]\}\}

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?

Body:
You may use the following to extract the matches:

var s = "this is {{{ bad bob triple}}} a triple token {{bob double}} {{bob}} a double token {{{bad token}}  {{bad token}}}";
var rx = /(?:^|[^{]){{([^{}]*)}}(?!})/g;
var m, res=[];
while(m=rx.exec(s)) {
  res.push(m[1]);
}
console.log(res);

See the regex demo here.

(?:^|[^{]) - either start of string or any char but {

{{ - double {

([^{}]*) - Group 1: any char but { and } zero or more times

}} - double }

(?!}) - not followed immediately with }.


问:
How can I make a printf function in c for my operating system without stdio?
I wanted to make a basic operating system in c and I wanted to make a printf
function.

```<code>void printf(char* str){
    (unsigned short*) VideoMemory = (unsigned short*) 0xb800;
    for(int i = 0; str[i] != '\0'; ++i)
        VideoMemory[i] = (VideoMemory[i] & 0xFF00) | str[i];
}

kmain()
{
    printf("Hello from kernel.");
}
</code>```

But when I compile it I get this error:

kernel.c:3:20: error: ‘VideoMemory’ undeclared (first use in this function)
  (unsigned short*) VideoMemory = (unsigned short*) 0xb800;

答:
You seem to target a real mode PC BIOS system.  Your definition for VideoMemory is incorrect. If your compiler uses 32-bit pointers in flat mode, try this:

```<code>void printf(char *str) {
    unsigned short *VideoMemory = (unsigned short*)0xb8000UL;
    for (int i = 0; str[i] != '\0'; ++i)
        VideoMemory[i] = (VideoMemory[i] & 0xFF00) | str[i];
}

void kmain() {
    printf("Hello from kernel.");
}
</code>```

Otherwise, with 16 bit ints and segmented pointers, you may need to use the far or __far keyword such as:

```<code>unsigned short far* VideoMemory = (unsigned short far*)0xb8000000UL;
</code>```

Note that it is a bad idea to define your own version of printf with different semantics than the standard function.  It creates confusion among programmers and the compiler might perform incorrect optimizations, such as converting printf calls to something else.  Call this function kputstr until you can make it handle formatting with variable argument lists, at which time you will rename it kprintf.

Body:
I wanted to make a basic operating system in c and I wanted to make a printf
function.

void printf(char* str){
    (unsigned short*) VideoMemory = (unsigned short*) 0xb800;
    for(int i = 0; str[i] != '\0'; ++i)
        VideoMemory[i] = (VideoMemory[i] & 0xFF00) | str[i];
}

kmain()
{
    printf("Hello from kernel.");
}

But when I compile it I get this error:

kernel.c:3:20: error: ‘VideoMemory’ undeclared (first use in this function)
  (unsigned short*) VideoMemory = (unsigned short*) 0xb800;

Body:
You seem to target a real mode PC BIOS system.  Your definition for VideoMemory is incorrect. If your compiler uses 32-bit pointers in flat mode, try this:

void printf(char *str) {
    unsigned short *VideoMemory = (unsigned short*)0xb8000UL;
    for (int i = 0; str[i] != '\0'; ++i)
        VideoMemory[i] = (VideoMemory[i] & 0xFF00) | str[i];
}

void kmain() {
    printf("Hello from kernel.");
}

Otherwise, with 16 bit ints and segmented pointers, you may need to use the far or __far keyword such as:

unsigned short far* VideoMemory = (unsigned short far*)0xb8000000UL;

Note that it is a bad idea to define your own version of printf with different semantics than the standard function.  It creates confusion among programmers and the compiler might perform incorrect optimizations, such as converting printf calls to something else.  Call this function kputstr until you can make it handle formatting with variable argument lists, at which time you will rename it kprintf.


问:
JS can't call function when content is dynamically added
Ok, I have this HTML:

```<code><td class="text-left"><button type="button" onclick="addImage('<?php echo $language['language_id']; ?>');" data-toggle="tooltip" title="<?php echo $button_banner_add; ?>" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></td>
</code>```

On click I call JS function addImage.

```<code><script type="text/javascript">
function addImage(language_id) {
html = '<td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';

$('#images' + language_id + ' tbody').append(html);
</script>
</code>```

After that I want to call function on this div

This function:

```<code><script type="text/javascript">
  $(function () {
    $('#datetimepicker1').datetimepicker();
  });
</script>
</code>```

But this div is dynamically added and I don't know, but the function is not running.

答:
For elements dynamically added, you must use event handlers like this:

```<code>someElement.addEventListener( "click", function() {
       //some code to run on click
});
</code>```

This should work for you then

Body:
Ok, I have this HTML:

<button type="button" onclick="addImage('<?php echo $language['language_id']; ?>');" data-toggle="tooltip" title="<?php echo $button_banner_add; ?>" class="btn btn-primary"></button>

On click I call JS function addImage.

After that I want to call function on this div

This function:

But this div is dynamically added and I don't know, but the function is not running.

Body:
For elements dynamically added, you must use event handlers like this:

someElement.addEventListener( "click", function() {
       //some code to run on click
});

This should work for you then


问:
Aws Elastic Beanstalk deploy Akka application
I have a simple akka Http Server:

```<code>import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.HttpApp
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.settings.ServerSettings
import com.typesafe.config.ConfigFactory

object MinimalHttpServer extends HttpApp {
  def route =
    pathPrefix("v1") {
      path("subscribe" / Segment) { id =>
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"<h1>Hello $id from Akka Http!</h1>"))
        } ~
        post {
          entity(as[String]) { entity =>
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"<b>Thanks $id for posting your message <i>$entity</i></b>"))
          }
        }
      }
    }
}

object MinimalHttpServerApplication extends App {
  MinimalHttpServer.startServer("localhost", 8088, ServerSettings(ConfigFactory.load))
}
</code>```

I use Sbt native Packager to build an universal zip. When I deploy my application to Aws Elastic Beanstalk, I receive this error:

[Instance: i-0a846978718d54d76] Command failed on instance. Return code: 1 Output: (TRUNCATED)...xml_2.11-1.0.5.jar Unable to launch application as the source bundle does not contain either a file named application.jar or a Procfile. Unable to launch application as the source bundle does not contain either a file named application.jar or a Procfile. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/01_configure_application.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.

Any Ideas? Thank You!

答:
It appears AWS Elastic Beanstalk expects your .zip to contain either a file named application.jar or a Procfile, and the zip created by sbt-native-packager does not look like that.

It appears sbt-native-packager does not have support for the format Elastic Beanstalk expects, though GitHub issue 632 shows some work done in that direction.

Body:
I have a simple akka Http Server:

import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.HttpApp
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.settings.ServerSettings
import com.typesafe.config.ConfigFactory

object MinimalHttpServer extends HttpApp {
  def route =
    pathPrefix("v1") {
      path("subscribe" / Segment) { id =>
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"
Hello $id from Akka Http!
"))
        } ~
        post {
          entity(as[String]) { entity =>
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"Thanks $id for posting your message $entity"))
          }
        }
      }
    }
}

object MinimalHttpServerApplication extends App {
  MinimalHttpServer.startServer("localhost", 8088, ServerSettings(ConfigFactory.load))
}

I use Sbt native Packager to build an universal zip. When I deploy my application to Aws Elastic Beanstalk, I receive this error:

[Instance: i-0a846978718d54d76] Command failed on instance. Return code: 1 Output: (TRUNCATED)...xml_2.11-1.0.5.jar Unable to launch application as the source bundle does not contain either a file named application.jar or a Procfile. Unable to launch application as the source bundle does not contain either a file named application.jar or a Procfile. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/01_configure_application.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.

Any Ideas? Thank You!


问:
MongoDb and java dao implementation
I would like to know if there is a way to implement the DAO design pattern to connect to a Nosql database (MongoDB) and do all the CRUD opérations.
In my research i found all the solutions are related to spring support for MongoDB but I am using only pure Java. </p>

答:
Have you tried using Morphia instead : https://mongodb.github.io/morphia/ Pretty much does the job.

Here's a quick tutorial : https://dzone.com/articles/using-morphia-map-java-objects

Title: MongoDb and java dao implementation


问:
How to manipulate an embedded player with time slider?
I am now using an embedded Windows Media Player (tutorial) and I can manipulate with time slider through Javascript. But then I discovered the Jlembed plugin for jQuery and thought it solves all my problems because of the different platforms, etc.

But after I spent a few hours in setting things up I relized that it does not have functions like  setCurrentTime or getCurrentTime and these functions are most important for my type of project.

Is there a way to achieve this functionallity with Jlembed?

答:
As far as I know, Windows Media Player does not support the type of interaction you're trying to achieve with it's embedded player. I did not include any javascript functions for Windows Media Player because it is not necessary. jlEmbed does not affect your ability to control the embedded player with javascript. So, if Windows Media Player supports a particular script, jlEmbed supports it also.

If there is a javascript API for WMP please point me in that direction and I will add better support for it, but I don't think it exists. However, if one does exist, jlEmbed will not prevent you from scripting as would normally be done.

I spent a great deal of time on the YouTube support, but only because I had to. Otherwise, it would have been much more difficult to control the YouTube player, which is the most popular and widely available media player on the web.

Only a small percentage of users will actually be able to use your embedded WMP presentation. The YouTube player is compatible with any browser that supports Flash. You would be better off creating a custom 'chromeless' YouTube player than using WMP for your presentation. An even better alternative would be to use Flash to make your video presentation.


问:
Google App Engine - JSONProperty vs Separate Model
Say I have a blog app with blog posts and comments. Lets say for the sake of argument that there can be a very large number of comments, big enough that a simple comments = StringProperty(repeated=True) would be insufficient.

Should I store the comments as a JSONProperty (serialized from python list):

```<code>class BlogPost(ndb.Model):
  title = ndb.StringProperty()
  description = ndb.TextProperty()
  comments = ndb.JSONProperty()
</code>```

Or should I create a separate Comment model altogether and store the corresponding blogpost's ID as a property:

```<code>class Comment(ndb.Model):
  text = ndb.TextProperty()
  blog_id = ndb.IntegerProperty()
  created = ndb.DateTimeProperty(auto_now_add=True)
</code>```

And I can query for all the comments of a specific blogpost as follows: query = Comment.query(Comment.blog_id==blog_id).order(-Comment.created)?

Is one approach preferable? Especially if comments could get very large > 1000.

答:
You definitely want a separate model for comments.

One reason is that entities are limited to 1MB in size.  If one post gets a huge number of comments, then you are in danger of exceeding the limit and your code would crash.

Another reason is that you want to consider read/write rates for entities and scalability.  If you use JSON, then you need update the BlogPost entity every time a comment is made.  If a lot of people are writing comments at the same time, then you will need transactions and have contention issues.  If you have a separate model for comments, then you can easily scale to a million comments per second!

Body:
Say I have a blog app with blog posts and comments. Lets say for the sake of argument that there can be a very large number of comments, big enough that a simple comments = StringProperty(repeated=True) would be insufficient.

Should I store the comments as a JSONProperty (serialized from python list):

class BlogPost(ndb.Model):
  title = ndb.StringProperty()
  description = ndb.TextProperty()
  comments = ndb.JSONProperty()

Or should I create a separate Comment model altogether and store the corresponding blogpost's ID as a property:

class Comment(ndb.Model):
  text = ndb.TextProperty()
  blog_id = ndb.IntegerProperty()
  created = ndb.DateTimeProperty(auto_now_add=True)

And I can query for all the comments of a specific blogpost as follows: query = Comment.query(Comment.blog_id==blog_id).order(-Comment.created)?

Is one approach preferable? Especially if comments could get very large > 1000.


问:
Wordpress single item dynamic content
Wordpress offers great customization for posts, pages and custom post types, but  the only thing I cant figure out is how to make a single item.

Let me give you an example: I have one image on my front page and I want it to be dynamic or maybe I have a telephone in the footer. How can I make them dynamically editable without hardcoding page/post IDs in the theme.

Is this possible without plugins?

答:
There are many ways you can do this. However for your use cases WordPress has the perfect built-in mechanism which is exactly meant for things like this. Widgets.

Most probably your Theme already has all dynamic areas which you may need registered. Go to

Design -> Widgets

and populate them.

This is how you do it with your own code.

Register a dynamic sidebar within your Theme:

```<code>add_action( 'widgets_init', 'my_sidebars' );

function my_sidebars() {
    register_sidebar( array(
        'name' => __( 'Foo', 'theme-slug' ),
        'id' => 'bar',
        'description' => __( 'I am in area XYZ.', 'theme-slug' ),
        'before_widget' => '<div>',
    'after_widget'  => '</div>',
    'before_title'  => '<h2 class="widgettitle">',
    'after_title'   => '</h2>',
    ) );
}
</code>```

Put this code where you want it to be:

```<code><div id="my_dynamic_content">
    <?php dynamic_sidebar( 'my-dynamic-content' ); ?>
</div>
</code>```

For 99 % of use cases the existing text widgets are enough. You can also install a Plugin for WYSIWYG widget or code your own widgets. Whatever you need is possible.

More information here:

https://codex.wordpress.org/WordPress_Widgets

Title: Wordpress single item dynamic content

Body:
There are many ways you can do this. However for your use cases WordPress has the perfect built-in mechanism which is exactly meant for things like this. Widgets.

Most probably your Theme already has all dynamic areas which you may need registered. Go to

Design -> Widgets

and populate them.

This is how you do it with your own code.

Register a dynamic sidebar within your Theme:

add_action( 'widgets_init', 'my_sidebars' );

function my_sidebars() {
    register_sidebar( array(
        'name' => __( 'Foo', 'theme-slug' ),
        'id' => 'bar',
        'description' => __( 'I am in area XYZ.', 'theme-slug' ),
        'before_widget' => '<div>',
    'after_widget'  => '</div>',
    'before_title'  => '<h2 class="widgettitle">',
    'after_title'   => '</h2>',
    ) );
}

Put this code where you want it to be:

<div id="my_dynamic_content">
    <?php dynamic_sidebar( 'my-dynamic-content' ); ?>
</div>

For 99 % of use cases the existing text widgets are enough. You can also install a Plugin for WYSIWYG widget or code your own widgets. Whatever you need is possible.

More information here:

https://codex.wordpress.org/WordPress_Widgets


问:
scala method with 2 generics where one can be inferred
I'm new to Scala.   I am writing a method which sends a request of type RQ to a server, and receives a response of type Response[RSP].  The simplified version:  I define a method to make a call:

```<code>def invoke[RQ, RSP](request: RQ): Response[RSP] = {....}
</code>```

When I invoke the method, all parameters can be inferred if I specify the type of the receiving variable, like this:

```<code>val result: Response[Double] = invoke("Hello")
</code>```

But if I just say invoke("Hello") without assigning it to anything, it won't compile. I have to supply the 2 generic types (e.g  invoke[String, Double]("Hello") ).  My question is:   The String can be inferred from the parameter.   Is there a way to write the call specifying only the RSP generic?  Something in the lines of : invoke[ , Double]("Hello")  ?

答:
No.

This is a feature that has been asked about a number of times. Future versions of Scala may support a syntax similar to named arguments for methods:

```<code>invoke[RSP = Double]("Hello")
</code>```

At the moment, there is nothing much you can do except restructure your code so that the method has only one type parameter, and the second comes from the surrounding context.

The more interesting question is: why do you even care about the return type if you just throw away the result anyway? It looks like your method violates the Command-Query Separation Principle. If your method simply returned Unit, you wouldn't need the second type parameter, and all would work fine. If you actually used the return value, the type inferencer would at least have a chance to infer the second type parameter from the context. But the fact that you have a type parameter for the return value but ignore the return value means that there is no context for the type inferencer to look at.

Body:
I'm new to Scala.   I am writing a method which sends a request of type RQ to a server, and receives a response of type Response[RSP].  The simplified version:  I define a method to make a call:

def invoke[RQ, RSP](request: RQ): Response[RSP] = {....}

When I invoke the method, all parameters can be inferred if I specify the type of the receiving variable, like this:

val result: Response[Double] = invoke("Hello")

But if I just say invoke("Hello") without assigning it to anything, it won't compile. I have to supply the 2 generic types (e.g  invoke[String, Double]("Hello") ).  My question is:   The String can be inferred from the parameter.   Is there a way to write the call specifying only the RSP generic?  Something in the lines of : invoke[ , Double]("Hello")  ?

Body:
No.

This is a feature that has been asked about a number of times. Future versions of Scala may support a syntax similar to named arguments for methods:

invoke[RSP = Double]("Hello")

At the moment, there is nothing much you can do except restructure your code so that the method has only one type parameter, and the second comes from the surrounding context.

The more interesting question is: why do you even care about the return type if you just throw away the result anyway? It looks like your method violates the Command-Query Separation Principle. If your method simply returned Unit, you wouldn't need the second type parameter, and all would work fine. If you actually used the return value, the type inferencer would at least have a chance to infer the second type parameter from the context. But the fact that you have a type parameter for the return value but ignore the return value means that there is no context for the type inferencer to look at.


问:
.htaccess to redirect specific index file when particular url is visited
I have one website url http://t8.example.info/home.html
I want to redirect this url to http://t8.example.info/index.php?id=802 when i open it in mobile version.
I dont want to redirect when it is open in desktop version. It should be open as it is in desktop version.

need a quick help.
Thanks in advance

答:
Don't know about htaccess but you can achieve it from javascript</p>

```<code>var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
  window.location = "http://t8.example.info/index.php?id=802";
}
</code>```

Body:
Don't know about htaccess but you can achieve it from javascript

var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
  window.location = "http://t8.example.info/index.php?id=802";
}


问:
Common Feature between Scala Trait ,Java Interface and Java Class
I am little confused about what the common feature does Scala trait and Java Interface have? Also what is common feature present in Scala trait and Java Class have but not present in Java Interface ?

答: Starting Java 8, you can define "default methods" on interface (as well as static methods), so that java interface and scala trait become equivalent.</p>


问:
How to query or get other chaincode data in Hyperledger Composer?
From a currently running business network/logic built from Composer, how can one query or get data from another business network (chaincode) using a composer app/javascript function?

Fabric's JIRA shows that at least querying within the same channel is available
https://jira.hyperledger.org/browse/FAB-1788

答:
Composer doesn't currently have any direct way to communicate with other business networks as yet. Business networks can emit events to external systems so you could create an intermediary client application to do something for now.
There is an issue tracking this requirement at
https://github.com/hyperledger/composer/issues/898 </p>


问:
How to calculate the exponential of a matrix in Fortran
I have a 4*4 complex matrix. I am looking for an intrinsic function in Fortran 90 to calculate the matrix exponential.</p>

答: There is no intrinsic fortran function that can do that.</p>


问:
How to change component places on click?
What i want when user click on some button to change place for that component. I want to put some component on first place. Can i achive that? Any suggestion?

So if i have something like this:

```<code><default-component></default-component>
<first-component></first-component>
</code>```

So on click to be like this:

```<code><first-component></first-component>
<default-component></default-component>
</code>```

Is that possible to do?

答:
create one variable for that and display like that.

```<code><first-component *ngIf="isClicked"></first-component>
<default-component></default-component>
<first-component *ngIf="!isClicked"></first-component>
</code>```

change a value of isClicked variable (click)="onClicking"

component

```<code>onClicking(): void {
this.isClicked = !this.isClicked;
}
</code>```

Body:
What i want when user click on some button to change place for that component. I want to put some component on first place. Can i achive that? Any suggestion?

So if i have something like this:

<default-component></default-component>
<first-component></first-component>

So on click to be like this:

<first-component></first-component>
<default-component></default-component>

Is that possible to do?

Body:
create one variable for that and display like that.

<first-component *ngIf="isClicked"></first-component>
<default-component></default-component>
<first-component *ngIf="!isClicked"></first-component>

change a value of isClicked variable (click)="onClicking"

component

onClicking(): void {
this.isClicked = !this.isClicked;
}


问:
How do I use Haskell's type system to enforce correctness while still being able to pattern-match?
Let's say that I have an adt representing some kind of tree structure:

```<code>data Tree = ANode (Maybe Tree) (Maybe Tree) AValType
          | BNode (Maybe Tree) (Maybe Tree) BValType
          | CNode (Maybe Tree) (Maybe Tree) CValType
</code>```

As far as I know there's no way of pattern matching against type constructors (or the matching functions itself wouldn't have a type?) but I'd still like to use the compile-time type system to eliminate the possibility of returning or parsing the wrong 'type' of Tree node. For example, it might be that CNode's can only be parents to ANodes. I might have

```<code>parseANode :: Parser (Maybe Tree)
</code>```

as a Parsec parsing function that get's used as part of my CNode parser:

```<code>parseCNode :: Parser (Maybe Tree)
parseCNode = try (
                  string "<CNode>" >>
                  parseANode >>= \maybeanodel ->
                  parseANode >>= \maybeanoder ->
                  parseCValType >>= \cval ->
                  string "</CNode>"
                  return (Just (CNode maybeanodel maybeanoder cval))
             ) <|> return Nothing
</code>```

According to the type system, parseANode could end up returning a Maybe CNode, a Maybe BNode, or a Maybe ANode, but I really want to make sure that it only returns a Maybe ANode. Note that this isn't a schema-value of data or runtime-check that I want to do - I'm actually just trying to check the validity of the parser that I've written for a particular tree schema. IOW, I'm not trying to check parsed data for schema-correctness, what I'm really trying to do is check my parser for schema correctness - I'd just like to make sure that I don't botch-up parseANode someday to return something other than an ANode value.

I was hoping that maybe if I matched against the value constructor in the bind variable, that the type-inferencing would figure out what I meant:

```<code>parseCNode :: Parser (Maybe Tree)
parseCNode = try (
                  string "<CNode>" >>
                  parseANode >>= \(Maybe (ANode left right avall)) ->
                  parseANode >>= \(Maybe (ANode left right avalr)) ->
                  parseCValType >>= \cval ->
                  string "</CNode>"
                  return (Just (CNode (Maybe (ANode left right avall)) (Maybe (ANode left right avalr)) cval))
             ) <|> return Nothing
</code>```

But this has a lot of problems, not the least of which that parseANode is no longer free to return Nothing. And it doesn't work anyways - it looks like that bind variable is treated as a pattern match and the runtime complains about non-exhaustive pattern matching when parseANode either returns Nothing or Maybe BNode or something.

I could do something along these lines:

```<code>data ANode = ANode (Maybe BNode) (Maybe BNode) AValType
data BNode = BNode (Maybe CNode) (Maybe CNode) BValType
data CNode = CNode (Maybe ANode) (Maybe ANode) CValType
</code>```

but that kind of sucks because it assumes that the constraint is applied to all nodes - I might not be interested in doing that - indeed it might just be CNodes that can only be parenting ANodes. So I guess I could do this:

```<code>data AnyNode = AnyANode ANode | AnyBNode BNode | AnyCNode CNode

data ANode = ANode (Maybe AnyNode) (Maybe AnyNode) AValType
data BNode = BNode (Maybe AnyNode) (Maybe AnyNode) BValType
data CNode = CNode (Maybe ANode) (Maybe ANode) CValType
</code>```

but then this makes it much harder to pattern-match against *Node's - in fact it's impossible because they're just completely distinct types. I could make a typeclass wherever I wanted to pattern-match I guess

```<code>class Node t where
    matchingFunc :: t -> Bool

instance Node ANode where
    matchingFunc (ANode left right val) = testA val

instance Node BNode where
    matchingFunc (BNode left right val) = val == refBVal

instance Node CNode where
    matchingFunc (CNode left right val) = doSomethingWithACValAndReturnABool val
</code>```

At any rate, this just seems kind of messy. Can anyone think of a more succinct way of doing this?

答: An extension of keegan's answer: encoding the correctness properties of red/black trees is sort of a canonical example. This thread has code showing both the GADT and nested data type solution: http://www.reddit.com/r/programming/comments/w1oz/how_are_gadts_useful_in_practical_programming/cw3i9</p>

Body:
Let's say that I have an adt representing some kind of tree structure:

data Tree = ANode (Maybe Tree) (Maybe Tree) AValType
          | BNode (Maybe Tree) (Maybe Tree) BValType
          | CNode (Maybe Tree) (Maybe Tree) CValType

As far as I know there's no way of pattern matching against type constructors (or the matching functions itself wouldn't have a type?) but I'd still like to use the compile-time type system to eliminate the possibility of returning or parsing the wrong 'type' of Tree node. For example, it might be that CNode's can only be parents to ANodes. I might have

parseANode :: Parser (Maybe Tree)

as a Parsec parsing function that get's used as part of my CNode parser:

parseCNode :: Parser (Maybe Tree)
parseCNode = try (
                  string "<CNode>" >>
                  parseANode >>= \maybeanodel ->
                  parseANode >>= \maybeanoder ->
                  parseCValType >>= \cval ->
                  string "</CNode>"
                  return (Just (CNode maybeanodel maybeanoder cval))
             ) <|> return Nothing

According to the type system, parseANode could end up returning a Maybe CNode, a Maybe BNode, or a Maybe ANode, but I really want to make sure that it only returns a Maybe ANode. Note that this isn't a schema-value of data or runtime-check that I want to do - I'm actually just trying to check the validity of the parser that I've written for a particular tree schema. IOW, I'm not trying to check parsed data for schema-correctness, what I'm really trying to do is check my parser for schema correctness - I'd just like to make sure that I don't botch-up parseANode someday to return something other than an ANode value.

I was hoping that maybe if I matched against the value constructor in the bind variable, that the type-inferencing would figure out what I meant:

parseCNode :: Parser (Maybe Tree)
parseCNode = try (
                  string "<CNode>" >>
                  parseANode >>= \(Maybe (ANode left right avall)) ->
                  parseANode >>= \(Maybe (ANode left right avalr)) ->
                  parseCValType >>= \cval ->
                  string "</CNode>"
                  return (Just (CNode (Maybe (ANode left right avall)) (Maybe (ANode left right avalr)) cval))
             ) <|> return Nothing

But this has a lot of problems, not the least of which that parseANode is no longer free to return Nothing. And it doesn't work anyways - it looks like that bind variable is treated as a pattern match and the runtime complains about non-exhaustive pattern matching when parseANode either returns Nothing or Maybe BNode or something.

I could do something along these lines:

data ANode = ANode (Maybe BNode) (Maybe BNode) AValType
data BNode = BNode (Maybe CNode) (Maybe CNode) BValType
data CNode = CNode (Maybe ANode) (Maybe ANode) CValType

but that kind of sucks because it assumes that the constraint is applied to all nodes - I might not be interested in doing that - indeed it might just be CNodes that can only be parenting ANodes. So I guess I could do this:

data AnyNode = AnyANode ANode | AnyBNode BNode | AnyCNode CNode

data ANode = ANode (Maybe AnyNode) (Maybe AnyNode) AValType
data BNode = BNode (Maybe AnyNode) (Maybe AnyNode) BValType
data CNode = CNode (Maybe ANode) (Maybe ANode) CValType

but then this makes it much harder to pattern-match against *Node's - in fact it's impossible because they're just completely distinct types. I could make a typeclass wherever I wanted to pattern-match I guess

class Node t where
    matchingFunc :: t -> Bool

instance Node ANode where
    matchingFunc (ANode left right val) = testA val

instance Node BNode where
    matchingFunc (BNode left right val) = val == refBVal

instance Node CNode where
    matchingFunc (CNode left right val) = doSomethingWithACValAndReturnABool val

At any rate, this just seems kind of messy. Can anyone think of a more succinct way of doing this?


问:
Working of Mockito's verify and argument captor
I'm trying to test the following method

```<code>public void saveToMultipleSources(MyObject myObject)
{
    if (myObject.isOfSomeType()) {
        firstDAO.saveObject(myObject);
        myObject.setContent(null);
    }
    secondDAO.saveObject(myObject);
}
</code>```

The test I wrote was

```<code>@Test
public void testSaveFeature()
{
    //initialize all objects
    obj.saveToMultipleSources(myObject); //myObject has a valid content.
    Mockito.verify(firstDAO).saveObject(myObject);
    myObject.setContent(null);
    Mockito.verify(secondDAO).saveObject(myObject);
}
</code>```

But on running, I get the error that expected and actual arguments differ for the verify statement of firstDAO. The expected was an object with valid content but actual arguments invoked are with Content set as null. I tried the exact same thing with ArgumentCaptor as well, but got the same results.

Can someone explain why does Mockito behave this way? I tried logging the entire object and can see valid Content being set just before I call the firstDAO.

Also how do I go about testing this?

答:
```<code>//initialize all objects
obj.saveToMultipleSources(myObject); //myObject has a valid content.
Mockito.verify(firstDAO).saveObject(myObject);
</code>```

The problem is that setting the objects content to null is a side effect of your method. In consequence Mockito compares the recorded parameter (having valid content) with the object modified by your method (having content already set to null).

In that case, how can I test this? – Abhilash Panigrahi

In the test Make  myObject a Mockito.spy() and prevent the execution of setContent():

```<code>@Test
public void testSaveFeature()
{
    //initialize all objects
    MyObject spyOfMyObject = Mockito.spy(myObject);
    doNothing().when(spyOfMyObject).setContent(null); // special null matcher may be needed...

    obj.saveToMultipleSources(spyOfMyObject);

    Mockito.verify(firstDAO).saveObject(spyOfMyObject);
    Mockito.verify(spyOfMyObject).setContent(null);
    Mockito.verify(secondDAO).saveObject(spyOfMyObject);
}
</code>```

But you most likely want to be sure that myObject.setContent(null);
is called before econdDAO.saveObject(myObject);`...

```<code>@Test
public void testSaveFeature()
{
    //initialize all objects
    MyObject spyOfMyObject = Mockito.spy(myObject);
    doNothing().when(spyOfMyObject).setContent(null);

    obj.saveToMultipleSources(spyOfMyObject);

    Mockito.verify(firstDAO).saveObject(spyOfMyObject);
    InOrder inOrder = Mockito.inOrder(spyOfMyObject,secondDAO);
    inOrder.verify(spyOfMyObject).setContent(null);
    inOrder..verify(secondDAO).saveObject(spyOfMyObject);
}
</code>```

Body:
I'm trying to test the following method

public void saveToMultipleSources(MyObject myObject)
{
    if (myObject.isOfSomeType()) {
        firstDAO.saveObject(myObject);
        myObject.setContent(null);
    }
    secondDAO.saveObject(myObject);
}

The test I wrote was

@Test
public void testSaveFeature()
{
    //initialize all objects
    obj.saveToMultipleSources(myObject); //myObject has a valid content.
    Mockito.verify(firstDAO).saveObject(myObject);
    myObject.setContent(null);
    Mockito.verify(secondDAO).saveObject(myObject);
}

But on running, I get the error that expected and actual arguments differ for the verify statement of firstDAO. The expected was an object with valid content but actual arguments invoked are with Content set as null. I tried the exact same thing with ArgumentCaptor as well, but got the same results.

Can someone explain why does Mockito behave this way? I tried logging the entire object and can see valid Content being set just before I call the firstDAO.

Also how do I go about testing this?

Body:
//initialize all objects
obj.saveToMultipleSources(myObject); //myObject has a valid content.
Mockito.verify(firstDAO).saveObject(myObject);

The problem is that setting the objects content to null is a side effect of your method. In consequence Mockito compares the recorded parameter (having valid content) with the object modified by your method (having content already set to null).

In that case, how can I test this? – Abhilash Panigrahi

In the test Make  myObject a Mockito.spy() and prevent the execution of setContent():

@Test
public void testSaveFeature()
{
    //initialize all objects
    MyObject spyOfMyObject = Mockito.spy(myObject);
    doNothing().when(spyOfMyObject).setContent(null); // special null matcher may be needed...

    obj.saveToMultipleSources(spyOfMyObject);

    Mockito.verify(firstDAO).saveObject(spyOfMyObject);
    Mockito.verify(spyOfMyObject).setContent(null);
    Mockito.verify(secondDAO).saveObject(spyOfMyObject);
}

But you most likely want to be sure that myObject.setContent(null);
is called before econdDAO.saveObject(myObject);`...

@Test
public void testSaveFeature()
{
    //initialize all objects
    MyObject spyOfMyObject = Mockito.spy(myObject);
    doNothing().when(spyOfMyObject).setContent(null);

    obj.saveToMultipleSources(spyOfMyObject);

    Mockito.verify(firstDAO).saveObject(spyOfMyObject);
    InOrder inOrder = Mockito.inOrder(spyOfMyObject,secondDAO);
    inOrder.verify(spyOfMyObject).setContent(null);
    inOrder..verify(secondDAO).saveObject(spyOfMyObject);
}


问:
Move values after comma to newline to text file
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

```<code>Monday
Tuesday
Wednesday
Thursday
Friday
</code>```

One below the other.

Hope this makes sense.

答:
explode function will help you</p>

```<code>$str = "Monday,Tuesday,Wednesday,Thursday,Friday";
    $val = explode(",",$str);

    foreach ($val as $key=>$value) {

      echo $value.'</br>';
    }
</code>```

Body:
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

Monday
Tuesday
Wednesday
Thursday
Friday

One below the other.

Hope this makes sense.

Body:
explode function will help you

$str = "Monday,Tuesday,Wednesday,Thursday,Friday";
    $val = explode(",",$str);

    foreach ($val as $key=>$value) {

      echo $value.'</br>';
    }


问:
How to setup Android Firebase Notification in Manifest?
I'm trying to setup Firebase notifications. I did changes in app level and root level build.gradle. But still, its giving me error in Manifest for MyFirebaseMessagingService. Error is Unresolved Class.

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".s" />
    <activity android:name=".im" />
    <activity android:name=".Main2Activity" />
    <activity android:name=".sactivity" />
    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <activity
        android:name=".ScrollingActivity"
        android:label="@string/title_activity_scrolling"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</code>```

答:
```<code>  <service android:name="com.fcm.MyFirebaseMessagingServices">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name="com.fcm.MyFirebaseInstanceIdServices">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
</code>```

Body:
I'm trying to setup Firebase notifications. I did changes in app level and root level build.gradle. But still, its giving me error in Manifest for MyFirebaseMessagingService. Error is Unresolved Class.

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".s" />
    <activity android:name=".im" />
    <activity android:name=".Main2Activity" />
    <activity android:name=".sactivity" />
    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <activity
        android:name=".ScrollingActivity"
        android:label="@string/title_activity_scrolling"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>


问:
Rowwise maximum of multiple columns (ignoring null values)
How to apply the max()-functions to multiple columns, ignoring NULL values

(in this context NULL is named NA).

My data:

```<code># data
df <- data.frame( a = sample(5), b = sample(5) )
df[2:3,1] <- NA
dbWriteTable(db1, "df", df, overwrite = TRUE )
</code>```

What I have tried

What I want:

(notice that the column max1 does not contain NA)

I was hoping there was a simple way to do this in SQLite, but may there is not?

答:
```<code>df$max<-apply(X=df, MARGIN=1, FUN=max,na.rm=T)
</code>```

Body:
How to apply the max()-functions to multiple columns, ignoring NULL values

(in this context NULL is named NA).

My data:

# data
df <- data.frame( a = sample(5), b = sample(5) )
df[2:3,1] <- NA
dbWriteTable(db1, "df", df, overwrite = TRUE )

What I have tried

What I want:

(notice that the column max1 does not contain NA)

I was hoping there was a simple way to do this in SQLite, but may there is not?


问:
open specific page using firebase api
I am sending push notification to devices using below code.

```<code>      var nTitle = "New message from " + $rootScope.clients_firstName;
      var to = "DeviceToken is here";
      var notification = {
        'title': nTitle,
        //'body': 'Click here to more details...',
        'icon': 'firebase-logo.png',
        'click_action': 'openapp'
      };

      var key = 'your key';
      fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
        'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify({
        'notification': data,
        'to': to
      })
      }).then(function(response) {
        //console.log("res ", response);
      }).catch(function(error) {
        console.error("err ", error);
     });
</code>```

push notification sends on device successfully.

But when I click on notification the specific page should be open.

For example 'click_action' : 'openapp/somepage'

Then the 'somepage' should be open when I click on pushnotification.

AndroidManifest.xml

```<code><activity android:name="MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

        <intent-filter>
            <action android:name="openapp" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

</activity>
</code>```

My project structure

```<code>--platforms
--plugins
--www
  --app
    --about
      --about.html
      --about.ctrl.js
    --product
      --product.html
      --product.ctrl.js
  --css
  --js
  --lib
  index.html
</code>```

If I click on notification and I want to open product or about page then what I have to do?

What is wrong here? Please tell me the proper solution.

答:
You asked me here.
If you use my solution and creating notifications manually in onReceive(Context context, Intent intent) method, you must put pending intent to notification builder.

```<code>NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//init builder with icon, text, any other params

Intent activityIntent = new Intent(context, Activity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); //it is needed if you creating an activity from not activity context
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pendingIntent);

Notification notification = builder.build();
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
NotificationManagerCompat.from(context).notify(notificationId, notification);
</code>```

Title: open specific page using firebase api

Body:
I am sending push notification to devices using below code.

      var nTitle = "New message from " + $rootScope.clients_firstName;
      var to = "DeviceToken is here";
      var notification = {
        'title': nTitle,
        //'body': 'Click here to more details...',
        'icon': 'firebase-logo.png',
        'click_action': 'openapp'
      };

      var key = 'your key';
      fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
        'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify({
        'notification': data,
        'to': to
      })
      }).then(function(response) {
        //console.log("res ", response);
      }).catch(function(error) {
        console.error("err ", error);
     });

push notification sends on device successfully.

But when I click on notification the specific page should be open.

For example 'click_action' : 'openapp/somepage'

Then the 'somepage' should be open when I click on pushnotification.

AndroidManifest.xml

<activity android:name="MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

        <intent-filter>
            <action android:name="openapp" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

</activity>

My project structure

--platforms
--plugins
--www
  --app
    --about
      --about.html
      --about.ctrl.js
    --product
      --product.html
      --product.ctrl.js
  --css
  --js
  --lib
  index.html

If I click on notification and I want to open product or about page then what I have to do?

What is wrong here? Please tell me the proper solution.

Body:
You asked me here.
If you use my solution and creating notifications manually in onReceive(Context context, Intent intent) method, you must put pending intent to notification builder.

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//init builder with icon, text, any other params

Intent activityIntent = new Intent(context, Activity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); //it is needed if you creating an activity from not activity context
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pendingIntent);

Notification notification = builder.build();
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
NotificationManagerCompat.from(context).notify(notificationId, notification);


问:
Difference between /.../ and m/.../ in Perl
What is difference between /.../ and m/.../?

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

my $str = "This is a testing for modifier";

if ($str =~ /This/i) { print "Modifier...\n";  }
if ($str =~ m/This/i) { print "W/O Modifier...\n";  }
</code>```

However, I checked with this site for Reference not clearly understand with the theory

答:
There's no difference. If you just supply /PATTERN/ then it assumes m. However, if you're using an alternative delimiter, you need to supply the m. E.g. m|PATTERN| won't work as |PATTERN|.

In your example, i is the modifier as it's after the pattern. m is the operation. (as opposed to s, tr, y etc.)

Perhaps slightly confusingly - you can use m as a modifier, but only if you put if after the match.

m/PATTERN/m will cause ^ and $ to match differently than in m/PATTERN/, but it's the trailing m that does this, not the leading one.

Body:
What is difference between /.../ and m/.../?

use strict;
use warnings;

my $str = "This is a testing for modifier";

if ($str =~ /This/i) { print "Modifier...\n";  }
if ($str =~ m/This/i) { print "W/O Modifier...\n";  }

However, I checked with this site for Reference not clearly understand with the theory


问:
To find which image out of the two were clicked and report it to Database
I'm not very new to programming nor am I a prodigy or a maestro at it. Now I'm trying to make a website like Facesmash where

two images show up randomly from the respective arrays and

an up-vote is given to the image on which user clicked

the result is stored as a vote in database

Now I've done with the first part and will do with the third as well with php.

Where I'm facing a problem is the 2nd part.

My code in JavaScript looks like this..

```<code>var imagesArray1 = ["a.jpg","b.jpg","c.jpg","d.jpg","e.jpg"];

var imagesArray2 = ["f.jpg","g.jpg","h.jpg","i.jpg","j.jpg"];

function displayImage(){

document.getElementById('nextButton').value="NEXT";
 var num1 = Math.floor(Math.random() * (imagesArra1.length));
var num2 = Math.floor(Math.random() * (imagesArray2.length));

document.canvas1.src = imagesArray1[num1];
document.canvas2.src = imagesArray2[num2];     }
</code>```

As you can see.. I've created two arrays and a random Image is generated from both the two. Now to create a polling system, one solution would be to take two variables p and q.
 p=num1 and q=num2

 If image1 is clicked, the php code reports "p" and value of the index num1 to the DB

If image2 is clicked, php code sends "q" and value of the index num2

num1 and num2 are the randomly generated indices of the image arrays. I'll do with the php part, Just wanted help in this.
 Any other code solution would be appreciated. Thanks a ton for time and help

答:
I tried to write this up :

This is what I suggest you should display your images.

```<code><img src="pathToImage1Array" data-name="p" id="num1_Image1IndexFROMTheArrayVariable">

<img src="pathToImage2Array" data-name="q" id="num2_Image2IndexFROMTheArrayVariable">
</code>```

Please note.

Id needs to be unique for each image that will come from the array.

so we need to make our ID for the image unique.. with a dynamic data. so we will have a prefix for each image ID that will come up from the array.

in this case we have num1_ then the string after the underscore (_) will be replaced by the variable that stores index of each image so if the index of the image is 8 then num1_8 this changes as the image changes.

Then you will need to send ajax request to some php script when the image is clicked.

then your ajax :

```<code><script type="text/javascript">
    $('document').ready(function(){

        //getting data of the 1st image.. that have a dyamic ID.
        $('[id^="num1_"]').on('click',function(){

            var index = $(this).attr('id').split("_")[1]; //get index  of the clicked image
            var action = "firstimage";
            var image = $(this).data('name');
            $.ajax({

                type : "POST",
                data : {imageIndex:index,action:action,:image:image},
                url  : "pathTophpfile/phpfile.php",
                dataType :"json",
                encode : true,
                success : function(response){

                    if(response == "ok"){

                        alert("vote casted");
                    }else{

                        alert(response);
                    }
                }
            });
        });

        $('[id^="num2_"]').on('click',function(){

            var index = $(this).attr('id').split("_")[1]; //get the index of the clicked image
            var action = "secondimage";
            var image = $(this).data('name');

            $.ajax({

                type : "POST",
                data : {imageIndex:index,action:action},
                url  : "pathTophpfile/phpfile.php",
                dataType :"json",
                encode : true,
                success : function(response){

                    if(response == "ok"){

                        alert("vote casted");
                    }else{

                        alert(response);
                    }
                }
            });
        });
    });
</script>
</code>```

then your server side :

I'm not sure which API you comfortable with PDO/MYSQLI I did mysqli prepared statements :

```<code><?php

$conn = new mysli("..."); // the staff you should know already

function image1($conn)
{

    if ($_SERVER['REQUEST_METHOD'] == "POST"):
        $imageIndex = $_POST['imageIndex'];
        $image      = $_POST['image'];
        $sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
        $sql->bind_param("si", $image, $imageIndex);
        if ($sql->execute()) {

            echo json_decode("ok");
        } else {

            echo json_decode("Error : " . $conn->error);
        }
    endif;
}

function image2($conn)
{

    if ($_SERVER['REQUEST_METHOD'] == "POST"):
        $imageIndex = $_POST['imageIndex'];
        $image      = $_POST['image'];
        $sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
        $sql->bind_param("si", $image, $imageIndex);
        if ($sql->execute()) {
            echo json_decode("ok");
        } else {
            echo json_decode("Error : " . $conn->error);
        }
    endif;
}

if (isset($_POST['action'])) {

    $action = $_POST['action'];

    switch ($action) {
        case 'firstimage':
            image1($conn);
            break;

        case 'secondimage':
            image2($conn);
            break;
    }
}

?>
</code>```

Body:
I'm not very new to programming nor am I a prodigy or a maestro at it. Now I'm trying to make a website like Facesmash where

two images show up randomly from the respective arrays and

an up-vote is given to the image on which user clicked

the result is stored as a vote in database

Now I've done with the first part and will do with the third as well with php.

Where I'm facing a problem is the 2nd part.

My code in JavaScript looks like this..

var imagesArray1 = ["a.jpg","b.jpg","c.jpg","d.jpg","e.jpg"];

var imagesArray2 = ["f.jpg","g.jpg","h.jpg","i.jpg","j.jpg"];

function displayImage(){

document.getElementById('nextButton').value="NEXT";
 var num1 = Math.floor(Math.random() * (imagesArra1.length));
var num2 = Math.floor(Math.random() * (imagesArray2.length));

document.canvas1.src = imagesArray1[num1];
document.canvas2.src = imagesArray2[num2];     }

As you can see.. I've created two arrays and a random Image is generated from both the two. Now to create a polling system, one solution would be to take two variables p and q.
 p=num1 and q=num2

 If image1 is clicked, the php code reports "p" and value of the index num1 to the DB

If image2 is clicked, php code sends "q" and value of the index num2

num1 and num2 are the randomly generated indices of the image arrays. I'll do with the php part, Just wanted help in this.
 Any other code solution would be appreciated. Thanks a ton for time and help

Body:
I tried to write this up :

This is what I suggest you should display your images.

<img src="pathToImage1Array" data-name="p" id="num1_Image1IndexFROMTheArrayVariable">

<img src="pathToImage2Array" data-name="q" id="num2_Image2IndexFROMTheArrayVariable">

Please note.

Id needs to be unique for each image that will come from the array.

so we need to make our ID for the image unique.. with a dynamic data. so we will have a prefix for each image ID that will come up from the array.

in this case we have num1_ then the string after the underscore (_) will be replaced by the variable that stores index of each image so if the index of the image is 8 then num1_8 this changes as the image changes.

Then you will need to send ajax request to some php script when the image is clicked.

then your ajax :

<script type="text/javascript">
    $('document').ready(function(){

        //getting data of the 1st image.. that have a dyamic ID.
        $('[id^="num1_"]').on('click',function(){

            var index = $(this).attr('id').split("_")[1]; //get index  of the clicked image
            var action = "firstimage";
            var image = $(this).data('name');
            $.ajax({

                type : "POST",
                data : {imageIndex:index,action:action,:image:image},
                url  : "pathTophpfile/phpfile.php",
                dataType :"json",
                encode : true,
                success : function(response){

                    if(response == "ok"){

                        alert("vote casted");
                    }else{

                        alert(response);
                    }
                }
            });
        });

        $('[id^="num2_"]').on('click',function(){

            var index = $(this).attr('id').split("_")[1]; //get the index of the clicked image
            var action = "secondimage";
            var image = $(this).data('name');

            $.ajax({

                type : "POST",
                data : {imageIndex:index,action:action},
                url  : "pathTophpfile/phpfile.php",
                dataType :"json",
                encode : true,
                success : function(response){

                    if(response == "ok"){

                        alert("vote casted");
                    }else{

                        alert(response);
                    }
                }
            });
        });
    });
</script>

then your server side :

I'm not sure which API you comfortable with PDO/MYSQLI I did mysqli prepared statements :

<?php

$conn = new mysli("..."); // the staff you should know already

function image1($conn)
{

    if ($_SERVER['REQUEST_METHOD'] == "POST"):
        $imageIndex = $_POST['imageIndex'];
        $image      = $_POST['image'];
        $sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
        $sql->bind_param("si", $image, $imageIndex);
        if ($sql->execute()) {

            echo json_decode("ok");
        } else {

            echo json_decode("Error : " . $conn->error);
        }
    endif;
}

function image2($conn)
{

    if ($_SERVER['REQUEST_METHOD'] == "POST"):
        $imageIndex = $_POST['imageIndex'];
        $image      = $_POST['image'];
        $sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
        $sql->bind_param("si", $image, $imageIndex);
        if ($sql->execute()) {
            echo json_decode("ok");
        } else {
            echo json_decode("Error : " . $conn->error);
        }
    endif;
}

if (isset($_POST['action'])) {

    $action = $_POST['action'];

    switch ($action) {
        case 'firstimage':
            image1($conn);
            break;

        case 'secondimage':
            image2($conn);
            break;
    }
}

?>


问:
Display table-cell vertical-align middle create 1px weird spacing in chrome
I need to centre my content in the div, so I use the table-cell and vertical-align to achieve it. However, it create a weird spacing like 1px in Chrome only. I can't really find the solution. Please do help me.

body {
  background: red;
}
.img-wrapper, .txt-wrapper {
  height: 300px;
  width: 50%;
  float: left;
  position: relative;
}
.img-wrapper {
  background: yellow;
}
.txt-wrapper {
  background: green;
  display: table;
}
.txt {
  display: table-cell;
  vertical-align: middle;
}
.col1 {
  vertical-align: middle !important;
  background: yellow;
  width: 50%;
}
.col2 {
  background: green;
  width: 50%;
}
.pushtoright {
  left: 50%;
}
.pulltoleft {
  right: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 1</h2>
      <p>Description 1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 2</h2>
      <p>Description 2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 3</h2>
      <p>Description 3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 4</h2>
      <p>Description 4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div></code>```

The demo : https://codepen.io/rae0724/pen/jwxJqX

答:
If you can do without display: table in .txt-wrapper , if this is not a problem for other things ... the strange effect disappears

body {
  background: red;
}
.img-wrapper, .txt-wrapper {
  height: 300px;
  width: 50%;
  float: left;
  position: relative;
}
.img-wrapper {
  background: yellow;
}
.txt-wrapper {
  background: green;
  display: flex;
  align-items:center;

  /*display: table;*/
}
.txt {
  display: inline-block;
  padding: 20px;
}
.col1 {
  vertical-align: middle !important;
  background: yellow;
  width: 50%;
}
.col2 {
  background: green;
  width: 50%;
}
.pushtoright {
  left: 50%;
}
.pulltoleft {
  right: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 1</h2>
      <p>Description 1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 2</h2>
      <p>Description 2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 3</h2>
      <p>Description 3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 4</h2>
      <p>Description 4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div></code>```

Body:
I need to centre my content in the div, so I use the table-cell and vertical-align to achieve it. However, it create a weird spacing like 1px in Chrome only. I can't really find the solution. Please do help me.

body {
  background: red;
}
.img-wrapper, .txt-wrapper {
  height: 300px;
  width: 50%;
  float: left;
  position: relative;
}
.img-wrapper {
  background: yellow;
}
.txt-wrapper {
  background: green;
  display: table;
}
.txt {
  display: table-cell;
  vertical-align: middle;
}
.col1 {
  vertical-align: middle !important;
  background: yellow;
  width: 50%;
}
.col2 {
  background: green;
  width: 50%;
}
.pushtoright {
  left: 50%;
}
.pulltoleft {
  right: 50%;
}

Title 1

Description 1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Title 2

Description 2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Title 3

Description 3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Title 4

Description 4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

The demo : https://codepen.io/rae0724/pen/jwxJqX

Body:
If you can do without display: table in .txt-wrapper , if this is not a problem for other things ... the strange effect disappears

body {
  background: red;
}
.img-wrapper, .txt-wrapper {
  height: 300px;
  width: 50%;
  float: left;
  position: relative;
}
.img-wrapper {
  background: yellow;
}
.txt-wrapper {
  background: green;
  display: flex;
  align-items:center;

  /*display: table;*/
}
.txt {
  display: inline-block;
  padding: 20px;
}
.col1 {
  vertical-align: middle !important;
  background: yellow;
  width: 50%;
}
.col2 {
  background: green;
  width: 50%;
}
.pushtoright {
  left: 50%;
}
.pulltoleft {
  right: 50%;
}

<div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 1</h2>
      <p>Description 1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 2</h2>
      <p>Description 2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper">
    <div class="txt">
      <h2>Title 3</h2>
      <p>Description 3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>

<div class="therow">
  <div class="img-wrapper pushtoright">
    <div class="img"></div>
  </div>
  <div class="txt-wrapper pulltoleft">
    <div class="txt">
      <h2>Title 4</h2>
      <p>Description 4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>


问:
Output redirect of nested script not working with cron
So, I have this shell script, that dynamically builds another script and calls it (i.e. a nested script).

Something like this, let's say it is called the_script.sh:

```<code>#!/bin/sh

# do some stuff here, and create another script
./nested_script.sh

# do some other stuff, end
</code>```

If I just call ./the_script.sh it outputs everything to STDOUT, including the nested script's output.

But if it runs from a cronjob, like so:

```<code>0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log
</code>```

Then it does not output the nested script's result, which is very important for me. The result of both script is correct however it is run (from the prompt or cron), and it runs as expected.

Any clues on why this happens and how to prevent it?

答: The cron does not run from a specific user's home directory - so running ./nested_script.sh may not work.  You should specify the absolute path to this so the cron knows exactly where it is.</p>

Body:
So, I have this shell script, that dynamically builds another script and calls it (i.e. a nested script).

Something like this, let's say it is called the_script.sh:

#!/bin/sh

# do some stuff here, and create another script
./nested_script.sh

# do some other stuff, end

If I just call ./the_script.sh it outputs everything to STDOUT, including the nested script's output.

But if it runs from a cronjob, like so:

0 8,12 * * 1-5 /home/myuser/the_script.sh >> /home/myuser/thescript.log

Then it does not output the nested script's result, which is very important for me. The result of both script is correct however it is run (from the prompt or cron), and it runs as expected.

Any clues on why this happens and how to prevent it?


问:
Get values of 2 columns as single value when separated with '|'
I want to have the values of two columns as a single value but separated with '|' and to also skip the hyphen if values are not present in the particular column.

For example:

The output should be like below,

```<code>1|2
2
1|2
2
1|2
</code>```

答:
Try it like this:

Concatenating a string with  NULL value returns NULL. ISNULL() will set a default in case of NULL, while NULLIF will return NULL in case of a fullfilled condition:

```<code>DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup
</code>```

The result

```<code>1|2
2
1|2

2|
1|2
</code>```

Body:
I want to have the values of two columns as a single value but separated with '|' and to also skip the hyphen if values are not present in the particular column.

For example:

The output should be like below,

1|2
2
1|2
2
1|2

Body:
Try it like this:

Concatenating a string with  NULL value returns NULL. ISNULL() will set a default in case of NULL, while NULLIF will return NULL in case of a fullfilled condition:

DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup

The result

1|2
2
1|2

2|
1|2


问:
Order By TableName and columnname
Lets say I have a table with following columns:

```<code>Id,TableName,Columnname
</code>```

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

```<code>Select * From MyTable Order By TableName,ColumnName
</code>```

Now say I would like a special case of ordering depending on TableName

```<code>Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;
</code>```

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

答:
As alternative, you could

1) create a new table

```<code>CREATE TABLE_ORDER (TABLE_NAME VARCHAR(100) NOT NULL, ORDER_VAL INT);
ALTER TABLE TABLE_ORDER ADD CONSTRAINT TABLE_ORDER_PK PRIMARY KEY(TABLE_NAME);
</code>```

2) insert into it appropriate values:

```<code> INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Foo', 1);
 INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Bar', 2);
 INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Test', 3);
</code>```

3) Use the following query

```<code>   SELECT A.*
   FROM MYTABLE A
   LEFT JOIN TABLE_ORDER B ON A.TABLENAME= B.TABLE_NAME
   ORDER BY B.ORDER_VAL, A.COLUMNNAME
</code>```

Title: Order By TableName and columnname

Body:
Lets say I have a table with following columns:

Id,TableName,Columnname

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

Select * From MyTable Order By TableName,ColumnName

Now say I would like a special case of ordering depending on TableName

Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

Body:
As alternative, you could

1) create a new table

CREATE TABLE_ORDER (TABLE_NAME VARCHAR(100) NOT NULL, ORDER_VAL INT);
ALTER TABLE TABLE_ORDER ADD CONSTRAINT TABLE_ORDER_PK PRIMARY KEY(TABLE_NAME);

2) insert into it appropriate values:

 INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Foo', 1);
 INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Bar', 2);
 INSERT INTO TABLE_ORDER (TABLE_NAME, ORDER_VAL) VALUES ('Test', 3);

3) Use the following query

   SELECT A.*
   FROM MYTABLE A
   LEFT JOIN TABLE_ORDER B ON A.TABLENAME= B.TABLE_NAME
   ORDER BY B.ORDER_VAL, A.COLUMNNAME


问:
MYSQL Select row when first part of condition is valid (with a group by)
I really don't know how to find an answer for my question, so I'm asking you.

Here is the table I have :

```<code>+----+------------+------------+-------------+
| id | start_date |  end_date  |  id_person  |
+----+------------+------------+-------------+
| 1  | 2017-10-01 | 2017-12-01 |      1      |
| 2  | 2017-07-01 | 2017-09-01 |      1      |
| 3  | 2016-01-01 | 2016-02-01 |      1      |
| 4  | 2016-05-01 | 2016-06-01 |      2      |
| 5  | 2016-01-01 | 2016-02-01 |      2      |
+----+------------+------------+-------------+
</code>```

And here is the query I tried to use :

```<code>SELECT * FROM table
WHERE ((start_date < NOW() AND end_date > NOW())
OR start_date > NOW()
OR end_date < NOW())
GROUP BY `id_person`
</code>```

The result I was expecting was this one :

```<code>+----+------------+------------+-------------+
| id | start_date |  end_date  |  id_person  |
+----+------------+------------+-------------+
| 2  | 2017-07-01 | 2017-09-01 |      1      | // matches first condition
| 4  | 2016-05-01 | 2016-06-01 |      2      | // matches 3rd condition and has the most recent start_date
+----+------------+------------+-------------+
</code>```

If you didn't get what I did wrong yet, I'm going to tell you.

Here, I was trying to show a single row per person but I wanted this row to match the first condition it finds and not the others, I don't want the row to just be ordered by start_date. It is like a custom order where I want the first row for each person.

The problem is that this query doesn't work since the GROUP BY statement doesn't apply conditions first. (even if it did, I'm not sure the condition would only select one row)

I really don't know how I can achieve that and I don't even know if it is possible, I hope someone can lead me towards any solution.

Thanks for reading this, I'll answer as fast as I can to give you more informations.

答:
If are happy to write the rules directly in sql rather than as where conditions you can ask the database for what yuo want more directly.

This means taking a step back to see what the rules you want are. It looks like you want to prioritise the entries by closest date, showing first current, then future, then historical. It also looks like end_date >= start_date, which means you only need to look at end_date to find what you are looking for.

Mysql can answer the question abusing it's group by functionality (until recent versions).

```<code>SELECT t.* FROM
(
   SELECT t.*
   FROM table t
   ORDER BY SIGN(t.end_date - NOW()),ABS(t.end_date-NOW())
)
GROUP BY t.id_person
</code>```

A standard sql method that will also play better with indexes would be to look for end dates before and after today separately.

```<code>SELECT t.*
FROM table t
JOIN (
    SELECT t.person_id
      ,COALESCE(first_not_ended.end_date,t.last_ended.end_date) AS end_date
    FROM table t
    LEFT JOIN (
        SELECT t.*,MIN(end_date) AS end_date
        FROM table t
        WHERE t.end_date > NOW()
        GROUP by t.person_id
    ) first_not_ended
    ON t.person_id=first_not_ended.person_id
    AND t.end_date=first_not_ended.end_ate
    LEFT JOIN (
        SELECT t.person_id,MAX(end_date) AS end_date
        FROM table t
        WHERE t.end_date < NOW()
        GROUP by t.person_id
    ) last_ended
    ON t.person_id=last_ended.person_id
    AND t.end_date=last_ended.end_date
) closest
ON t.person_id=closest.person_id
AND t.end_date=closest.end_date
</code>```

Body:
I really don't know how to find an answer for my question, so I'm asking you.

Here is the table I have :

+----+------------+------------+-------------+
| id | start_date |  end_date  |  id_person  |
+----+------------+------------+-------------+
| 1  | 2017-10-01 | 2017-12-01 |      1      |
| 2  | 2017-07-01 | 2017-09-01 |      1      |
| 3  | 2016-01-01 | 2016-02-01 |      1      |
| 4  | 2016-05-01 | 2016-06-01 |      2      |
| 5  | 2016-01-01 | 2016-02-01 |      2      |
+----+------------+------------+-------------+

And here is the query I tried to use :

SELECT * FROM table
WHERE ((start_date < NOW() AND end_date > NOW())
OR start_date > NOW()
OR end_date < NOW())
GROUP BY `id_person`

The result I was expecting was this one :

+----+------------+------------+-------------+
| id | start_date |  end_date  |  id_person  |
+----+------------+------------+-------------+
| 2  | 2017-07-01 | 2017-09-01 |      1      | // matches first condition
| 4  | 2016-05-01 | 2016-06-01 |      2      | // matches 3rd condition and has the most recent start_date
+----+------------+------------+-------------+

If you didn't get what I did wrong yet, I'm going to tell you.

Here, I was trying to show a single row per person but I wanted this row to match the first condition it finds and not the others, I don't want the row to just be ordered by start_date. It is like a custom order where I want the first row for each person.

The problem is that this query doesn't work since the GROUP BY statement doesn't apply conditions first. (even if it did, I'm not sure the condition would only select one row)

I really don't know how I can achieve that and I don't even know if it is possible, I hope someone can lead me towards any solution.

Thanks for reading this, I'll answer as fast as I can to give you more informations.

Body:
If are happy to write the rules directly in sql rather than as where conditions you can ask the database for what yuo want more directly.

This means taking a step back to see what the rules you want are. It looks like you want to prioritise the entries by closest date, showing first current, then future, then historical. It also looks like end_date >= start_date, which means you only need to look at end_date to find what you are looking for.

Mysql can answer the question abusing it's group by functionality (until recent versions).

SELECT t.* FROM
(
   SELECT t.*
   FROM table t
   ORDER BY SIGN(t.end_date - NOW()),ABS(t.end_date-NOW())
)
GROUP BY t.id_person

A standard sql method that will also play better with indexes would be to look for end dates before and after today separately.

SELECT t.*
FROM table t
JOIN (
    SELECT t.person_id
      ,COALESCE(first_not_ended.end_date,t.last_ended.end_date) AS end_date
    FROM table t
    LEFT JOIN (
        SELECT t.*,MIN(end_date) AS end_date
        FROM table t
        WHERE t.end_date > NOW()
        GROUP by t.person_id
    ) first_not_ended
    ON t.person_id=first_not_ended.person_id
    AND t.end_date=first_not_ended.end_ate
    LEFT JOIN (
        SELECT t.person_id,MAX(end_date) AS end_date
        FROM table t
        WHERE t.end_date < NOW()
        GROUP by t.person_id
    ) last_ended
    ON t.person_id=last_ended.person_id
    AND t.end_date=last_ended.end_date
) closest
ON t.person_id=closest.person_id
AND t.end_date=closest.end_date