问:
Haskell List Generator High Memory Usage
While working on a competitive programming problem I discovered an interesting issue that drastically reduced the performance of some of my code. After much experimentation I have managed to reduce the issue to the following minimal example:

```<code>module Main where

main = interact handle

handle :: String -> String
-- handle s = show $ sum l
-- handle s = show $ length l
-- handle s = show $ seq (length l) (sum l)
  where
    l = [0..10^8] :: [Int]
</code>```

If you uncomment each commented line individually, compile with ghc -O2 test.hs and run with time ./test > /dev/null, you should get something like the following:

For sum l:

```<code>0.02user 0.00system 0:00.03elapsed 93%CPU (0avgtext+0avgdata 3380maxresident)k
0inputs+0outputs (0major+165minor)pagefaults 0swaps
</code>```

For length l:

```<code>0.02user 0.00system 0:00.02elapsed 100%CPU (0avgtext+0avgdata 3256maxresident)k
0inputs+0outputs (0major+161minor)pagefaults 0swaps
</code>```

For seq (length l) (sum l):

```<code>5.47user 1.15system 0:06.63elapsed 99%CPU (0avgtext+0avgdata 7949048maxresident)k
0inputs+0outputs (0major+1986697minor)pagefaults 0swaps
</code>```

Look at that huge increase in peak memory usage. This makes some amount of sense, because of course both sum and length can lazily consume the list as a stream, while the seq will be triggering the evaluation of the whole list, which must then be stored. But the seq version of the code is using just shy of 8 GB of memory to handle a list that contains just 400 MB of actual data. The purely functional nature of Haskell lists could explain some small constant factor, but a 20 fold increase in memory seems unintended.

This behaviour can be triggered by a number of things. Perhaps the easiest way is using force from Control.DeepSeq, but the way in which I originally encountered this was while using Data.Array.IArray (I can only use the standard library) and trying to construct an array from a list. The implementation of Array is monadic, and so was forcing the evaluation of the list from which it was being constructed.

If anyone has any insight into the underlying cause of this behaviour, I would be very interested to learn why this happens. I would of course also appreciate any suggestions as to how to avoid this issue, bearing in mind that I have to use just the standard library in this case, and that every Array constructor takes and eventually forces a list.

I hope you find this issue as interesting as I did, but hopefully less baffling.

EDIT: user2407038's comment made me realize I had forgotten to post profiling results. I have tried profiling this code and the profiler simply states that 100% of allocations are performed in handle.l, so it seems that simply anything that forces the evaluation of the list uses huge amounts of memory. As I mentioned above, using the force function from Control.DeepSeq, constructing an Array, or anything else that forces the list causes this behaviour. I am confused as to why it would ever require 8 GB of memory to compute a list containing 400 MB of data. Even if every element in the list required two 64-bit pointers, that is still only a factor of 5, and I would think GHC would be able to do something more efficient than that. If not this is an obvious bottleneck for the Array package, as constructing any array inherently requires us to allocate far more memory than the array itself.

So, ultimately: Does anyone have any idea why forcing a list requires such huge amounts of memory, which has such a high cost on performance?

EDIT: user2407038 provided a link to the very helpful GHC Memory Footprint reference. This explains exactly the data sizes of everything, and almost entirely explains the huge overhead: An [Int] is specified as requiring 5N+1 words of memory, which at 8 bytes per word gives 40 bytes per element. In this example that would suggest 4 GB, which accounts for half the total peak usage. It is easy to then believe that the evaluation of sum would then add a similar factor, so this answers my question.

Thanks to all commenters for your help.

EDIT: As I mentioned above, I originally encountered this behaviour why trying to construct an Array. Having had a bit of a dig into GHC.Arr I have found what I think is the root cause of this behaviour when constructing an array: The constructor folds over the list to compose a program in the ST monad that it then runs. Obviously the ST can't be executed until it is completely composed, and in this case the ST construct will be large and linear in the size of the input. To avoid this behaviour we would have to somehow modify the constructor to stream elements from the list as it adds them in ST.

答:
There are multiple factors that come to play here. The first one is that GHC will lazily lift l out of handle. This would enable handle to reuse l, so that you don't have to recalculate it every time, but in this case it creates a space leak. You can check this if you -ddump-simplified core:

```<code>Main.handle_l :: [Int]
[GblId,
 Str=DmdType,
 Unf=Unf{Src=<vanilla>, TopLvl=True, Value=False, ConLike=False,
         WorkFree=False, Expandable=False, Guidance=IF_ARGS [] 40 0}]
Main.handle_l =
  case Main.handle3 of _ [Occ=Dead] { GHC.Types.I# y_a1HY ->
  GHC.Enum.eftInt 0 y_a1HY
  }
</code>```

The functionality to calculate the [0..10^7] 1 is hidden away in other functions, but essentially, handle_l = [0..10^7], at top-level (TopLvl=True). It won't get reclaimed, since you may or may not use handle again. If we use handle s = show $ length l, l itself will be inlined. You will not find any TopLvl=True function that has type [Int].

So GHC detects that you use l twice and creates a top-level CAF. How big is that CAF? An Int takes two words:

```<code>data Int = I# Int#
</code>```

One for I#, one for Int#. How much for [Int]?

```<code>data [a] = [] | (:) a ([a]) -- pseudo, but similar
</code>```

That's one word for [], and three words for (:) a ([a]). A list of [Int] with size N will therefore have a total size of (3N + 1) + 2N words, in your case 5N+1 words. Given your memory, I assume a word is 8byte on your plattform, so we end up with

```<code>5 * 10^8 * 8 bytes = 4 000 000 000 bytes
</code>```

So how do we get rid of that list? The first option we have is to get rid of l:

```<code>handle _ = show $ seq (length [0..10^8]) (sum [0..10^8])
</code>```

This will now run in constant memory due to foldr/buildr rules. While we have [0..10^8] there twice, they don't share the same name. If we check the -stats, we will see that it runs in constant memory:

```<code>> SO.exe +RTS -s
5000000050000000   4,800,066,848 bytes allocated in the heap
         159,312 bytes copied during GC
          43,832 bytes maximum residency (2 sample(s))
          20,576 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      9154 colls,     0 par    0.031s   0.013s     0.0000s    0.0000s
  Gen  1         2 colls,     0 par    0.000s   0.000s     0.0001s    0.0002s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time    4.188s  (  4.232s elapsed)
  GC      time    0.031s  (  0.013s elapsed)
  EXIT    time    0.000s  (  0.001s elapsed)
  Total   time    4.219s  (  4.247s elapsed)

  %GC     time       0.7%  (0.3% elapsed)

  Alloc rate    1,146,284,620 bytes per MUT second

  Productivity  99.3% of total user, 98.6% of total elapsed
</code>```

But that's not really nice, since we now have to track all the uses of [0..10^8]. What if we create a function instead?

```<code>handle :: String -> String
handle _ = show $ seq (length $ l ()) (sum $ l ())
  where
    {-# INLINE l #-}
    l _ = [0..10^7] :: [Int]
</code>```

This works, but we must inline l, otherwise we get the same problem as before if we use optimizations. -O1 (and -O2) enable -ffull-laziness, which—together with common subexpression elimination—would lift l () to the top. So we either need to inline it or use -O2 -fno-full-laziness to prevent that behaviour.

1 Had to decrease the list size, otherwise I would have started swapping.

Body:
While working on a competitive programming problem I discovered an interesting issue that drastically reduced the performance of some of my code. After much experimentation I have managed to reduce the issue to the following minimal example:

module Main where

main = interact handle

handle :: String -> String
-- handle s = show $ sum l
-- handle s = show $ length l
-- handle s = show $ seq (length l) (sum l)
  where
    l = [0..10^8] :: [Int]

If you uncomment each commented line individually, compile with ghc -O2 test.hs and run with time ./test > /dev/null, you should get something like the following:

For sum l:

0.02user 0.00system 0:00.03elapsed 93%CPU (0avgtext+0avgdata 3380maxresident)k
0inputs+0outputs (0major+165minor)pagefaults 0swaps

For length l:

0.02user 0.00system 0:00.02elapsed 100%CPU (0avgtext+0avgdata 3256maxresident)k
0inputs+0outputs (0major+161minor)pagefaults 0swaps

For seq (length l) (sum l):

5.47user 1.15system 0:06.63elapsed 99%CPU (0avgtext+0avgdata 7949048maxresident)k
0inputs+0outputs (0major+1986697minor)pagefaults 0swaps

Look at that huge increase in peak memory usage. This makes some amount of sense, because of course both sum and length can lazily consume the list as a stream, while the seq will be triggering the evaluation of the whole list, which must then be stored. But the seq version of the code is using just shy of 8 GB of memory to handle a list that contains just 400 MB of actual data. The purely functional nature of Haskell lists could explain some small constant factor, but a 20 fold increase in memory seems unintended.

This behaviour can be triggered by a number of things. Perhaps the easiest way is using force from Control.DeepSeq, but the way in which I originally encountered this was while using Data.Array.IArray (I can only use the standard library) and trying to construct an array from a list. The implementation of Array is monadic, and so was forcing the evaluation of the list from which it was being constructed.

If anyone has any insight into the underlying cause of this behaviour, I would be very interested to learn why this happens. I would of course also appreciate any suggestions as to how to avoid this issue, bearing in mind that I have to use just the standard library in this case, and that every Array constructor takes and eventually forces a list.

I hope you find this issue as interesting as I did, but hopefully less baffling.

EDIT: user2407038's comment made me realize I had forgotten to post profiling results. I have tried profiling this code and the profiler simply states that 100% of allocations are performed in handle.l, so it seems that simply anything that forces the evaluation of the list uses huge amounts of memory. As I mentioned above, using the force function from Control.DeepSeq, constructing an Array, or anything else that forces the list causes this behaviour. I am confused as to why it would ever require 8 GB of memory to compute a list containing 400 MB of data. Even if every element in the list required two 64-bit pointers, that is still only a factor of 5, and I would think GHC would be able to do something more efficient than that. If not this is an obvious bottleneck for the Array package, as constructing any array inherently requires us to allocate far more memory than the array itself.

So, ultimately: Does anyone have any idea why forcing a list requires such huge amounts of memory, which has such a high cost on performance?

EDIT: user2407038 provided a link to the very helpful GHC Memory Footprint reference. This explains exactly the data sizes of everything, and almost entirely explains the huge overhead: An [Int] is specified as requiring 5N+1 words of memory, which at 8 bytes per word gives 40 bytes per element. In this example that would suggest 4 GB, which accounts for half the total peak usage. It is easy to then believe that the evaluation of sum would then add a similar factor, so this answers my question.

Thanks to all commenters for your help.

EDIT: As I mentioned above, I originally encountered this behaviour why trying to construct an Array. Having had a bit of a dig into GHC.Arr I have found what I think is the root cause of this behaviour when constructing an array: The constructor folds over the list to compose a program in the ST monad that it then runs. Obviously the ST can't be executed until it is completely composed, and in this case the ST construct will be large and linear in the size of the input. To avoid this behaviour we would have to somehow modify the constructor to stream elements from the list as it adds them in ST.

Body:
There are multiple factors that come to play here. The first one is that GHC will lazily lift l out of handle. This would enable handle to reuse l, so that you don't have to recalculate it every time, but in this case it creates a space leak. You can check this if you -ddump-simplified core:

Main.handle_l :: [Int]
[GblId,
 Str=DmdType,
 Unf=Unf{Src=<vanilla>, TopLvl=True, Value=False, ConLike=False,
         WorkFree=False, Expandable=False, Guidance=IF_ARGS [] 40 0}]
Main.handle_l =
  case Main.handle3 of _ [Occ=Dead] { GHC.Types.I# y_a1HY ->
  GHC.Enum.eftInt 0 y_a1HY
  }

The functionality to calculate the [0..10^7] 1 is hidden away in other functions, but essentially, handle_l = [0..10^7], at top-level (TopLvl=True). It won't get reclaimed, since you may or may not use handle again. If we use handle s = show $ length l, l itself will be inlined. You will not find any TopLvl=True function that has type [Int].

So GHC detects that you use l twice and creates a top-level CAF. How big is that CAF? An Int takes two words:

data Int = I# Int#

One for I#, one for Int#. How much for [Int]?

data [a] = [] | (:) a ([a]) -- pseudo, but similar

That's one word for [], and three words for (:) a ([a]). A list of [Int] with size N will therefore have a total size of (3N + 1) + 2N words, in your case 5N+1 words. Given your memory, I assume a word is 8byte on your plattform, so we end up with

5 * 10^8 * 8 bytes = 4 000 000 000 bytes

So how do we get rid of that list? The first option we have is to get rid of l:

handle _ = show $ seq (length [0..10^8]) (sum [0..10^8])

This will now run in constant memory due to foldr/buildr rules. While we have [0..10^8] there twice, they don't share the same name. If we check the -stats, we will see that it runs in constant memory:

> SO.exe +RTS -s
5000000050000000   4,800,066,848 bytes allocated in the heap
         159,312 bytes copied during GC
          43,832 bytes maximum residency (2 sample(s))
          20,576 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0      9154 colls,     0 par    0.031s   0.013s     0.0000s    0.0000s
  Gen  1         2 colls,     0 par    0.000s   0.000s     0.0001s    0.0002s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time    4.188s  (  4.232s elapsed)
  GC      time    0.031s  (  0.013s elapsed)
  EXIT    time    0.000s  (  0.001s elapsed)
  Total   time    4.219s  (  4.247s elapsed)

  %GC     time       0.7%  (0.3% elapsed)

  Alloc rate    1,146,284,620 bytes per MUT second

  Productivity  99.3% of total user, 98.6% of total elapsed

But that's not really nice, since we now have to track all the uses of [0..10^8]. What if we create a function instead?

handle :: String -> String
handle _ = show $ seq (length $ l ()) (sum $ l ())
  where
    {-# INLINE l #-}
    l _ = [0..10^7] :: [Int]

This works, but we must inline l, otherwise we get the same problem as before if we use optimizations. -O1 (and -O2) enable -ffull-laziness, which—together with common subexpression elimination—would lift l () to the top. So we either need to inline it or use -O2 -fno-full-laziness to prevent that behaviour.

1 Had to decrease the list size, otherwise I would have started swapping.


来源: stackexchange

问:
Getting wrong time after Submitting Form Php Mysql Strtotime
I am converting date time format to Strtotime for form submit but getting 10sec wrong time. And if the form is idle for 10 minutes , it will get 10 minutes ago after form submit. Please help me. i am beginner

Here is Form.php

```<code><form action="index.php " method="post" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<input type="file" name="image" />
<input type="hidden" name="date" value="<?php echo date('Y-m-d H:i:s', strtotime($date));?>">
</code>```

Here is Mysql.php

```<code>$date = $_POST['date'];
</code>```

GET.php

```<code>echo "<div id='ts'>".$timeago=get_timeago(strtotime($row['date']))."</div>";
</code>```

Here is my sql

```<code>CREATE TABLE `posts` (
  `date` timestamp NOT NULL CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
</code>```

答:
You generate the time server side with

```<code><?php echo date('Y-m-d H:i:s', strtotime($date));?>
</code>```

This is the server time of the page load. It will never change on the client side, therefore this is the time you get on form submission.

ContentLicense: CC BY-SA 3.0

Body:
I am converting date time format to Strtotime for form submit but getting 10sec wrong time. And if the form is idle for 10 minutes , it will get 10 minutes ago after form submit. Please help me. i am beginner

Here is Form.php

<form action="index.php " method="post" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<input type="file" name="image" />
<input type="hidden" name="date" value="<?php echo date('Y-m-d H:i:s', strtotime($date));?>">

Here is Mysql.php

$date = $_POST['date'];

GET.php

echo "
".$timeago=get_timeago(strtotime($row['date']))."
";

Here is my sql

CREATE TABLE `posts` (
  `date` timestamp NOT NULL CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

Body:
You generate the time server side with

<?php echo date('Y-m-d H:i:s', strtotime($date));?>

This is the server time of the page load. It will never change on the client side, therefore this is the time you get on form submission.


问:
Unbalanced Elasticsearch Performance
We have an Elasticsearch cluster with 9 nodes with the following settings:

Elasticsearch Version 5.1.2

One Index in Cluster

Primary Shard Storage Size: 3GB

Number of Shards: 5

Number of Replica: 3

Node-1, Node-2 and Node-3 Master Only Nodes

Node-4 through Node-9 Data Only Nodes

No Parent Child Relationship in Mappings

Each node 24 GB of Ram, 18 Cores of CPU

Disabled Swaped, Increased Open File Descriptor, 12 GB JVM Heap Memory

Nest Client 'Static' Adaptor And List of all Nodes IPs

As you see we have an over allocation of resources on our nodes but under stress test only one node uses all it's available search threads. As I mentioned we have 18 cores and according to default search thread limit we have (3*18/2)+1 = 28 search threads in each node.

Problems:

Http Requests Are Not Balanced

Other nodes don't use all their search threads. One nodes uses It's all  threads and It's search queue gets large

What we have tested:

- Use one coordinator node to balance requests (no change)

How we send requests:

- We use Elasticsearch as a Search Engine and a Jmeter is used to put stress test on search services. Test services are web services which call Some SearchTemplates using Elasticsearch Nest Client

Any idea is appreciated.

答:
Have a read of
https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/connection-pooling.html

Looks like you're using the SingleNodeConnectionPool which is used when you use the low ceremony ElasticClient, i.e.

var client = new ElasticClient(uri);

In this case, all your requests will be sent to one node which needs to act as a Coordinator node described here:

https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html

A search request, for example, is executed in two phases which are
  coordinated by the node which receives the client request — the
  coordinating node.

In the scatter phase, the coordinating node forwards the request to
  the data nodes which hold the data. Each data node executes the
  request locally and returns its results to the coordinating node. In
  the gather phase, the coordinating node reduces each data node’s
  results into a single global resultset.

Every node is implicitly a coordinating node. This means that a node
  that has all three node.master, node.data and node.ingest set to false
  will only act as a coordinating node, which cannot be disabled. As a
  result, such a node needs to have enough memory and CPU in order to
  deal with the gather phase.

StaticConnectionPool or SniffingConnectionPool would be a better choice for your cluster.

Title: Unbalanced Elasticsearch Performance


问:
Why is my AngularJS TreeView not working?
I am trying to use this interesting looking Angular treeview component, with no luck.

I know it is not a browser issue, because when I load it up from jsfiddle it works fine. (Tried it in Chrome latest version and IE, both on Windows)

I will paste a few poignant parts downloaded from the GIThub usage instructions.

```<code><html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script type="text/javascript" src="/angular.treeview.js"></script>
    <link rel="stylesheet" type="text/css" href="css/angular.treeview.css">
    <script>
        (function () {
            //angular module
            var myApp = angular.module('myApp', ['angularTreeview']);
            //test controller
            myApp.controller('myController', function ($scope) {
                //test tree model 1

                $scope.roleList1 = [
                    { "roleName": "User", "roleId": "role1", "children": [
                        { "roleName": "subUser1", "roleId": "role11", "children": [] },
                        { "roleName": "subUser2", "roleId": "role12", "children": [
                            { "roleName": "subUser2-1", "roleId": "role121", "children": [
                                                        . . .
                ];
    </script>
</head>
<body>
<div ng-app="myApp">
    <div ng-controller="myController">
        <div>
            <input type="button" value="TREE MODEL 1" data-ng-click="roleList = roleList1"/>
            <input type="button" value="TREE MODEL 2" data-ng-click="roleList = roleList2"/>
        </div>
        <div style="margin:10px 0 30px 0; padding:10px; background-color:#EEEEEE; border-radius:5px; font:12px Tahoma;">
            <span><b>Selected Node</b> : {{currentNode.roleName}}</span>
        </div>
        <div
                data-angular-treeview="true"
                data-tree-model="roleList"
                data-node-id="roleId"
                data-node-label="roleName"
                data-node-children="children">
        </div>
    </div>
</div>
</body>
</code>```

This is what I see when viewing the page. Clicking the buttons does nothing.

Does anyone know what I might be doing wrong?

答:
Please check the value what you are passing.
you are calling it like *data-tree-model="roleList" * but in data you have written roleList1.

I Think that is the issue.

Body:
I am trying to use this interesting looking Angular treeview component, with no luck.

I know it is not a browser issue, because when I load it up from jsfiddle it works fine. (Tried it in Chrome latest version and IE, both on Windows)

I will paste a few poignant parts downloaded from the GIThub usage instructions.

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

            <input type="button" value="TREE MODEL 1" data-ng-click="roleList = roleList1"/>
            <input type="button" value="TREE MODEL 2" data-ng-click="roleList = roleList2"/>

            Selected Node : {{currentNode.roleName}}

This is what I see when viewing the page. Clicking the buttons does nothing.

Does anyone know what I might be doing wrong?


问:
Search multiple words in differnt table at a time in Mysql php

   0)

       {

      while($row = mysqli_fetch_array($result))

        {

echo $company_data[] = $row;

        }

             }

          else

           {

       echo 'Data not Found';

             }

          }

             ?>

答:
Refer Insert Query.

Your code should have condition-

if ($rest)


问:
Drag 'n Drop Element targeting
so i was programming (with a friend) a Drag 'n Drop system with elements (here buttons) for HTML in plain JS. Then i realised, what if i have multiple element on this page? Answer: All these are being affected. So i said... okay! i just increasingly add a value to the id, then the whole thing won't interfere.

So now I've got the Problem, that i can't know which element is being targeted... or better: which id is being targeted.

PS: Please JS only no JQuery and no Frameworks.

PPS: (I already looked through Stackoverflow etc for this situation, nothing very suiting to my case, at least i didn't found one)

```<code>    var pressed = 0;

    function drag(state){
        if(state == true){
           pressed = 1;
        }
        else{
           pressed = 0;
        }
    }
  var obj = "";
    onmousemove = function(a){
        if(pressed == 1){
    obj = document.getElementById("move1"); //<-- This var (obj) needs to be "flexible" to any element, not only the element with the id "move1"
            var x = a.clientX - parseInt(obj.style.width) / 2;
            var y = a.clientY - parseInt(obj.style.height) / 2;
            obj.style.left = x + "px";
            obj.style.top = y + "px";
        }
    }

var counter = 0;

function createbutton() {
counter++;
document.getElementById("surface").innerHTML += "<button id = 'move" + counter + "' style = 'width: 100px; height: 100px; background-color: blue; border: none; position: fixed;' onmousedown = 'drag(true)' onmouseup = 'drag(false)' onClick = 'drag(false)'>Move this Button</button>";
}
</code>```

`
Note: This doesn't include HTML because somehow Stackoverflow does not show properly, so only JS, pls visit JSFiddle to see full (create multiple Buttons and drag the last one!): https://jsfiddle.net/2nyc4a83/

答:
I added a new parameter to your function drag(). On the events onmousedown, onmouseup and onClick the id of the current object will be used as an argument for drag(). Example for how this looks in the code: <button ... onmousedown = 'drag(true, this.id)'>Move this button</button>

The id will then be saved in a global variable so that you can later access it in the onmousemove function like this:

```<code>obj = document.getElementById(obj_id);
</code>```

-> jsfiddle

Title: Drag 'n Drop Element targeting

Body:
so i was programming (with a friend) a Drag 'n Drop system with elements (here buttons) for HTML in plain JS. Then i realised, what if i have multiple element on this page? Answer: All these are being affected. So i said... okay! i just increasingly add a value to the id, then the whole thing won't interfere.

So now I've got the Problem, that i can't know which element is being targeted... or better: which id is being targeted.

PS: Please JS only no JQuery and no Frameworks.

PPS: (I already looked through Stackoverflow etc for this situation, nothing very suiting to my case, at least i didn't found one)

    var pressed = 0;

    function drag(state){
        if(state == true){
           pressed = 1;
        }
        else{
           pressed = 0;
        }
    }
  var obj = "";
    onmousemove = function(a){
        if(pressed == 1){
    obj = document.getElementById("move1"); //<-- This var (obj) needs to be "flexible" to any element, not only the element with the id "move1"
            var x = a.clientX - parseInt(obj.style.width) / 2;
            var y = a.clientY - parseInt(obj.style.height) / 2;
            obj.style.left = x + "px";
            obj.style.top = y + "px";
        }
    }

var counter = 0;

function createbutton() {
counter++;
document.getElementById("surface").innerHTML += "<button id = 'move" + counter + "' style = 'width: 100px; height: 100px; background-color: blue; border: none; position: fixed;' onmousedown = 'drag(true)' onmouseup = 'drag(false)' onClick = 'drag(false)'>Move this Button</button>";
}

`
Note: This doesn't include HTML because somehow Stackoverflow does not show properly, so only JS, pls visit JSFiddle to see full (create multiple Buttons and drag the last one!): https://jsfiddle.net/2nyc4a83/

Body:
I added a new parameter to your function drag(). On the events onmousedown, onmouseup and onClick the id of the current object will be used as an argument for drag(). Example for how this looks in the code: <button ... onmousedown = 'drag(true, this.id)'>Move this button</button>

The id will then be saved in a global variable so that you can later access it in the onmousemove function like this:

obj = document.getElementById(obj_id);

-> jsfiddle


问:
react-native-fbsdk error: package com.facebook.reactnative.androidsdk does not exist
recently i've been trying to setup facebooksdk into my react-native apps. I've gone through a lot of post, but i'm still getting a lot of errors during setup.

i follow guide, and i install using npm react-native-fbsdk@0.6.0 ( because latest version have error ) and i ran react-native link react-native-fbsdk

Below is my setup

MainApplicaiton.Java

```<code>package com.ddc;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

  protected static CallbackManager getCallbackManager() {
    return mCallbackManager;
  }

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new FBSDKPackage(mCallbackManager),
          new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    FacebookSdk.sdkInitialize(getApplicationContext());
  }
}
</code>```

MainActivity.Java

```<code>package com.ddc;

import com.facebook.react.ReactActivity;
import android.content.Intent;

public class MainActivity extends ReactActivity {

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "DDC";
    }
}
</code>```

My build.gradle

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.ddc"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-vector-icons')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}
</code>```

This is the result I've got

答:
Add this lines into your gradle.build : </p>

```<code>compile(project(':react-native-fbsdk')) {
 exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
}
compile('com.facebook.android:facebook-android-sdk:4.22.1')
</code>```

Body:
recently i've been trying to setup facebooksdk into my react-native apps. I've gone through a lot of post, but i'm still getting a lot of errors during setup.

i follow guide, and i install using npm react-native-fbsdk@0.6.0 ( because latest version have error ) and i ran react-native link react-native-fbsdk

Below is my setup

MainApplicaiton.Java

package com.ddc;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

  protected static CallbackManager getCallbackManager() {
    return mCallbackManager;
  }

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new FBSDKPackage(mCallbackManager),
          new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    FacebookSdk.sdkInitialize(getApplicationContext());
  }
}

MainActivity.Java

package com.ddc;

import com.facebook.react.ReactActivity;
import android.content.Intent;

public class MainActivity extends ReactActivity {

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "DDC";
    }
}

My build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.ddc"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-vector-icons')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

This is the result I've got

Body:
Add this lines into your gradle.build :

compile(project(':react-native-fbsdk')) {
 exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
}
compile('com.facebook.android:facebook-android-sdk:4.22.1')


问:
Sending iMessage via Messages.app using Javascript for Automation (JXA)
I have been attempting to create a JavaScript for Automation script to send an iMessage via the Messages app on Yosemite 10.10.2 (the end goal to write a solution to allow backoffice tasks to iMessage failure statuses etc.).

The script executes through without error in Script Editor, however no message is sent and nothing shows or happens in Messages.app.  Although my service and buddy below are obfuscated, my script with the real values retrieves the correct service and buddy (as verified by doing a messages.displayAlert() for both the service and buddy name).  The only output I get from the script is an "undefined" for the service.send() which I assume is correct since that method has a void return type).  This script below is what I've been unsuccessfully trying to get working:

```<code>messages = Application('Messages');

service = messages.services["E:foo@bar.com"];
buddy = service.buddies["+61nnnnnnnnn"]

service.send({
    send: "Hello World",
    to: buddy
});
</code>```

The equivalent AppleScript script (below) successfully works:

```<code>tell application "Messages"
    send "Hello World" to buddy "+61nnnnnnnnn" of service "E:foo@bar.com"
end tell
</code>```

答:
You need to call the send method on your messages instance, not service.
Like this:

messages.send("hello", {to: buddy})

Also, the message you're sending should be a top level parameter as in my example above.

Body:
I have been attempting to create a JavaScript for Automation script to send an iMessage via the Messages app on Yosemite 10.10.2 (the end goal to write a solution to allow backoffice tasks to iMessage failure statuses etc.).

The script executes through without error in Script Editor, however no message is sent and nothing shows or happens in Messages.app.  Although my service and buddy below are obfuscated, my script with the real values retrieves the correct service and buddy (as verified by doing a messages.displayAlert() for both the service and buddy name).  The only output I get from the script is an "undefined" for the service.send() which I assume is correct since that method has a void return type).  This script below is what I've been unsuccessfully trying to get working:

messages = Application('Messages');

service = messages.services["E:foo@bar.com"];
buddy = service.buddies["+61nnnnnnnnn"]

service.send({
    send: "Hello World",
    to: buddy
});

The equivalent AppleScript script (below) successfully works:

tell application "Messages"
    send "Hello World" to buddy "+61nnnnnnnnn" of service "E:foo@bar.com"
end tell


问:
Reverse The Words In A Sentence But Not The Letters
I want to make a program to reverse the words only, not the letters.

For example...

```<code>i love india
</code>```

... should become...

```<code>india love i
</code>```

Another example...

```<code> google is the best website
</code>```

... should become...

```<code> website best the is google
</code>```

With spaces I have thoroughly researched on it but found just nothing.

My logic is that I should just give you my program that is not working.  If you find a small error in my code please give the solution for it and a corrected copy of my program.  Also, if you are not too busy, can you please give me the logic in a flow chart.

my logic is here

Thank you for your time.

答:
1.
Store the words of each line in a string array.
2.
Print the elements of the array from the last item to the first.</p>

Body:
I want to make a program to reverse the words only, not the letters.

For example...

i love india

... should become...

india love i

Another example...

 google is the best website

... should become...

 website best the is google

With spaces I have thoroughly researched on it but found just nothing.

My logic is that I should just give you my program that is not working.  If you find a small error in my code please give the solution for it and a corrected copy of my program.  Also, if you are not too busy, can you please give me the logic in a flow chart.

my logic is here

Thank you for your time.


问:
PHP File send mail every time when opened explicitly
I have a contact page which made with the help of PHPMailer. The minimal code is as follows

```<code><form class="form-horizontal" method="POST" action="Mail.php" name="contactForm">
...
</form>
</code>```

This works perfectly fine, but whenever I try to open Mail.php explicitly on the webserver, the webserver sends blank email every time. Here's a screenshot of email whenever I access Mail.php

Below is the minimal code from PHPMailer's Mail.php

```<code>$mail->Subject = $subject;
    $mail->Body    = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
    $mail->AltBody = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;

        if(!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
        else {
            echo "Message has been sent....You're being redirected.....";
            }
</code>```

How can I restrict the user to explicitly access Mail.php?

答:
So, as suggested by Jiri Hrazdil and Ahmad Mobaraki, using isset should solve my problem, but I couldn't figure out how to implement that. So I came up with my own solution. I check, if the variables are empty in the first place, So this way if anyone directly tries to access the file it'll show a message the Fields are empty, This is the way I did it.

```<code>require 'PHPMailer/PHPMailerAutoload.php';
$yourName = $_POST['yourName'];
$sender  = $_POST['emailID'];
$subject  = $_POST['subject'];
$message  = $_POST['message'];
$to = 'email@email.com';
header('Refresh: 5; URL=whatever.php');

if(empty($yourName) || empty($sender) || empty($subject) || empty($message) || empty($message))
{
    echo "Fields are empty";
}
else
{
    //Working Code of PHP Mailer
}
</code>```

Body:
I have a contact page which made with the help of PHPMailer. The minimal code is as follows

<form class="form-horizontal" method="POST" action="Mail.php" name="contactForm">
...
</form>

This works perfectly fine, but whenever I try to open Mail.php explicitly on the webserver, the webserver sends blank email every time. Here's a screenshot of email whenever I access Mail.php

Below is the minimal code from PHPMailer's Mail.php

$mail->Subject = $subject;
    $mail->Body    = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;
    $mail->AltBody = "From: ". $sender. "
" ." Name: ". $yourName. "
". " Message Body " .$message;

        if(!$mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
        else {
            echo "Message has been sent....You're being redirected.....";
            }

How can I restrict the user to explicitly access Mail.php?

Body:
So, as suggested by Jiri Hrazdil and Ahmad Mobaraki, using isset should solve my problem, but I couldn't figure out how to implement that. So I came up with my own solution. I check, if the variables are empty in the first place, So this way if anyone directly tries to access the file it'll show a message the Fields are empty, This is the way I did it.

require 'PHPMailer/PHPMailerAutoload.php';
$yourName = $_POST['yourName'];
$sender  = $_POST['emailID'];
$subject  = $_POST['subject'];
$message  = $_POST['message'];
$to = 'email@email.com';
header('Refresh: 5; URL=whatever.php');

if(empty($yourName) || empty($sender) || empty($subject) || empty($message) || empty($message))
{
    echo "Fields are empty";
}
else
{
    //Working Code of PHP Mailer
}


问:
Mysql get min, avg and latest from two tables(products and products-prices)
I have two Mysql tables:

products with id, name, link

products-prices with id, id_prod, price, availability and date

In the second one, as you can see I can have more prices for the same product depending on the time it was updated, what I want to do is to have one query to show me the lowest price, average price and latest price. I can get first two (lowest and average price) in one query and latest price in another query but I don't know how to concatenate them or if there is another way.

My first query looks like that:

```<code>SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
GROUP BY
    ids
ORDER BY
    ids
</code>```

and the second one is:

```<code>SELECT *
FROM `products-prices`
WHERE date IN (SELECT DISTINCT MAX(date) max_date
               FROM `products-prices`
               GROUP BY id_produs)
</code>```

Can you give me an idea how to combine them? Thank you very much!

(I don't know how UNION works and if it works, I will try it)

//EDIT: And I also have another question, can I get the MIN, AVG values without the latest entry in database ?

答:
This is an untested solution, please let me know if it helps</p>

```<code>SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim,
    latest.`date` as latest_date,
    latest.price as latest_price
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
INNER JOIN
    (select id_produs, price, `date`
     from `products-prices` t1
     where not exists (select 1
                       from `products-prices` t2
                       where t1.`date` < t2.`date` and t1.id_produs = t2.id_produs)
     group by id_produs
    ) latest
ON
    latest.id_produs = products.id
GROUP BY
    ids
ORDER BY
    ids
</code>```

Body:
I have two Mysql tables:

products with id, name, link

products-prices with id, id_prod, price, availability and date

In the second one, as you can see I can have more prices for the same product depending on the time it was updated, what I want to do is to have one query to show me the lowest price, average price and latest price. I can get first two (lowest and average price) in one query and latest price in another query but I don't know how to concatenate them or if there is another way.

My first query looks like that:

SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
GROUP BY
    ids
ORDER BY
    ids

and the second one is:

SELECT *
FROM `products-prices`
WHERE date IN (SELECT DISTINCT MAX(date) max_date
               FROM `products-prices`
               GROUP BY id_produs)

Can you give me an idea how to combine them? Thank you very much!

(I don't know how UNION works and if it works, I will try it)

//EDIT: And I also have another question, can I get the MIN, AVG values without the latest entry in database ?

Body:
This is an untested solution, please let me know if it helps

SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim,
    latest.`date` as latest_date,
    latest.price as latest_price
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
INNER JOIN
    (select id_produs, price, `date`
     from `products-prices` t1
     where not exists (select 1
                       from `products-prices` t2
                       where t1.`date` < t2.`date` and t1.id_produs = t2.id_produs)
     group by id_produs
    ) latest
ON
    latest.id_produs = products.id
GROUP BY
    ids
ORDER BY
    ids


问:
How much memory your program takes? (FastMM vs Borland MM)
I have seen recently a strange behavior in my program. After creating large amounts of objects (500MB of RAM) then releasing them, the program's memory footprint does not return to its original size. It still shows a footprint of 160MB (Private working set).

Normal behavior?

Borland's memory manager does not behave like this, so if possible please confirm (or infirm) this is a normal behavior for FastMM: If you have a handy program in which you create a rather complex MDI child (containing several controls/objects), can you create in a loop 250 instances of that MDI child in memory (at the same time) then release them all and check the memory footprint. Please make sure that you consume at least 200-300MB or RAM with those MDI childs.

Especially those that still using Delphi 7 can see the difference by temporary disabling FastMM.

Thanks

If anybody is interested, especially if you want some proof this is not a memory leak (I hope it is not a mem leak in my code - this is also one of the points of this post: to check if it is my fault), here are the original discussions:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答:
IIRC, the Delphi memory manager does not immediately return free'd memory to the OS.

Memory is allocated in chunks of small, medium and large sizes, called blocks.
These blocks are kept for a while after their contents have been disposed to have them readyly available when another allocation is requested afterwards.

This limits the amount of system calls required for succesive allocation of multiple objects, and helps avoiding heap fragmentation.

ContentLicense: CC BY-SA 2.5


问:
React or React Native to start learning
I have to work on project which has mobile application as well as web development too.For Mobile Application Development React Native has chosen but for Web development React has chosen.

I am new to React and confused from where i have to start learning. It should be React or React Native?

Thanks in advance for your answer.

答: I would recommend to first start learning React, and then move on to React Native as React Native builds on React, and assumes you are already familiar with it. As pointed out by Vucko, the official documentation is a great place for information, otherwise you are interested in reading a book instead, check out Learning React functional web development with react and redux by alex banks and eve porcello, this helped me figure out a lot of things, and also covers redux which you might be using in the future.</p>

Title: React or React Native to start learning


问:
efficiency working with dates in R
I have a function that I use to calculate the difference between two dates. I have a dataset with over 400K records, and I am having difficulty with getting it to work at scale.

The function:

```<code>library(lubridate)
get_recency <- function(last_gift_date, refresh_date) {
  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  case_when(
    is.na(last_gift_date) ~ "ERROR",
    last_gift_date > refresh_date ~ "ERROR",
    last_gift_date %m+% months(12) >= refresh_date ~ "0-12",
    last_gift_date %m+% months(24) >= refresh_date ~ "13-24",
    last_gift_date %m+% months(36) >= refresh_date ~ "25-36",
    last_gift_date %m+% months(48) >= refresh_date ~ "37-48",
    last_gift_date %m+% months(60) >= refresh_date ~ "49-60",
    last_gift_date %m+% months(72) >= refresh_date ~ "61-72",
    last_gift_date %m+% months(84) >= refresh_date ~ "73-84",
    TRUE ~ "85+")
}
</code>```

If I pass a single date into the refresh_date parameter it seems to execute fine, however when I pass an equivalent length vector in, it takes super long.

Any thoughts on how to improve this would be appreciated.

Example to run the code:

```<code>a<- c("2014-01-29", "2015-04-07", "2015-04-10")
b<- c(NA, "2014-01-29", "2015-04-07")
get_recency(b,a)

# OUTPUT
#[1] "ERROR" "13-24" "0-12"
</code>```

UPDATE 2017-07-10
I took the advise of @Akrun and made use of the cut() function. It has the benefit of being quicker and more succinct code. Results below.

```<code>get_recency <- function(last_gift_date, refresh_date) {
  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  x <- (as.yearmon(refresh_date)-as.yearmon(last_gift_date))*12

  x <- replace(x, is.na(x), -Inf)

  cut(x, breaks = c(-Inf, -0.000001, 12, 24, 36, 48, 60, 72, 84, Inf),
      labels = c("ERROR", "0-12", "13-24", "25-36", "37-48",
                 "49-60", "61-72", "73-84", "85+"),
      include.lowest = T)
}
</code>```

答:
```<code>library(lubridate)
library(dplyr)

a <- c("2014-01-29", "2015-04-07", "2015-04-10", "2025-04-10")
b <- c(NA, "2014-01-29", "2015-04-07", "2015-04-07")
intervals <- 12 * 1:7

get_recency <- function(last_gift_date, refresh_date, intervals) {

  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  intervals_chr <- c(
    "ERROR",
    paste(c(0, intervals[-length(intervals)] + 1), intervals, sep = "-"),
    paste0(tail(intervals, 1) + 1, "+")
  )

  code <- sapply(c(0, intervals), function(n) {
    last_gift_date %m+% months(n) < refresh_date
  }) %>%
    rowSums()

  if_else(condition = is.na(code), true = "ERROR",
          false = intervals_chr[code + 1])
}

get_recency(b, a, intervals)

[1] "ERROR" "13-24" "0-12"  "85+"
</code>```

Is this faster?

Title: efficiency working with dates in R

Body:
I have a function that I use to calculate the difference between two dates. I have a dataset with over 400K records, and I am having difficulty with getting it to work at scale.

The function:

library(lubridate)
get_recency <- function(last_gift_date, refresh_date) {
  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  case_when(
    is.na(last_gift_date) ~ "ERROR",
    last_gift_date > refresh_date ~ "ERROR",
    last_gift_date %m+% months(12) >= refresh_date ~ "0-12",
    last_gift_date %m+% months(24) >= refresh_date ~ "13-24",
    last_gift_date %m+% months(36) >= refresh_date ~ "25-36",
    last_gift_date %m+% months(48) >= refresh_date ~ "37-48",
    last_gift_date %m+% months(60) >= refresh_date ~ "49-60",
    last_gift_date %m+% months(72) >= refresh_date ~ "61-72",
    last_gift_date %m+% months(84) >= refresh_date ~ "73-84",
    TRUE ~ "85+")
}

If I pass a single date into the refresh_date parameter it seems to execute fine, however when I pass an equivalent length vector in, it takes super long.

Any thoughts on how to improve this would be appreciated.

Example to run the code:

a<- c("2014-01-29", "2015-04-07", "2015-04-10")
b<- c(NA, "2014-01-29", "2015-04-07")
get_recency(b,a)

# OUTPUT
#[1] "ERROR" "13-24" "0-12"

UPDATE 2017-07-10
I took the advise of @Akrun and made use of the cut() function. It has the benefit of being quicker and more succinct code. Results below.

get_recency <- function(last_gift_date, refresh_date) {
  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  x <- (as.yearmon(refresh_date)-as.yearmon(last_gift_date))*12

  x <- replace(x, is.na(x), -Inf)

  cut(x, breaks = c(-Inf, -0.000001, 12, 24, 36, 48, 60, 72, 84, Inf),
      labels = c("ERROR", "0-12", "13-24", "25-36", "37-48",
                 "49-60", "61-72", "73-84", "85+"),
      include.lowest = T)
}

Body:
library(lubridate)
library(dplyr)

a <- c("2014-01-29", "2015-04-07", "2015-04-10", "2025-04-10")
b <- c(NA, "2014-01-29", "2015-04-07", "2015-04-07")
intervals <- 12 * 1:7

get_recency <- function(last_gift_date, refresh_date, intervals) {

  last_gift_date <- as.Date(last_gift_date)
  refresh_date <- as.Date(refresh_date)

  intervals_chr <- c(
    "ERROR",
    paste(c(0, intervals[-length(intervals)] + 1), intervals, sep = "-"),
    paste0(tail(intervals, 1) + 1, "+")
  )

  code <- sapply(c(0, intervals), function(n) {
    last_gift_date %m+% months(n) < refresh_date
  }) %>%
    rowSums()

  if_else(condition = is.na(code), true = "ERROR",
          false = intervals_chr[code + 1])
}

get_recency(b, a, intervals)

[1] "ERROR" "13-24" "0-12"  "85+"

Is this faster?


问:
How to cut box corner Using CSS with transparent background?
I want to cut left top corner of a box using CSS like this.

keep in mind that background is transparent.

答:
Nearly the same solution as OriDrori's answer but more flexible (if you need fixed-width cutted corner).

This gradient will look the same regardless of .card width and height.

body {
  background: purple;
}

.card {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, transparent 20px, white 20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card"></div></code>```

Body:
Nearly the same solution as OriDrori's answer but more flexible (if you need fixed-width cutted corner).

This gradient will look the same regardless of .card width and height.

body {
  background: purple;
}

.card {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, transparent 20px, white 20px);
}

<div class="card"></div>


问:
Laravel 5.4 Mail error on Heroku deployment
I have a Laravel app that I deployed in Heroku. I do not know how to configure the mail. This is what I did with the config\mail.php

```<code><?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    'port' => env('MAIL_PORT', 587),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'myemail@gmail.com'),
        'name' => env('MAIL_FROM_NAME', 'My App'),
    ],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => 'myemail@gmail.com',
    'password' => 'mypassword',
    'sendmail' => '/usr/sbin/sendmail -bs',
    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

I get the following exception.

```<code>SwiftTransportException:
    Failed to authenticate on SMTP server with username "myemail@email.com" using 2 possible authenticators`
</code>```

My .env is here, I searched this problem, but none of it worked.

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls
</code>```

答:
Did you update your environments variable in heroku dashboard or using command line.

As far I know, heroku does not read variables from .env. Thus, Swiftmailer is using credentials in your config/mail.php not from .env file.

So it's attempting to us

```<code>'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
</code>```

instead of

```<code>MAIL_HOST=smtp.gmail.com
</code>```

Also, the error says @email.com instead of @gmail.com do you have a typo somewhere?

Body:
I have a Laravel app that I deployed in Heroku. I do not know how to configure the mail. This is what I did with the config\mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    'port' => env('MAIL_PORT', 587),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'myemail@gmail.com'),
        'name' => env('MAIL_FROM_NAME', 'My App'),
    ],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => 'myemail@gmail.com',
    'password' => 'mypassword',
    'sendmail' => '/usr/sbin/sendmail -bs',
    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

I get the following exception.

SwiftTransportException:
    Failed to authenticate on SMTP server with username "myemail@email.com" using 2 possible authenticators`

My .env is here, I searched this problem, but none of it worked.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls

Body:
Did you update your environments variable in heroku dashboard or using command line.

As far I know, heroku does not read variables from .env. Thus, Swiftmailer is using credentials in your config/mail.php not from .env file.

So it's attempting to us

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

instead of

MAIL_HOST=smtp.gmail.com

Also, the error says @email.com instead of @gmail.com do you have a typo somewhere?


问:
access EC2 Ubuntu instance's localhost address from local web browser using port forwarding
I have a Linux Ubuntu instance running on AWS EC2. On this instance I have a service running on localhost:8889, which means the service runs on port 8889 on the instance's localhost.

I want to access this localhost address from my Mac. I've already tried to access it using the following addresses but none has worked:

```<code>http://<public-dns>:8889
http://<public-ip>:8889
http://<private-ip>:8889
</code>```

I've also tried to search for it in Google, but so far none if the methods worked for me, including associating an Elastic IP address to the instance and editing the Inbound and Outbound rules on the security group to allow the port to everyone.

I have read something about Port Forwarding but I'm not sure that I'm completely understanding it. I have understand the idea of it, but I didn't understand how to do it.

If you could please help me figure out how to access to the instance's localhost using port forwarding that would be great. I realized it has something to do with the terminal, but I didn't understand where I need to run the command (on the Mac or on the instance), and what are the parameters I need to use.

答:
In your case, the service jupyter-notebook is listening to localhost interface only so you'll not be able to access from the IP of the server.

A simple solution would be to start using a specific config.

```<code>$ Jupiter-notebook --config=jupyter_notebook_config.py
</code>```

and in your jupyter_notebook_config.py file to have at minimum the property

```<code>c.NotebookApp.ip = "0.0.0.0"
</code>```

You can review the doc for all details on possible config. By listening on 0.0.0.0 the service will be accessible on the different IP (duns, private or public IP)

Body:
I have a Linux Ubuntu instance running on AWS EC2. On this instance I have a service running on localhost:8889, which means the service runs on port 8889 on the instance's localhost.

I want to access this localhost address from my Mac. I've already tried to access it using the following addresses but none has worked:

http://<public-dns>:8889
http://<public-ip>:8889
http://<private-ip>:8889

I've also tried to search for it in Google, but so far none if the methods worked for me, including associating an Elastic IP address to the instance and editing the Inbound and Outbound rules on the security group to allow the port to everyone.

I have read something about Port Forwarding but I'm not sure that I'm completely understanding it. I have understand the idea of it, but I didn't understand how to do it.

If you could please help me figure out how to access to the instance's localhost using port forwarding that would be great. I realized it has something to do with the terminal, but I didn't understand where I need to run the command (on the Mac or on the instance), and what are the parameters I need to use.

Body:
In your case, the service jupyter-notebook is listening to localhost interface only so you'll not be able to access from the IP of the server.

A simple solution would be to start using a specific config.

$ Jupiter-notebook --config=jupyter_notebook_config.py

and in your jupyter_notebook_config.py file to have at minimum the property

c.NotebookApp.ip = "0.0.0.0"

You can review the doc for all details on possible config. By listening on 0.0.0.0 the service will be accessible on the different IP (duns, private or public IP)


问:
prompt user to enter the size of box and also the character to be used to draw the box then proceed to draw box using these two values
I've been trying to figure this out for a while now and am in need of help.

Prompt user to enter the size of box and

also the character to be used to draw the box then proceed to draw
  box using these two values.

For ex:

```<code>Enter size of box : 3
Enter character to use : %
%%%
%%%
%%%
</code>```

Your task in this question is to implement the same result but now
  the drawing of the box will be done in a function called print_box()

You will prompt for user to enter the character to use and size of box
  as shown

And then call the function print_box() passing the two values obtained
  in line

ex:

```<code>char_to_use = input('Enter a character: ')
size = int(input('Size of the box?: '))
print_box (char_to_use, size)
</code>```

Sample run :

```<code>Enter a character: ^
Size of the box?:4
^^^^
^^^^
^^^^
^^^^
</code>```

答:
Function needs to print size rows of size characters, so you can use for loop and repeating a string with * operator. Like this:

def print_box(c, s):
    for r in range(s):
        print(c * s)

char_to_use = input('Enter a character: ')
size = int(input('Size of the box?: '))
print_box(char_to_use, size)
```

Body:
I've been trying to figure this out for a while now and am in need of help.

Prompt user to enter the size of box and

also the character to be used to draw the box then proceed to draw
  box using these two values.

For ex:

Enter size of box : 3
Enter character to use : %
%%%
%%%
%%%

Your task in this question is to implement the same result but now
  the drawing of the box will be done in a function called print_box()

You will prompt for user to enter the character to use and size of box
  as shown

And then call the function print_box() passing the two values obtained
  in line

ex:

char_to_use = input('Enter a character: ')
size = int(input('Size of the box?: '))
print_box (char_to_use, size)

Sample run :

Enter a character: ^
Size of the box?:4
^^^^
^^^^
^^^^
^^^^


问:
Error "UserInfo has no default constructor"
I'm having trouble with my app. The error says "UserInfo has no default constructor".

This is my Java code in UserInfo.

```<code>package com.example.christian.loginapp2;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class UserInfo extends Activity {
    SharedPreferences.Editor edit;
    SharedPreferences pref;

    private static final String PREF_NAME = "userinfo";
    private static final String KEY_UNAME = "uname";
    private static final String KEY_PASS = "pass";
    private static final String KEY_FNAME = "fname";
    private static final String KEY_MNAME = "mname";
    private static final String KEY_LNAME = "lname";
    private static final String KEY_BDATE = "bdate";
    private static final String KEY_CONTACT = "contact";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        final TextView tvUsername = (TextView) findViewById(R.id.tvUsername);
        final TextView tvPassword = (TextView) findViewById(R.id.tvPassword);
        final TextView tvFirstname = (TextView) findViewById(R.id.tvFirstname);
        final TextView tvMiddlename = (TextView) findViewById(R.id.tvMiddlename);
        final TextView tvLastname = (TextView) findViewById(R.id.tvLastname);
        final TextView tvBirthdate = (TextView) findViewById(R.id.tvBirthdate);
        final TextView tvContact = (TextView) findViewById(R.id.tvContact);

        String uname = pref.getString(KEY_UNAME, "");
        String pass = pref.getString(KEY_PASS, "");
        String fname = pref.getString(KEY_FNAME, "");
        String mname = pref.getString(KEY_MNAME, "");
        String lname = pref.getString(KEY_LNAME, "");
        String bdate = pref.getString(KEY_BDATE, "");
        String contact = pref.getString(KEY_CONTACT, "");

        tvUsername.setText(uname);
        tvPassword.setText(pass);
        tvFirstname.setText(fname);
        tvMiddlename.setText(mname);
        tvLastname.setText(lname);
        tvBirthdate.setText(bdate);
        tvContact.setText(contact);

    }

    public void cacheUserInfo(String uname, String pass, String fname, String mname, String lname, String bdate, String contact) {
        edit.putString(KEY_UNAME, uname);
        edit.putString(KEY_PASS, pass);
        edit.putString(KEY_FNAME, fname);
        edit.putString(KEY_MNAME, mname);
        edit.putString(KEY_LNAME, lname);
        edit.putString(KEY_BDATE, bdate);
        edit.putString(KEY_CONTACT, contact);
        edit.commit();
    }

    public UserInfo(Context c){
        pref = c.getSharedPreferences(PREF_NAME, 0);
        edit = pref.edit();
        edit.apply();
    }
}
</code>```

I am a beginner in Android Studio and Java.

答:
Do remove this constructor:

```<code>public UserInfo(Context c){
    pref = c.getSharedPreferences(PREF_NAME, 0);
    edit = pref.edit();
    edit.apply();
}
</code>```

And move this line (which is the only one needed, since you are only reading, not editing the preferences) in the onCreate() method:

```<code>pref = c.getSharedPreferences(PREF_NAME, 0);
</code>```

Body:
I'm having trouble with my app. The error says "UserInfo has no default constructor".

This is my Java code in UserInfo.

package com.example.christian.loginapp2;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class UserInfo extends Activity {
    SharedPreferences.Editor edit;
    SharedPreferences pref;

    private static final String PREF_NAME = "userinfo";
    private static final String KEY_UNAME = "uname";
    private static final String KEY_PASS = "pass";
    private static final String KEY_FNAME = "fname";
    private static final String KEY_MNAME = "mname";
    private static final String KEY_LNAME = "lname";
    private static final String KEY_BDATE = "bdate";
    private static final String KEY_CONTACT = "contact";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        final TextView tvUsername = (TextView) findViewById(R.id.tvUsername);
        final TextView tvPassword = (TextView) findViewById(R.id.tvPassword);
        final TextView tvFirstname = (TextView) findViewById(R.id.tvFirstname);
        final TextView tvMiddlename = (TextView) findViewById(R.id.tvMiddlename);
        final TextView tvLastname = (TextView) findViewById(R.id.tvLastname);
        final TextView tvBirthdate = (TextView) findViewById(R.id.tvBirthdate);
        final TextView tvContact = (TextView) findViewById(R.id.tvContact);

        String uname = pref.getString(KEY_UNAME, "");
        String pass = pref.getString(KEY_PASS, "");
        String fname = pref.getString(KEY_FNAME, "");
        String mname = pref.getString(KEY_MNAME, "");
        String lname = pref.getString(KEY_LNAME, "");
        String bdate = pref.getString(KEY_BDATE, "");
        String contact = pref.getString(KEY_CONTACT, "");

        tvUsername.setText(uname);
        tvPassword.setText(pass);
        tvFirstname.setText(fname);
        tvMiddlename.setText(mname);
        tvLastname.setText(lname);
        tvBirthdate.setText(bdate);
        tvContact.setText(contact);

    }

    public void cacheUserInfo(String uname, String pass, String fname, String mname, String lname, String bdate, String contact) {
        edit.putString(KEY_UNAME, uname);
        edit.putString(KEY_PASS, pass);
        edit.putString(KEY_FNAME, fname);
        edit.putString(KEY_MNAME, mname);
        edit.putString(KEY_LNAME, lname);
        edit.putString(KEY_BDATE, bdate);
        edit.putString(KEY_CONTACT, contact);
        edit.commit();
    }

    public UserInfo(Context c){
        pref = c.getSharedPreferences(PREF_NAME, 0);
        edit = pref.edit();
        edit.apply();
    }
}

I am a beginner in Android Studio and Java.

Body:
Do remove this constructor:

public UserInfo(Context c){
    pref = c.getSharedPreferences(PREF_NAME, 0);
    edit = pref.edit();
    edit.apply();
}

And move this line (which is the only one needed, since you are only reading, not editing the preferences) in the onCreate() method:

pref = c.getSharedPreferences(PREF_NAME, 0);


问:
Ignore URL resolving in third-party CSS files
I am using Webpack with the configuration below to compile my CSS. In my CSS I am importing some CSS files from NPM packages - e.g. @import '../../node_modules/slick-carousel/slick/slick-theme.scss'; - that contain URLs which it cannot resolve.

Is it possible to disable URL resolving for these imported CSS files specifically? Since I am overwriting these styles anyway with my own CSS I don't need Webpack to handle these.

Example error:

```<code>ERROR in ./node_modules/css-loader?{"minimize":false}!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js?{}!./src/css/style.scss
Module not found: Error: Can't resolve './ajax-loader.gif' in '/.../css'
@ ./node_modules/css-loader?{"minimize":false}!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js?{}!./src/css/style.scss 6:9840-9868
@ ./src/css/style.scss
@ ./src/js/app.js
@ multi ./src/js/app.js
</code>```

Excerpt from webpack.config.js:

```<code>{
    test: /\.(scss)$/,
    use: [
        'style-loader',
        {
            loader: 'css-loader',
            options: {
                minimize: false
            },
        },
        'postcss-loader',
        {
          loader: 'sass-loader',
          options: {
          }
        }
    ]
  }
</code>```

答:
css-loader is the loader which parses your CSS and resolves URLs and @import()s, so you need to make sure that you do not use css-loader for any files in your node_modules directory. You will need two separate rules:

{
  test: /\.scss$/,
  exclude: /\/node_modules\//,
  use: [
    'style-loader',
    'css-loader',
    'postcss-loader',
    'sass-loader',
  ],
},
{
  test: /\.scss$/,
  include: /\/node_modules\//,
  use: [
    'style-loader',
    'postcss-loader',
    'sass-loader',
  ],
},
```

Body:
I am using Webpack with the configuration below to compile my CSS. In my CSS I am importing some CSS files from NPM packages - e.g. @import '../../node_modules/slick-carousel/slick/slick-theme.scss'; - that contain URLs which it cannot resolve.

Is it possible to disable URL resolving for these imported CSS files specifically? Since I am overwriting these styles anyway with my own CSS I don't need Webpack to handle these.

Example error:

ERROR in ./node_modules/css-loader?{"minimize":false}!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js?{}!./src/css/style.scss
Module not found: Error: Can't resolve './ajax-loader.gif' in '/.../css'
@ ./node_modules/css-loader?{"minimize":false}!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js?{}!./src/css/style.scss 6:9840-9868
@ ./src/css/style.scss
@ ./src/js/app.js
@ multi ./src/js/app.js

Excerpt from webpack.config.js:

{
    test: /\.(scss)$/,
    use: [
        'style-loader',
        {
            loader: 'css-loader',
            options: {
                minimize: false
            },
        },
        'postcss-loader',
        {
          loader: 'sass-loader',
          options: {
          }
        }
    ]
  }


问:
Sublime text in Ubuntu-Unity. Open file in current workspace
I have four workspaces (call them "spaces" or "desktops" if you like) in Ubuntu, with Unity on. I have multiple Sublime Text 2 windows open in each of them. If I open a new file from Nautilus in desktop 1, the file may be opened in any of the other desktops, depending on which of the Sublime windows has been opened last. Is there any way to change this behaviour to a more natural one, i.e. open the file in the most recent window of the workspace I am actually in?  </p>

答:
You can edit the application launcher of Sublime Text. It can be found in /usr/share/applications/sublime-text.desktop.

To do so just run sudo nano /usr/share/applications/sublime-text.desktop & add -n to the Exec= line so it looks like -

Exec=/opt/sublime_text/sublime_text -n %F

Also to note- on some systems sublime will cause cursor run on when used from the context menu. If that's the case while the .desktop is open to edit scroll down to the StartupNotify=true line & make it StartupNotify=false. This will prevent cursor run on...

Note: This may not be the exact thing you want. But this enables sublime text to open files in a new window, within the currently active workspace.


问:
Getting wrong time after Submitting Form Php Mysql Strtotime
I am converting date time format to Strtotime for form submit but getting 10sec wrong time. And if the form is idle for 10 minutes , it will get 10 minutes ago after form submit. Please help me. i am beginner

Here is Form.php

```<code><form action="index.php " method="post" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<input type="file" name="image" />
<input type="hidden" name="date" value="<?php echo date('Y-m-d H:i:s', strtotime($date));?>">
</code>```

Here is Mysql.php

```<code>$date = $_POST['date'];
</code>```

GET.php

```<code>echo "<div id='ts'>".$timeago=get_timeago(strtotime($row['date']))."</div>";
</code>```

Here is my sql

```<code>CREATE TABLE `posts` (
  `date` timestamp NOT NULL CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
</code>```

答:
Use strtotime in Mysql.php, it will store the current time at insertion.

```<code>$date=date('Y-m-d H:i:s', strtotime($date));
</code>```

Body:
I am converting date time format to Strtotime for form submit but getting 10sec wrong time. And if the form is idle for 10 minutes , it will get 10 minutes ago after form submit. Please help me. i am beginner

Here is Form.php

<form action="index.php " method="post" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<input type="file" name="image" />
<input type="hidden" name="date" value="<?php echo date('Y-m-d H:i:s', strtotime($date));?>">

Here is Mysql.php

$date = $_POST['date'];

GET.php

echo "
".$timeago=get_timeago(strtotime($row['date']))."
";

Here is my sql

CREATE TABLE `posts` (
  `date` timestamp NOT NULL CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

Body:
Use strtotime in Mysql.php, it will store the current time at insertion.

$date=date('Y-m-d H:i:s', strtotime($date));


问:
partial matching from middle in completion suggestion elasticsearch
I have a field named search_suggest having the below

```<code>search_suggest: {
   type: "completion",
   analyzer: "simple",
   payloads: true,
   preserve_separators: false,
   preserve_position_increments: false,
  max_input_length: 50
}
</code>```

It has values indexed as

```<code>{
  input: [
   "apple iphone 6"
  ],
  output: "apple iphone 6",
  weight: 5,
  payload: {
   category: "mobiles"
  }
}
</code>```

If I searched for apple ,It is giving me results. But If I search for iphone it is not giving me any results.

Is there any way in completion suggester to do this?.
Do i have to index input as

apple iphone 6

iphone 6

6

I am aware of edge-ngram suggester. But the cons is it will suggest duplicates also.

Please help.

答:
If anyone still looking for answers,

Completion suggester is suitable for prefix matches. So, in input, you can provide the possible suffixes of your phrase. This will allow you to do prefix searches even if you start from the middle, aka sub string searches.

For example:

```<code>{
  "text" : "Courtyard by Marriot Munich City",
  "text_suggest" : {
    "input": [
      "Courtyard by Marriot Munich City",
      "by Marriot Munich City",
      "Marriot Munich City",
      "Munich City",
      "City"
    ],
    "output" : "Courtyard by Marriot Munich City",
    "weight" : 11,
    "payload": { "id" : 314159 }
  }
}
</code>```

As you can see, wherever you start within "Courtyard by Marriot Munich City" you will get results. (Except may be for "by" because in most cases it will be discarded as a stop word).

Going up to 4-5 steps are well enough for general search strings. Also, if you handle stop-words with a filter, no need to worry about stop words in input.

Sample index analyzer

```<code>{
  "settings" : {
    "analysis" : {
      "filter" : {
        "suggester_stop" : {
          "type" : "stop",
          "stopwords" : "_english_",
          "remove_trailing" : false,
          "ignore_case" : true
        },
        "suggester_stemmer" : {
          "type" : "stemmer",
          "name" : "light_english"
        }
      },
      "analyzer" : {
        "suggester_analyzer" : {
          "type" : "custom",
          "tokenizer" : "standard",
          "char_filter" : ["html_strip"],
          "filter" : [
            "standard",
            "lowercase",
            "suggester_stop",
            "suggester_stemmer"
          ]
        }
      }
    }
  }
}
</code>```

This will solve the problem you mentioned in one of your comments:

Then if I suggest for "apple ip", It won't give result.
  How about iphone 6?

```<code>{
  "text_suggest" : {
    "input": [
      "apple iphone 6",
      "iphone 6"
    ],
    "output" : "apple iphone 6",
    "weight" : 11
  }
}
</code>```

You will get search results for both "apple ip", "iphone 6" etc. However you will not get result for "apple 6" which is not that common for people to search anyway.

Body:
I have a field named search_suggest having the below

search_suggest: {
   type: "completion",
   analyzer: "simple",
   payloads: true,
   preserve_separators: false,
   preserve_position_increments: false,
  max_input_length: 50
}

It has values indexed as

{
  input: [
   "apple iphone 6"
  ],
  output: "apple iphone 6",
  weight: 5,
  payload: {
   category: "mobiles"
  }
}

If I searched for apple ,It is giving me results. But If I search for iphone it is not giving me any results.

Is there any way in completion suggester to do this?.
Do i have to index input as

apple iphone 6

iphone 6

6

I am aware of edge-ngram suggester. But the cons is it will suggest duplicates also.

Please help.

Body:
If anyone still looking for answers,

Completion suggester is suitable for prefix matches. So, in input, you can provide the possible suffixes of your phrase. This will allow you to do prefix searches even if you start from the middle, aka sub string searches.

For example:

{
  "text" : "Courtyard by Marriot Munich City",
  "text_suggest" : {
    "input": [
      "Courtyard by Marriot Munich City",
      "by Marriot Munich City",
      "Marriot Munich City",
      "Munich City",
      "City"
    ],
    "output" : "Courtyard by Marriot Munich City",
    "weight" : 11,
    "payload": { "id" : 314159 }
  }
}

As you can see, wherever you start within "Courtyard by Marriot Munich City" you will get results. (Except may be for "by" because in most cases it will be discarded as a stop word).

Going up to 4-5 steps are well enough for general search strings. Also, if you handle stop-words with a filter, no need to worry about stop words in input.

Sample index analyzer

{
  "settings" : {
    "analysis" : {
      "filter" : {
        "suggester_stop" : {
          "type" : "stop",
          "stopwords" : "_english_",
          "remove_trailing" : false,
          "ignore_case" : true
        },
        "suggester_stemmer" : {
          "type" : "stemmer",
          "name" : "light_english"
        }
      },
      "analyzer" : {
        "suggester_analyzer" : {
          "type" : "custom",
          "tokenizer" : "standard",
          "char_filter" : ["html_strip"],
          "filter" : [
            "standard",
            "lowercase",
            "suggester_stop",
            "suggester_stemmer"
          ]
        }
      }
    }
  }
}

This will solve the problem you mentioned in one of your comments:

Then if I suggest for "apple ip", It won't give result.
  How about iphone 6?

{
  "text_suggest" : {
    "input": [
      "apple iphone 6",
      "iphone 6"
    ],
    "output" : "apple iphone 6",
    "weight" : 11
  }
}

You will get search results for both "apple ip", "iphone 6" etc. However you will not get result for "apple 6" which is not that common for people to search anyway.


问:
Why do parenthesis make such a difference?
I wrote a code that returns the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. Here's my code:

```<code>def duplicate_count(text):
    sum_low = 0
    dic_low = []
    sum_up = 0
    dic_up = []
    sum_num = 0
    dic_num = []
    total = 0
    for i in text:
    if i.isalpha():
        if i.islower() and text.count(i) > 1 and i not in dic_low:
            dic_low.append(i)
            sum_low = sum_low + 1
        elif i.isupper() and text.count(i) > 1 and i not in dic_up:
            dic_up.append(i)
            sum_up = sum_up + 1
    elif i.isdigit() and text.count(i) > 1 and i not in dic_num:
        dic_num.append(i)
        sum_num = sum_num + 1
    total = sum_low + sum_up + sum_num
    print (total)
</code>```

The problem is, I noticed that when I missed parenthesis after "if i.isalpha()" this code worked perfectly with alphabetic characters but appeared to ignore digits, so for instance if I passed "aabbcdeBBAA" it printed "4", but if the argument was "11336" it printed "0". Later I found out that the parenthesis had been missed and corrected it, and the code started to work normally, but I still don't understand what the problem was. There was no any TraceBack, so I guess the problem was in missing parenthesis. Why does it make such a big difference?

PS: sorry if the code is too weird, I'm new to programming and just started to learn coding.
Thank you!

答:
i.isalpha is an object (the method isalpha of your string i). It is not Null, nor does it correspond to a falsy value like 0, "", [] etc., so if checked for its boolean value, it is evaluated as True.

Only by adding (), you actually call  that method.

A practical tip: There is a common beginners' mistake with file handles: myfile.close doesn't close the file myfile, only myfile.close() does. But the first statement is syntactically valid and will not raise an error. You just might be wondering why the file you just wrote is empty...

Body:
I wrote a code that returns the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. Here's my code:

def duplicate_count(text):
    sum_low = 0
    dic_low = []
    sum_up = 0
    dic_up = []
    sum_num = 0
    dic_num = []
    total = 0
    for i in text:
    if i.isalpha():
        if i.islower() and text.count(i) > 1 and i not in dic_low:
            dic_low.append(i)
            sum_low = sum_low + 1
        elif i.isupper() and text.count(i) > 1 and i not in dic_up:
            dic_up.append(i)
            sum_up = sum_up + 1
    elif i.isdigit() and text.count(i) > 1 and i not in dic_num:
        dic_num.append(i)
        sum_num = sum_num + 1
    total = sum_low + sum_up + sum_num
    print (total)

The problem is, I noticed that when I missed parenthesis after "if i.isalpha()" this code worked perfectly with alphabetic characters but appeared to ignore digits, so for instance if I passed "aabbcdeBBAA" it printed "4", but if the argument was "11336" it printed "0". Later I found out that the parenthesis had been missed and corrected it, and the code started to work normally, but I still don't understand what the problem was. There was no any TraceBack, so I guess the problem was in missing parenthesis. Why does it make such a big difference?

PS: sorry if the code is too weird, I'm new to programming and just started to learn coding.
Thank you!


问:
error in loading module in angular Js
I have search a lot for finding problem in my code but didn't get solution. I'm trying routing in html file there are two links 1 for view1 and second for view2 code for both views are in different files in folder named parts and in js file i have created a module named mymodule my problem is when i remove "mymodule" from an-app in html file then {{ studname }} works fine but after adding "mymodule" i'm getting error

html file code :

```<code><!DOCTYPE html>
<html ng-app="mymodule">
  <head>
    <title>Try Deep linking</title>
    <script src="angular.min.js"></script>
    <script type="text/javascript" src="route.min.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
  </head>
  <body>
    <input type="text" name="" ng-model="studname" />
    <p>{{ studname }}</p>
    <div ng-view>

    </div>
    <a href="#/view1">View 1</a>
    <a href="#/view2">View 2</a>
  </body>
</html>
</code>```

JS code :

```<code>var myapp = angular.module("mymodule",[]);

myapp.controller( "mycontroller", function ($scope) {
   $scope.student = [
      {name : "Abhay Sehgal", city: "Delhi" },
      {name : "Pankaj Singh", city: "Bihar" },
      {name : "ujjwal", city : "UP"}
   ];
});

myapp.config(function($routeProvider){
    $routeProvider
    .when('/view1',{
        controller : "mycontroller",
        templateUrl : "parts/view1.html"
    })
    .when('/view2',{
        controller : "mycontroller",
        templateUrl : "parts/view2.html"
    })
    .otherwise({redirectTo :'/'});
});
</code>```

Thanks in advance

答:
You need to add the dependency ngRoute to your module,

```<code>var myapp = angular.module("mymodule",['ngRoute']);
</code>```

Title: error in loading module in angular Js

Body:
I have search a lot for finding problem in my code but didn't get solution. I'm trying routing in html file there are two links 1 for view1 and second for view2 code for both views are in different files in folder named parts and in js file i have created a module named mymodule my problem is when i remove "mymodule" from an-app in html file then {{ studname }} works fine but after adding "mymodule" i'm getting error

html file code :

<!DOCTYPE html>

    <title>Try Deep linking</title>

    <input type="text" name="" ng-model="studname" />

{{ studname }}

    View 1
    View 2

JS code :

var myapp = angular.module("mymodule",[]);

myapp.controller( "mycontroller", function ($scope) {
   $scope.student = [
      {name : "Abhay Sehgal", city: "Delhi" },
      {name : "Pankaj Singh", city: "Bihar" },
      {name : "ujjwal", city : "UP"}
   ];
});

myapp.config(function($routeProvider){
    $routeProvider
    .when('/view1',{
        controller : "mycontroller",
        templateUrl : "parts/view1.html"
    })
    .when('/view2',{
        controller : "mycontroller",
        templateUrl : "parts/view2.html"
    })
    .otherwise({redirectTo :'/'});
});

Thanks in advance

Body:
You need to add the dependency ngRoute to your module,

var myapp = angular.module("mymodule",['ngRoute']);


问:
Qt could not create directory
I am new in Qt platform. I am trying to run and build a project in Qt but I have stumbled upon a bunch errors. I have found solutions to some of them and other I did not. Which leads me to ask you guys this question.
When I build/run my project it is giving me this error:

Could not create directory "C:\Users\name\Documents\Error in "
  Util.asciify("build-untitled9-Android_for_armeabi_v7a_GCC_4_9_Qt_5_6_2-Debug")":
  TypeError: Property 'asciify' of object
  Core::Internal::UtilsJsExtension(0x34d22c8) is not a function" Error
  while building/deploying project untitled9 (kit: Android for
  armeabi-v7a (GCC 4.9, Qt 5.6.2)) When executing step "qmake"

Does anyone know how to solve the problem? Thanks

答:
I met the error too!
You can try this method:

Tools -> Options -> Build&Run -> General

Then reset the "Default build directory".

My "Default build directory"  is "../build-%{CurrentProject:Name}-%{CurrentKit:FileSystemName}-%{CurrentBuild:Name}"

Finally
Restart the QT and create new project. The setting can take effect.

Title: Qt could not create directory


问:
Send data from fragment to activity android C#
i'm new to xamarin android. i want to send data from fragment to MainActivity.
i searched google a lot almost all of them was in Java.</p>

答:
You can do that by using Delegates:

Define delegates in your Fragment class

```<code>namespace Awesome.Android {
     public class AwesomeFragment : Fragment {

       public delegate void OnAwesomePress (int number);
       public event OnAwesomePress sendOnAwesomePressEvent;
     }
}
</code>```

You can assign it when you create a Framgent

```<code>AwesomeFragment fragment = new AwesomeFragment ();
fragment.OnAwesomePress += OnAwesomePress;
</code>```

After that, you implement OnAwesomePress in your activity

```<code>private void OnAwesomePress (int number) {

}
</code>```

Now, when you call sendOnAwesomePressEvent in your Fragment, that event will be passed to Activity.

```<code>sendOnAwesomePressEvent (10);
</code>```

Body:
You can do that by using Delegates:

Define delegates in your Fragment class

namespace Awesome.Android {
     public class AwesomeFragment : Fragment {

       public delegate void OnAwesomePress (int number);
       public event OnAwesomePress sendOnAwesomePressEvent;
     }
}

You can assign it when you create a Framgent

AwesomeFragment fragment = new AwesomeFragment ();
fragment.OnAwesomePress += OnAwesomePress;

After that, you implement OnAwesomePress in your activity

private void OnAwesomePress (int number) {

}

Now, when you call sendOnAwesomePressEvent in your Fragment, that event will be passed to Activity.

sendOnAwesomePressEvent (10);