问:
Discard variables through use of dot and dollar
I'm a Haskell beginner and I want to know why we can discard certain variables when using certain operators, for example:

```<code>     last xs = head (reverse xs)
     last'   = head . reverse
</code>```

Another example:

```<code>     example p xs = length (filter p xs)
     example' p = length . filter p
</code>```

Why can't we toss the p in this function?

答:
You don't “discard” the variables there, you merely don't mention them. The process is called eta-conversion: thanks to referential transparency, when you define

```<code>g x = f x
</code>```

you might just as well simply write g = f. This also works when f is not already a named function, like

```<code>last' xs = (head . reverse) xs
 ⇒ last' =  head . reverse
</code>```

But this requires that the variable actually turns up only as the final argument to a self-contained function, e.g. one that is already named or enclosed in parens. For instance, with your original last this is not possible because the xs occurs in the parenthesis (reverse xs), hence you first need to transform head (reverse xs) ≡ (head . reverse) xs before you can η-reduce it. Likewise,

```<code>length . filter p ≡ length . (filter p)
</code>```

so you can't just reduce the p because it's inside a parenthesis. You can however, as bereal suggests, consider the precomposition (length .) as a seperate function that's applied to the rest of the expression:

```<code>length . filter p
  ≡ (length .) (filter p)
  ≡ ((length .) . filter) p
example' = (length .) . filter
</code>```

But I agree that this makes the code rather harder to read, hence I'd normally leave example' as it is.

Body:
I'm a Haskell beginner and I want to know why we can discard certain variables when using certain operators, for example:

     last xs = head (reverse xs)
     last'   = head . reverse

Another example:

     example p xs = length (filter p xs)
     example' p = length . filter p

Why can't we toss the p in this function?

Body:
You don't “discard” the variables there, you merely don't mention them. The process is called eta-conversion: thanks to referential transparency, when you define

g x = f x

you might just as well simply write g = f. This also works when f is not already a named function, like

last' xs = (head . reverse) xs
 ⇒ last' =  head . reverse

But this requires that the variable actually turns up only as the final argument to a self-contained function, e.g. one that is already named or enclosed in parens. For instance, with your original last this is not possible because the xs occurs in the parenthesis (reverse xs), hence you first need to transform head (reverse xs) ≡ (head . reverse) xs before you can η-reduce it. Likewise,

length . filter p ≡ length . (filter p)

so you can't just reduce the p because it's inside a parenthesis. You can however, as bereal suggests, consider the precomposition (length .) as a seperate function that's applied to the rest of the expression:

length . filter p
  ≡ (length .) (filter p)
  ≡ ((length .) . filter) p
example' = (length .) . filter

But I agree that this makes the code rather harder to read, hence I'd normally leave example' as it is.


来源: stackexchange

问:
CSS to remove the spacing between the lines
Is it possible to remove the spacing between the two center align text?

HTML :

```<code>  <div id="content2">
       <p class="t1">Discover</p>
       <p class="t1">Discover</p>
    </div>
</code>```

CSS:

```<code>    #content2 {
        clear: both;
        overflow: auto;
    }

    .t1 {
      font-weight: bold;
      font-size:60px;
      color: black;
        text-align: center;
    }

p {
    font-size : 30px;
    padding : 0;
    margin : 30px;
    line-height : 20px;
}
</code>```

Codepen : https://codepen.io/jayvicious/pen/owNJRr

I'm also adapting from this thread :
Remove spacing between

When I increase the line height , the spacing between the content2 and p also increase.

I'm looking for similar output to this :

Each time I increase the line height, it also affect the spacing of the first pharagraph
 and the content2

答:
You can use Two class for a paragraph and margin-top Property for it.

#content2 {
 clear: both;
 overflow: auto;
}

.t1 {

  font-weight: bold;
  font-size:60px;
  color: black;
  text-align: center;

}

p {
    font-size : 30px;
    padding : 0;
    margin : 30px;
    line-height : 20px;
}

.t {
  margin-top: -20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div id="content2">
       <p class="t1">test</p>
       <p class="t1 t">test</p>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to remove the spacing between the two center align text?

HTML :

Discover

Discover

CSS:

    #content2 {
        clear: both;
        overflow: auto;
    }

    .t1 {
      font-weight: bold;
      font-size:60px;
      color: black;
        text-align: center;
    }

p {
    font-size : 30px;
    padding : 0;
    margin : 30px;
    line-height : 20px;
}

Codepen : https://codepen.io/jayvicious/pen/owNJRr

I'm also adapting from this thread :
Remove spacing between

When I increase the line height , the spacing between the content2 and p also increase.

I'm looking for similar output to this :

Each time I increase the line height, it also affect the spacing of the first pharagraph
 and the content2

Body:
You can use Two class for a paragraph and margin-top Property for it.

#content2 {
 clear: both;
 overflow: auto;
}

.t1 {

  font-weight: bold;
  font-size:60px;
  color: black;
  text-align: center;

}

p {
    font-size : 30px;
    padding : 0;
    margin : 30px;
    line-height : 20px;
}

.t {
  margin-top: -20px;
}

  <div id="content2">
       <p class="t1">test</p>
       <p class="t1 t">test</p>
</div>


问:
String literal Vs Unicode literal Vs unicode type object - Memory representation
Python 2.x doc says,

Unicode string is a sequence of code points

Unicode strings are expressed as instances of the unicode type

```<code>>>> ThisisNotUnicodeString = 'a정정' # What is the memory representation?
>>> ThisisNotUnicodeString
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> type(ThisisNotUnicodeString)
<type 'str'>
>>> a = u'a정정' # Which encoding technique used to represent in memory? utf-8?
>>> a
u'a\uc815\uc815\U0001f49b'
>>> type(a)
<type 'unicode'>
>>> b = unicode('a정정', 'utf-8')
>>> b
u'a\uc815\uc815\U0001f49b'
>>> c = unicode('a정정', 'utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
>>>
</code>```

Question:

1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

2) Which encoding technique used to represent unicode literal a in memory? utf-8?  If yes, How to know the number of bytes occupied?

3) Why c is not represented in memory, using utf-16 technique?

答:
1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

In the interactive prompt, which encoding will be used to encode Python 2.X's str type depends on your shell encoding, for example if you run the terminal under a Linux system with the encoding of the terminal being UTF-8:

```<code>>>> s = "a정정"
>>> s
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
</code>```

Now try to change the encoding from your terminal window to something else, in this case I've changed the shell's encoding from UTF-8 to WINDOWS-1250:

```<code> >>> s = "a???"
</code>```

If you try this with a tty session you get a diamonds instead of ? at least under Ubuntu you may get different characters.

As you can conclude which encoding will be used to determine the encoding of str in the interactive prompt is shell-dependent. This applies to code run interactively under Python interpreter, code that's not run interactively will raise an exception:

```<code>#main.py
s = "a정정"
</code>```

Trying to run the code raises SynatxError:

```<code>$ python main.py
SyntaxError: Non-ASCII character '\xec' in file main.py...
</code>```

This is because Python 2.X uses ASCII by default:

```<code>>>> sys.getdefaultencoding()
'ascii'
</code>```

Then, you have to specifiy the encoding explicity in your code by doing this:

```<code>#main.py
#*-*encoding:utf-8*-*
s = "a정정"
</code>```

2) Which encoding technique used to represent unicode literal a in memory? utf-8? If yes, How to know the number of bytes occupied?

Keep in mind that the encoding scheme can differ if you run your code in different shells, I have tested this under Linux, this could be slightly different for Windows, so check your operating system's documentation.

To know the number of bytes occupied, use len:

```<code>>>> s = "a정정"
>>> len(s)
11
</code>```

s occupies exactly 11 bytes.

2) Which encoding technique used to represent unicode literal a in memory? utf-8? If yes, How to know the number of bytes occupied?

Well, it's a confusion, unicode type does not have encoding. It's just a sequence of Unicode character points (a.k.a U+0040 for Commercial At).

3) Why c is not represented in memory, using utf-16 technique?

UTF-8 is an encoding scheme that's different from UTF-16--UTF-8 represents characters' bytes differently from that of UTF-16. Here:

```<code>>>> c = unicode('a정정', 'utf-16')
</code>```

You're essentially doing this:

```<code>>>> "a정정"
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> unicode('a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b', 'utf-16')
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
</code>```

This is because you're trying to decode UTF-8 with UTF-16. Again, both use different number of bytes to represent characters, they're just two different encoding schemes--different ways to represent characters in bytes.

For your reference:
Python str vs unicode types

Body:
Python 2.x doc says,

Unicode string is a sequence of code points

Unicode strings are expressed as instances of the unicode type

>>> ThisisNotUnicodeString = 'a정정' # What is the memory representation?
>>> ThisisNotUnicodeString
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> type(ThisisNotUnicodeString)
<type 'str'>
>>> a = u'a정정' # Which encoding technique used to represent in memory? utf-8?
>>> a
u'a\uc815\uc815\U0001f49b'
>>> type(a)
<type 'unicode'>
>>> b = unicode('a정정', 'utf-8')
>>> b
u'a\uc815\uc815\U0001f49b'
>>> c = unicode('a정정', 'utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
>>>

Question:

1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

2) Which encoding technique used to represent unicode literal a in memory? utf-8?  If yes, How to know the number of bytes occupied?

3) Why c is not represented in memory, using utf-16 technique?

Body:
1) ThisisNotUnicodeString is string literal. Despite ThisisNotUnicodeString is not a unicode literal, Which encoding technique used to represent ThisisNotUnicodeString in memory? Because there should be some encoding technique to represent 정 or  character in memory.

In the interactive prompt, which encoding will be used to encode Python 2.X's str type depends on your shell encoding, for example if you run the terminal under a Linux system with the encoding of the terminal being UTF-8:

>>> s = "a정정"
>>> s
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'

Now try to change the encoding from your terminal window to something else, in this case I've changed the shell's encoding from UTF-8 to WINDOWS-1250:

 >>> s = "a???"

If you try this with a tty session you get a diamonds instead of ? at least under Ubuntu you may get different characters.

As you can conclude which encoding will be used to determine the encoding of str in the interactive prompt is shell-dependent. This applies to code run interactively under Python interpreter, code that's not run interactively will raise an exception:

#main.py
s = "a정정"

Trying to run the code raises SynatxError:

$ python main.py
SyntaxError: Non-ASCII character '\xec' in file main.py...

This is because Python 2.X uses ASCII by default:

>>> sys.getdefaultencoding()
'ascii'

Then, you have to specifiy the encoding explicity in your code by doing this:

#main.py
#*-*encoding:utf-8*-*
s = "a정정"

2) Which encoding technique used to represent unicode literal a in memory? utf-8? If yes, How to know the number of bytes occupied?

Keep in mind that the encoding scheme can differ if you run your code in different shells, I have tested this under Linux, this could be slightly different for Windows, so check your operating system's documentation.

To know the number of bytes occupied, use len:

>>> s = "a정정"
>>> len(s)
11

s occupies exactly 11 bytes.

2) Which encoding technique used to represent unicode literal a in memory? utf-8? If yes, How to know the number of bytes occupied?

Well, it's a confusion, unicode type does not have encoding. It's just a sequence of Unicode character points (a.k.a U+0040 for Commercial At).

3) Why c is not represented in memory, using utf-16 technique?

UTF-8 is an encoding scheme that's different from UTF-16--UTF-8 represents characters' bytes differently from that of UTF-16. Here:

>>> c = unicode('a정정', 'utf-16')

You're essentially doing this:

>>> "a정정"
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> unicode('a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b', 'utf-16')
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data

This is because you're trying to decode UTF-8 with UTF-16. Again, both use different number of bytes to represent characters, they're just two different encoding schemes--different ways to represent characters in bytes.

For your reference:
Python str vs unicode types


问:
program that determines if array is ascending, descending, or random(C language)
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

```<code>int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

i'd appreciate some guidance.

答:
I find some mistake in your program . please try using
 if (flag == 0) return 0;
instead of
 if (flag=0) return 0;</p>

Body:
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

i'd appreciate some guidance.


问:
loop through new.env() R (quantmod)
I am new to R, loop and quantmod.
I am trying to build a database that can be used be used easier for calculations (in a column format).

I was wondering how you would use a "loop" to automate the process below.
I am simply binding two datasets together.

As you can see, I have bound two datasets together using rbind, Google and Apple stock prices. If I was to have 100 stocks, this process would take a very long time, thus I was wondering how I could automate this process?

```<code>library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)
</code>```

Many thanks,

Shoups

Title: loop through new.env() R (quantmod)

Body:
I am new to R, loop and quantmod.
I am trying to build a database that can be used be used easier for calculations (in a column format).

I was wondering how you would use a "loop" to automate the process below.
I am simply binding two datasets together.

As you can see, I have bound two datasets together using rbind, Google and Apple stock prices. If I was to have 100 stocks, this process would take a very long time, thus I was wondering how I could automate this process?

library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)

Many thanks,

Shoups

Body:
The package tidyquant was created exactly for tasks like the one you asked for. Assuming that you updated the quantmod package to version 0.4-9, which again allows price downloads from YAHOO, the tq_get function will download the data and with "grouping by symbol” you will get the desired output.

> library(tidyquant)
stocks <- c("AAPL", "GOOG", "NFLX") %>%
     tq_get(get  = "stock.prices",
            from = "2010-01-01",
            to   = "2015-12-31") %>%
     group_by(symbol)

> stocks
Source: local data frame [4,527 x 8]
Groups: symbol [3]

# A tibble: 4,527 x 8
   symbol       date   open   high    low  close    volume
    <chr>     <date>  <dbl>  <dbl>  <dbl>  <dbl>     <dbl>
 1   AAPL 2010-01-04 213.43 214.50 212.38 214.01 123432400
 2   AAPL 2010-01-05 214.60 215.59 213.25 214.38 150476200
 3   AAPL 2010-01-06 214.38 215.23 210.75 210.97 138040000
 4   AAPL 2010-01-07 211.75 212.00 209.05 210.58 119282800
 5   AAPL 2010-01-08 210.30 212.00 209.06 211.98 111902700
 6   AAPL 2010-01-11 212.80 213.00 208.45 210.11 115557400
 7   AAPL 2010-01-12 209.19 209.77 206.42 207.72 148614900
 8   AAPL 2010-01-13 207.87 210.93 204.10 210.65 151473000
 9   AAPL 2010-01-14 210.11 210.46 209.02 209.43 108223500
10   AAPL 2010-01-15 210.93 211.60 205.87 205.93 148516900
# ... with 4,517 more rows, and 1 more variables: adjusted <dbl>


答:
Best you can do is to remove margin / padding from the p tag and adjust the line height.

As an example check this out https://codepen.io/anon/pen/bRGzNW

Html:

```<code><div id="content2">
   <p class="t1">testGg</p>
   <p class="t1">testgG</p>
   <p class="t1">testGg</p>
</div>
</code>```

Css:

```<code>#content2 {
    clear: both;
    overflow: auto;
}

.t1 {
    font-weight: bold;
    font-size:60px;
    line-height:60px;
    color: black;
    text-align: center;
}

p {
    padding : 0;
    margin : 0;
}
</code>```

Title: CSS to remove the spacing between the lines

Body:
Best you can do is to remove margin / padding from the p tag and adjust the line height.

As an example check this out https://codepen.io/anon/pen/bRGzNW

Html:

<div id="content2">
   <p class="t1">testGg</p>
   <p class="t1">testgG</p>
   <p class="t1">testGg</p>
</div>

Css:

#content2 {
    clear: both;
    overflow: auto;
}

.t1 {
    font-weight: bold;
    font-size:60px;
    line-height:60px;
    color: black;
    text-align: center;
}

p {
    padding : 0;
    margin : 0;
}


问:
Filter out data from Spark dataframe by priority rules using Spark
I have a dataframe df, some sample records are mentioned below:

**customers**   **product**   **val_id**
     1               A            1
     2               C            r
     3               B            X
     4               D            X
     5               E            1
     6               F            9
```

<p>I have some n number of rules that I have to apply on this data, Some sample rules are:</p>

<p><strong>Name:Rule 1, ID:1</strong></p>

<pre class="lang-none prettyprint-override"><code>filter out customers who have product A and B, rule priority is 1
</code>```

Name:Rule 2, ID:2

filter out customers who have product A, B,C and F, rule priority is 3
```

<p><strong>Name:Rule 3, ID:3</strong></p>

<pre class="lang-none prettyprint-override"><code>filter out customers who have product C and E, rule priority is 2
</code>```

Requirement is that create a new dataframe and filter out those customers which are passed from these rules and also mention from which rule they passed, customers who passed from priority 1 rule, should not be processed by lower priority rules and customers who passed from priority 2 rule, should not be processed by low priority rules and so on.

So my final dataframe should be:

**customers**   **product**   **val_id**   **rule_name**   **rule_id**
     1               A            1              Rule1           1
     2               C            r              Rule3           3
     3               B            X              Rule1           1
     5               E            1              Rule3           3
     6               F            9              Rule2           2
```

Can some one help me out to resolve this problem, using Spark Scala. Any help will be appreciated.

答:
You can solve it by defining udf functions for rule_name and rule_id columns as

```<code>def rule_name = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "Rule1"
  else if(Seq("A", "B", "C", "F").contains(product)) "Rule3"
  else if(Seq("C", "E").contains(product)) "Rule2"
  else ""
})

def rule_id = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "1"
  else if(Seq("A", "B", "C", "F").contains(product)) "3"
  else if(Seq("C", "E").contains(product)) "2"
  else ""
})
</code>```

Then call these udf functions using withColumn function as

```<code>val ruledDF = dataframe.withColumn("rule_name" , rule_name(col("product")))
  .withColumn("rule_id" , rule_id(col("product")))
</code>```

Finally filter out the rows with empty rules

```<code>ruledDF.filter(!(ruledDF("rule_name") === ""))
</code>```

That should have your requirements fulfilled.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe df, some sample records are mentioned below:

**customers**   **product**   **val_id**
     1               A            1
     2               C            r
     3               B            X
     4               D            X
     5               E            1
     6               F            9

I have some n number of rules that I have to apply on this data, Some sample rules are:

Name:Rule 1, ID:1

filter out customers who have product A and B, rule priority is 1

Name:Rule 2, ID:2

filter out customers who have product A, B,C and F, rule priority is 3

Name:Rule 3, ID:3

filter out customers who have product C and E, rule priority is 2

Requirement is that create a new dataframe and filter out those customers which are passed from these rules and also mention from which rule they passed, customers who passed from priority 1 rule, should not be processed by lower priority rules and customers who passed from priority 2 rule, should not be processed by low priority rules and so on.

So my final dataframe should be:

**customers**   **product**   **val_id**   **rule_name**   **rule_id**
     1               A            1              Rule1           1
     2               C            r              Rule3           3
     3               B            X              Rule1           1
     5               E            1              Rule3           3
     6               F            9              Rule2           2

Can some one help me out to resolve this problem, using Spark Scala. Any help will be appreciated.

Body:
You can solve it by defining udf functions for rule_name and rule_id columns as

def rule_name = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "Rule1"
  else if(Seq("A", "B", "C", "F").contains(product)) "Rule3"
  else if(Seq("C", "E").contains(product)) "Rule2"
  else ""
})

def rule_id = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "1"
  else if(Seq("A", "B", "C", "F").contains(product)) "3"
  else if(Seq("C", "E").contains(product)) "2"
  else ""
})

Then call these udf functions using withColumn function as

val ruledDF = dataframe.withColumn("rule_name" , rule_name(col("product")))
  .withColumn("rule_id" , rule_id(col("product")))

Finally filter out the rows with empty rules

ruledDF.filter(!(ruledDF("rule_name") === ""))

That should have your requirements fulfilled.


问:
UITableView tableView(_:didEndEditingRowAt:) not called if rapidly tapping during swipe
I have a UITableView with an editAction that is accessible by swiping left.

It seems like there is a built in UITableView functionality where if you swipe the cell to show the edit action, and then later tap anywhere in the tableView, the action is swiped closed automatically, and didEndEditingRowAt is called to notify the delegate that editing is over.

However, the problem I am seeing is that sometimes, if you swipe to the left and then really quickly after the swipe (when only a tiny piece of the edit action is visible and the animation is in progress), you tap anywhere else on the screen, the edit action is closed but the didEndEditingRowAt is not called!

So, with the following code, we end up with the tableView being in Edit Mode, but no view swiped open, and the last line printed being Will Edit, confirming that didEndEditingRowAt was never called.

```<code>  class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  let tableView = UITableView()

  override func viewDidLoad() {
    super.viewDidLoad()

    view = tableView
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "foo")
    tableView.delegate = self
    tableView.dataSource = self
    tableView.allowsSelectionDuringEditing = false
  }

  func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .normal, title: " Remove") {(_, indexPath) in print("OK") }
    return [deleteAction]
  }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}

  func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {}

  func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    return indexPath
  }

  func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    print("Will edit")
  }

  func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    print("Did end edit")
  }

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
  }

  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    return tableView.dequeueReusableCell(withIdentifier: "foo") ?? UITableViewCell()
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
  }
}
</code>```

Now, this only happens sometimes, and its a bit hard to get the timing right, but its definitely reproducible.

Here is a link to the whole demo: https://github.com/gregkerzhner/SwipeBugDemo

Am I doing or expecting something wrong here?  In my real project I have code that fades the other cells to focus on the cell being currently edited, and I end up in a bad state where the other cells get faded, but the focused cell doesn't have any edit actions open.

答:
So in the end, the working solution ended up a bit different from what @ncke and @hybridcattt suggested.

The problem with @ncke's solution is that the func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) does not get called during this swipe/tap interaction, so the workaround never gets called.

The problem with @hybridcattt's solution is that those UITableViewCell callbacks get called too early, so if you do the swipe rapid tap action, the UITableViewCellDeleteConfirmationView is still part of the subviews of the cell when all of those callbacks get called.

The best way seems to be to override the willRemoveSubview(_ subview: UIView) function of UITableViewCell.  This gets called reliably every time the UITableViewCellDeleteConfirmationView gets removed, both during normal swipe close, and also in this buggy swipe rapid tap scenario.

```<code>  protocol BugFixDelegate {
    func editingEnded(cell: UITableViewCell)
  }

  class CustomCell: UITableViewCell {
    weak var bugFixDelegate: BugFixDelegate?
    override func willRemoveSubview(_ subview: UIView) {
      guard String(describing: type(of: subview)) == "UITableViewCellDeleteConfirmationView" else {return }
      endEditing(true)
      bugFixDelegate.editingEnded(cell: self)
    }
  }
</code>```

As @hybridcattt and @ncke suggested, in your controller you can hook into this delegate and send the missing events to the UITableView and UITableViewDelegate like

```<code>class DummyController: UIViewController {
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? CustomCell else {return UITableViewCell()}

    cell.bugFixDelegate = self

  }
}

extension DummyController: BugFixDelegate {
  //do all the missing stuff that was supposed to happen automatically
  func editingEnded(cell: UITableViewCell) {
    guard let indexPath = self.tableView.indexPath(for: cell) else {return}
    self.tableView.setEditing(false, animated: false)
    self.tableView.delegate?.tableView?(tableView, didEndEditingRowAt: indexPath)
  }
}
</code>```

Body:
I have a UITableView with an editAction that is accessible by swiping left.

It seems like there is a built in UITableView functionality where if you swipe the cell to show the edit action, and then later tap anywhere in the tableView, the action is swiped closed automatically, and didEndEditingRowAt is called to notify the delegate that editing is over.

However, the problem I am seeing is that sometimes, if you swipe to the left and then really quickly after the swipe (when only a tiny piece of the edit action is visible and the animation is in progress), you tap anywhere else on the screen, the edit action is closed but the didEndEditingRowAt is not called!

So, with the following code, we end up with the tableView being in Edit Mode, but no view swiped open, and the last line printed being Will Edit, confirming that didEndEditingRowAt was never called.

  class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  let tableView = UITableView()

  override func viewDidLoad() {
    super.viewDidLoad()

    view = tableView
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "foo")
    tableView.delegate = self
    tableView.dataSource = self
    tableView.allowsSelectionDuringEditing = false
  }

  func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .normal, title: " Remove") {(_, indexPath) in print("OK") }
    return [deleteAction]
  }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}

  func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {}

  func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    return indexPath
  }

  func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    print("Will edit")
  }

  func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    print("Did end edit")
  }

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
  }

  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    return tableView.dequeueReusableCell(withIdentifier: "foo") ?? UITableViewCell()
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
  }
}

Now, this only happens sometimes, and its a bit hard to get the timing right, but its definitely reproducible.

Here is a link to the whole demo: https://github.com/gregkerzhner/SwipeBugDemo

Am I doing or expecting something wrong here?  In my real project I have code that fades the other cells to focus on the cell being currently edited, and I end up in a bad state where the other cells get faded, but the focused cell doesn't have any edit actions open.

Body:
So in the end, the working solution ended up a bit different from what @ncke and @hybridcattt suggested.

The problem with @ncke's solution is that the func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) does not get called during this swipe/tap interaction, so the workaround never gets called.

The problem with @hybridcattt's solution is that those UITableViewCell callbacks get called too early, so if you do the swipe rapid tap action, the UITableViewCellDeleteConfirmationView is still part of the subviews of the cell when all of those callbacks get called.

The best way seems to be to override the willRemoveSubview(_ subview: UIView) function of UITableViewCell.  This gets called reliably every time the UITableViewCellDeleteConfirmationView gets removed, both during normal swipe close, and also in this buggy swipe rapid tap scenario.

  protocol BugFixDelegate {
    func editingEnded(cell: UITableViewCell)
  }

  class CustomCell: UITableViewCell {
    weak var bugFixDelegate: BugFixDelegate?
    override func willRemoveSubview(_ subview: UIView) {
      guard String(describing: type(of: subview)) == "UITableViewCellDeleteConfirmationView" else {return }
      endEditing(true)
      bugFixDelegate.editingEnded(cell: self)
    }
  }

As @hybridcattt and @ncke suggested, in your controller you can hook into this delegate and send the missing events to the UITableView and UITableViewDelegate like

class DummyController: UIViewController {
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? CustomCell else {return UITableViewCell()}

    cell.bugFixDelegate = self

  }
}

extension DummyController: BugFixDelegate {
  //do all the missing stuff that was supposed to happen automatically
  func editingEnded(cell: UITableViewCell) {
    guard let indexPath = self.tableView.indexPath(for: cell) else {return}
    self.tableView.setEditing(false, animated: false)
    self.tableView.delegate?.tableView?(tableView, didEndEditingRowAt: indexPath)
  }
}


问:
Store many numbers as a single unique number
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

```<code>a = 2
b = 3
c = 5
d = 7
e = 13
</code>```

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?

答:
If you are storing, say, base 10 numbers, then do a conversion through base 11 numbers.  With the increased base, you have an extra 'digit'.  Use that digit as a separator.  So, three base 10 numbers "10, 42, 457" become "10A42A457": a single base 11 number (with 'A' as the additional digit).

Whatever base your original numbers are in, increase the base by 1 and concatenate, using the extra digit as a separator.  That will give you a single number in the increased base.

That single number can be stored in whatever number base you find convenient: binary, denary or hex for example.

To retrieve your original numbers just convert to base 11 (or whatever) and replace the extra digit with separators.

ETA: You don't have to use base 11.  The single number "10A42A457" is also a valid hexadecimal number, so any base of 11 or above could be used.  Hex may be easier to work with than base 11.

Body:
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

a = 2
b = 3
c = 5
d = 7
e = 13

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?


问:
iptables: block incoming traffic just for an apache VirtualHost domain
I am running an Ubuntu Server with Apache 2.4.7 and iptables 1.4.21.

Currently, I am hosting three domain names on my apache server using VirtualHost because I only have one IP address.

I was wondering if there is a way to use iptables to block an IP from reaching domain1.com, while allowing the same IP to reach domain2.com and domain3.com.

I am a n00b, so have patience with me, thank you! :)

Thank you for your replies!

答:
You can do that instead of using iptables, using the Apache config. Put on your VirtualHost apache config something like this:

```<code>order Allow,Deny
Deny from x.x.x.x
Allow from All
</code>```

Of course this will only work if you have module installed and enabled.

```<code>sudo apt-get install libapache2-modsecurity
sudo a2enmod mod-security
</code>```

Don't forget to restart the service after changes.

```<code>sudo service apache2 reload
</code>```

Body:
You can do that instead of using iptables, using the Apache config. Put on your VirtualHost apache config something like this:

order Allow,Deny
Deny from x.x.x.x
Allow from All

Of course this will only work if you have module installed and enabled.

sudo apt-get install libapache2-modsecurity
sudo a2enmod mod-security

Don't forget to restart the service after changes.

sudo service apache2 reload


问:
Update from join returning id from other table in Postgres
I can't figure out how to do this in Postgres.

I have two tables, foo and bar:

foo:id, number

bar:id, foo_id

There is an entry in bar that corresponds to and entry in foo. I want to update foo and return the bar id when I do so. I though something like this would work, but I'm having a very difficult time getting join updates to work in Postgres.

I want to do something like this:

```<code>UPDATE
    foo f
INNER JOIN
    bar b
ON
    f.id = b.foo_id
SET
    f.number = 1
RETURNING
    b.id
</code>```

Thanks.

答:
Your syntax is off, try this instead:

```<code>UPDATE foo AS f
SET number = 1
FROM bar AS b
WHERE f.id = b.foo_id
RETURNING b.id
</code>```

There are many references out there which could have shown you how to phrase an update join in Postgres, Stack Overflow being one of them.

Body:
I can't figure out how to do this in Postgres.

I have two tables, foo and bar:

foo:id, number

bar:id, foo_id

There is an entry in bar that corresponds to and entry in foo. I want to update foo and return the bar id when I do so. I though something like this would work, but I'm having a very difficult time getting join updates to work in Postgres.

I want to do something like this:

UPDATE
    foo f
INNER JOIN
    bar b
ON
    f.id = b.foo_id
SET
    f.number = 1
RETURNING
    b.id

Thanks.

Body:
Your syntax is off, try this instead:

UPDATE foo AS f
SET number = 1
FROM bar AS b
WHERE f.id = b.foo_id
RETURNING b.id

There are many references out there which could have shown you how to phrase an update join in Postgres, Stack Overflow being one of them.


问:
Bash substring removal
I have strings in the following pattern: <SOMETHING_1>{<JSON>}<SOMETHING_2>

I want to keep the <JSON> and remove the <SOMETHING_X>blocks. I'm trying to do it with substring removal, but instead of getting

```<code>{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}
</code>```

I keep getting

```<code>{x:1,action:PLAYING,name:John,description:Some}
</code>```

because the whitespace in the description field cuts off the substring.

Any ideas on what to change?

CODE:

```<code>string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
string=$1
string=$(echo "${string#*{}")
string=$(echo "${string%}*}")
string={$string}
echo $string
</code>```

答:
Here you go…

```<code>string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
echo "original: ${string}"
string="${string#*\{}"
string="${string%\}*}"
echo "final: {${string}}"
</code>```

By the way, JSON keys should be surrounded with double quotes.

Title: Bash substring removal

Body:
I have strings in the following pattern: <SOMETHING_1>{<JSON>}<SOMETHING_2>

I want to keep the <JSON> and remove the <SOMETHING_X>blocks. I'm trying to do it with substring removal, but instead of getting

{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}

I keep getting

{x:1,action:PLAYING,name:John,description:Some}

because the whitespace in the description field cuts off the substring.

Any ideas on what to change?

CODE:

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
string=$1
string=$(echo "${string#*{}")
string=$(echo "${string%}*}")
string={$string}
echo $string

Body:
Here you go…

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
echo "original: ${string}"
string="${string#*\{}"
string="${string%\}*}"
echo "final: {${string}}"

By the way, JSON keys should be surrounded with double quotes.


问:
Understanding RSA signing for JWT
I'm implementing a sign in system with the help of the JWT (JSON Web Token) scheme. Basically, after a user sign in / login, the server signs a JWT and passes it to the client.

The client then returns the token with each request and the server verifies the token before sending back a response.

This is pretty much how you would expect it, but I'm having some problems with the logic of the process. From all the mathematical articles I've read, it seems that RSA signing uses asymmetric keys for signing. As the public key, as its name suggests, is exposed to the client and the private key is kept on the server, it makes sense to sign the JWT with the public key which is sent to the client and verify it on the server side using the private key.

However, on every example and library I see it seems to be the other way around. Any idea as to why it is so? If a JWT is signed with the private key and verified with the public one than whats the point?

答:
First off, apologies, this answer got rather long.

If you use RSA to sign your tokens, and a connecting client is a web browser, the client will never see the RSA keys (public or private). This is because the client presumably doesn't need to verify that the JWT is valid, only the server needs to do that. The client just holds onto the JWT and shows it to the server when asked. Then the server checks to make sure its valid when it see's the token.

So why might you need a public / private key combo for JWT's? Well first off, you don't need to use a public / private key algorithm.

You can sign JWT's with a number of different algorithms, RSA being one of them. Other popular choices for signing your JWT's are ECDSA or HMAC algorithms (the JWT standard supports others as well). HMAC, specifically, is not a public / private key scheme. There's just one key, the key, which is used to both sign and validate the tokens. You can think of this as using the private key for both signing and validating the JWT's. I'm not an expert on this by any means, but here's the conclusions I came to from doing my own research recently:

Using HMAC is nice because it's the fastest option. However, in order to validate the JWT's, you need to give someone the one key that does everything, Sharing this key with someone else means that that person could now also sign tokens and pretend like they're you. If you're building multiple server applications that all need to be able to validate your JWT's, you might not want every application to have the ability to sign tokens as well (different programmers might be maintaining the different applications, sharing the signing ability with more people is a security risk, etc). In this case, it's better to have one, tightly controlled private key (and one app that does the signing) and then share the public key around with other people to give them the ability to validate the tokens. Here, the private key is used for signing the tokens, and the public key is used for validating them. In this case you'd want to choose RSA or ECDSA.

As an example, you might have an ecosystem of apps that all connect to
the same database. To log users in, each app sends folks to one,
dedicated, 'logging in' app. This app has the private key. The other
apps can verify that the person is logged in using the public key (but
they can't log people in).

The research I've done points to RSA being the better option for most JWT apps in this scenario. This is because your app will be, theoretically, validating tokens frequently.  RSA is much faster then ECDSA at verification. ECDSA is primarily nice because the keys are smaller in size. This makes it better for HTTPS certificates because you need to send the public key to the client's browser. In the JWT scenario though, the keys are staying on a server so the storage size is n/a and the verification speed is more important.

Conclusion: if you're building a small app without multiple smaller 'micro-service apps' / you're the only developer, probably choose HMAC to encrypt your keys. Otherwise, probably choose RSA. Again though, I'm not an expert, just someone who recently googled this topic, so take this with a grain of salt.

Title: Understanding RSA signing for JWT


问:
Initializing a const array inside a struct
```<code>#define LENGTH 6
typedef char data_t[LENGTH];
struct foo {
    const data_t data;
    ...
}
...
void bar(data_t data) {
    printf("%.6s\n", data);
    struct foo myfoo = {*data};
    printf("%.6s\n", foo.data);
}
</code>```

I'm trying to have this struct which holds directly the data I'm interested in, sizeof(foo) == 6+the rest, not sizeof(foo) == sizeof(void*)+the rest. However I can't find a way to initialize a struct of type foo with a data_t. I think maybe I could remove the const modifier from the field and use memcpy but I like the extra safety and clarity.

I don't get any compile errors but when I run the code I get

```<code>123456
1??
</code>```

so the copy didn't work properly I think.

This is for an arduino (or similar device) so I'm trying to keep it to very portable code.

Is it just not possible ?

EDIT: removing the const modifier on the data_t field doesn't seem to help.

答:
It's impossible to do it in a standard compliant way.

Due to its being const, const char data[6]; must be initialized to be usable, and it may only be initialized statically (static objects with no initializer get automatically zeroed), with a string literal, or with a brace-enclosed initializer list. You cannot initialize it with a pointer or another array.

If I were you, I would get rid of the const, document that .data shouldn't be changed post-initialization, and then use memcpy to initialize it.

(const on struct members doesn't work very well in my opinion. It effectively prevents you from being able to have initializer functions, and while C++ gets around the problem a little bit by having special language support for its constructor functions, the problem still remains if the const members are arrays).

Body:
#define LENGTH 6
typedef char data_t[LENGTH];
struct foo {
    const data_t data;
    ...
}
...
void bar(data_t data) {
    printf("%.6s\n", data);
    struct foo myfoo = {*data};
    printf("%.6s\n", foo.data);
}

I'm trying to have this struct which holds directly the data I'm interested in, sizeof(foo) == 6+the rest, not sizeof(foo) == sizeof(void*)+the rest. However I can't find a way to initialize a struct of type foo with a data_t. I think maybe I could remove the const modifier from the field and use memcpy but I like the extra safety and clarity.

I don't get any compile errors but when I run the code I get

123456
1??

so the copy didn't work properly I think.

This is for an arduino (or similar device) so I'm trying to keep it to very portable code.

Is it just not possible ?

EDIT: removing the const modifier on the data_t field doesn't seem to help.


问:
sed command with -i option failing on Mac, but works on Linux
I've successfully used the following sed command to search/replace text in Linux:

```<code>sed -i 's/old_link/new_link/g' *
</code>```

However, when I try it on my Mac OS X, I get:

"command c expects \ followed by text"

I thought my Mac runs a normal BASH shell.  What's up?

EDIT:

According to @High Performance, this is due to Mac sed being of a different (BSD) flavor, so my question would therefore be how do I replicate this command in BSD sed?

EDIT:

Here is an actual example that causes this:

```<code>sed -i 's/hello/gbye/g' *
</code>```

答:
As the other answers indicate, there is not a way to use sed portably across OS X and Linux without making backup files. So, I instead used this Ruby one-liner to do so:

```<code>ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml
</code>```

In my case, I needed to call it from a rake task (i.e., inside a Ruby script), so I used this additional level of quoting:

```<code>sh %q{ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml}
</code>```

Body:
I've successfully used the following sed command to search/replace text in Linux:

sed -i 's/old_link/new_link/g' *

However, when I try it on my Mac OS X, I get:

"command c expects \ followed by text"

I thought my Mac runs a normal BASH shell.  What's up?

EDIT:

According to @High Performance, this is due to Mac sed being of a different (BSD) flavor, so my question would therefore be how do I replicate this command in BSD sed?

EDIT:

Here is an actual example that causes this:

sed -i 's/hello/gbye/g' *

Body:
As the other answers indicate, there is not a way to use sed portably across OS X and Linux without making backup files. So, I instead used this Ruby one-liner to do so:

ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml

In my case, I needed to call it from a rake task (i.e., inside a Ruby script), so I used this additional level of quoting:

sh %q{ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml}


问:
Finding all numbers in a array with top frequency?
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

```<code>8 => 2
1 => 2
9 => 2
</code>```

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

```<code>    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }
</code>```

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

```<code>    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }
</code>```

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

答:
This code is very inefficient and may run in O(n^2) at the worst case.

You can achieve your goal with a single for loop by building a Map<Integer,Integer> where the key is each unique number you encounter and the value is its frequency.

After you have the Map, it's trivial to find all the numbers having max frequency (just iterate over all the entries of the Map). The total running time will be O(n).

```<code>int maxFreq = Integer.MIN_VALUE;
Map<Integer,Integer> freqs = new HashMap<>();
for(int i=0;i<N;i++){
    int number = random.nextInt(n);
    data[i] = number;
    Integer freq = freqs.get(number);
    if (freq != null) {
        freq = freq + 1;
    } else {
        freq = 1;
    }
    freqs.put(number,freq);
    if (freq > maxFreq)
        maxFreq = freq;
}
for(Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
    if (entry.getValue().equals(maxFreq)) {
        System.out.println(entry.getKey() +" => "+ maxFreq);
    }
}
</code>```

Body:
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

Body:
This code is very inefficient and may run in O(n^2) at the worst case.

You can achieve your goal with a single for loop by building a Map<Integer,Integer> where the key is each unique number you encounter and the value is its frequency.

After you have the Map, it's trivial to find all the numbers having max frequency (just iterate over all the entries of the Map). The total running time will be O(n).

int maxFreq = Integer.MIN_VALUE;
Map<Integer,Integer> freqs = new HashMap<>();
for(int i=0;i<N;i++){
    int number = random.nextInt(n);
    data[i] = number;
    Integer freq = freqs.get(number);
    if (freq != null) {
        freq = freq + 1;
    } else {
        freq = 1;
    }
    freqs.put(number,freq);
    if (freq > maxFreq)
        maxFreq = freq;
}
for(Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
    if (entry.getValue().equals(maxFreq)) {
        System.out.println(entry.getKey() +" => "+ maxFreq);
    }
}


问:
How to set cookie object using CookieOptions(earlier CookieOptionsArgs) for setting cookie for other/parent domain?
Is angular2-cookie already Depricated? if yes how to set cookie object using CookieOptions(earlier CookieOptionsArgs) for setting cookie for other/parent domain?</p>

答:
Yes As the angular version has upgraded the new ngx-cookie has replaced earlier angular 2 cookie.You can set the cookie for parent domain using CookieOptions in ngx-cookie by setting the domain param provided.Hope it helps.

Just make sure you are setting cookie of parent domain from subdomain.


问:
Error 500 (Internal Server Error) ajax and laravel
Hello people I am facing a problem with my comments system in laravel and ajax. Actually it works only with php but i'm having problems with ajax.

This is the error message:

Status Code:500 Internal Server Error. And the error says: 1/3 SQLSTATE[23000]:Integrity constraint violation:1048 Column 'post_id' cannot be null.

I am editing the comments in a modal, I can create a new comment but the problem is editing it with ajax.

JS code:

```<code><script>

  var commentId = 0;
        var divcomment = null;

        $('.edit-comment').click(function(event){
          event.preventDefault();
          var divcomment = this.parentNode.parentNode;
          commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
          var commentBody = $(divcomment).find('#display-comment').text();
          $('#comment').val(commentBody);
          $('#edit-comment').modal();
        });

        $('#modal-save').click(function(){
            $.ajax({
                method: 'POST',
                url: urlEdit,
                data: {
                    comment: $('#comment').val(),
                    commentId: commentId,
                    _token: token,
                    _method: 'POST'
                 }
            })
            .done(function (msg){
                $(divcomment).text(msg['new_comment']);
                $('#edit-comment').modal('hide');
            });
        });

</script>
</code>```

Here's the HTML:

```<code><article class="row">
    <div class="col-md-3 col-sm-3 hidden-xs">
        <figure class="thumbnail">
            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
        </figure>
    </div>
    <div class="col-md-8 col-sm-8">
        <div class="panel panel-default arrow left">
            <div class="panel-body">
                <header class="text-left">
                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                </header>
                <div id="comment-post" data-commentid="{{ $comment->id }}">
                    <p id="display-comment">{{ $comment->comment }}</p>
                </div>
            </div>

            <div class="panel-footer list-inline comment-footer">
                @if(Auth::guest())

                    No puedes responder ningún comentario si no has ingresado.

                @else

                    @if(Auth::user() == $comment->user)
                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                    @endif

                    @if(Auth::user() != $comment->user)
                        <a href="#">Responder</a>
                    @endif

                @endif
            </div>

        </div>
    </div>
</article>
</code>```

My Edit Modal:

```<code><div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>
</code>```

My comments update route:

```<code>Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
</code>```

My update function on CommentsController:

```<code>public function update(Request $request)
{

    $this->validate($request, [
        'comment' => 'required'
    ]);

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }

    $comment->comment = $request['comment'];

    $comment->update();
    return response()->json(['new_comment' => $comment->comment], 200);

}
</code>```

And finally the variables created on my Post single view "where i display the comments"

```<code><script>

  var token = '{{ Session::token() }}';
  var urlEdit = '{{ url('comments/update') }}';

</script>
</code>```

UPDATE:

Comments table scheme:

    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->text('comment');
            $table->boolean('approved');
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table){
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }
```

<p>New Update:</p>

<p>Errors Messages:</p>

<p>Error 1/3</p>

<blockquote>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null</p>
</blockquote>

<p>Error 2/3</p>

<blockquote>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null</p>
</blockquote>

<p>Error 3/3</p>

<blockquote>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into <code>comments</code> (<code>comment</code>, <code>approved</code>, <code>post_id</code>, <code>user_id</code>, <code>updated_at</code>, <code>created_at</code>) values (Another yet comment, 1, , 4, 2017-06-04 04:54:34, 2017-06-04 04:54:34))</p>
</blockquote>

<p>Additional Info:</p>

<p><strong>General</strong></p>

```Request URL:http://devmedia.dev/comments/update
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade
```

<p><strong>Form</strong></p>

```comment:Another yet comment
commentId:13
_token:Do1gqYfziHij1nAj2CFOWwgdt7UWuubqbawrD5uX
_method:POST
```

<p>Whole comments routes:</p>

```Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);
```

答:
It appears my(and Anton's) hunch was correct.  You have two conflicting routes.

```<code>Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
</code>```

And of course

```<code>Route::post('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
</code>```

Because the two routes use roughly the same route, laravel just goes by which is defined first, which is your comments.store route.

There are a couple ways to fix this.

Change the order of your routes:

```<code>Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
</code>```

Use route constraints:

```<code>Route::post('comments/{post_id}', [
    'uses' => 'CommentsController@store',
     'as' => 'comments.store'
])->where(['post_id' => '[0-9]+']);;
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
</code>```

Of note, I don't know how the Facade registrar handles the casing(lower, upper) of facade methods.. So in an effort to not cause further bugs, I used the lower casing of POST, just as it is used in the documentation.

Body:
Hello people I am facing a problem with my comments system in laravel and ajax. Actually it works only with php but i'm having problems with ajax.

This is the error message:

Status Code:500 Internal Server Error. And the error says: 1/3 SQLSTATE[23000]:Integrity constraint violation:1048 Column 'post_id' cannot be null.

I am editing the comments in a modal, I can create a new comment but the problem is editing it with ajax.

JS code:

Here's the HTML:

            user->profilepic  }}" />

{{ $comment->user->name }}

 {{ $comment->user->name }}

                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}</time>

id }}">

{{ $comment->comment }}

                @if(Auth::guest())

                    No puedes responder ningún comentario si no has ingresado.

                @else

                    @if(Auth::user() == $comment->user)
                        Editar Eliminar
                    @endif

                    @if(Auth::user() != $comment->user)
                        Responder
                    @endif

                @endif

My Edit Modal:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Editar Comentario

        <form>

            Editar comentario
            <textarea class="form-control" name="comment" id="comment"></textarea>

        </form>

        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"> Editar</button>

My comments update route:

Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

My update function on CommentsController:

public function update(Request $request)
{

    $this->validate($request, [
        'comment' => 'required'
    ]);

    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }

    $comment->comment = $request['comment'];

    $comment->update();
    return response()->json(['new_comment' => $comment->comment], 200);

}

And finally the variables created on my Post single view "where i display the comments"

UPDATE:

Comments table scheme:

    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->text('comment');
            $table->boolean('approved');
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table){
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });
    }

New Update:

Errors Messages:

Error 1/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null

Error 2/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null

Error 3/3

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into comments (comment, approved, post_id, user_id, updated_at, created_at) values (Another yet comment, 1, , 4, 2017-06-04 04:54:34, 2017-06-04 04:54:34))

Additional Info:

General

Request URL:http://devmedia.dev/comments/update
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade

Form

comment:Another yet comment
commentId:13
_token:Do1gqYfziHij1nAj2CFOWwgdt7UWuubqbawrD5uX
_method:POST

Whole comments routes:

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::POST('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);

Body:
It appears my(and Anton's) hunch was correct.  You have two conflicting routes.

Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);

And of course

Route::post('comments/', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

Because the two routes use roughly the same route, laravel just goes by which is defined first, which is your comments.store route.

There are a couple ways to fix this.

Change the order of your routes:

Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);
Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);

Use route constraints:

Route::post('comments/{post_id}', [
    'uses' => 'CommentsController@store',
     'as' => 'comments.store'
])->where(['post_id' => '[0-9]+']);;
Route::get('comments/{id}/edit', ['uses' => 'CommentsController@edit', 'as' => 'comments.edit']);
Route::post('comments/update', ['uses' => 'CommentsController@update', 'as' => 'comments.update']);

Of note, I don't know how the Facade registrar handles the casing(lower, upper) of facade methods.. So in an effort to not cause further bugs, I used the lower casing of POST, just as it is used in the documentation.


问:
Retrieving div "value" to javascript
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }</code>```

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

```

答:
I think you  want this, please try to run this code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
        <style>
            div.container {
                display: flex;
                height: 28vh;
            }
            div.number {
                color:  black;
                background-color: rgb(140,0,0);
                margin: 10px;
                border: 10px solid black;
                display: flex;
                flex: 1;
                font-size: 500%;
                text-align: center;
                flex-direction: column;
                justify-content: center;
            }

        </style>
    </head>
    <body>
        <H1> Sliding Puzzle </H1>
        <div class="container">
            <div data-cell="0,0" class="number" >8</div>
            <div data-cell="0,1" class="number">5</div>
            <div data-cell="0,2" class="number">4</div>
        </div>
        <div class="container">
            <div data-cell="1,0" class="number">6</div>
            <div data-cell="1,1" class="number">7</div>
            <div data-cell="1,2" class="number">2</div>
        </div>
        <div class="container">
            <div data-cell="2,0" class="number">1</div>
            <div data-cell="2,1" class="number">3</div>
            <div data-cell="2,2" class="number"></div>
        </div>
        <script>

            //By defaul to null as we will calculate
            var emptyCell = null;
            var numbersEls = document.getElementsByClassName('number');
            for (var counter = 0, max = numbersEls.length; counter < max; counter++) {
                var el = numbersEls[counter];
                el.addEventListener('click', onNumberCellClick);
                if(el.innerHTML == ''){
                    emptyCell = el;
                }
            }

            function onNumberCellClick(clickedEl){
                var clickedEl = this;
                var cellIdentifier = getCellIdentifier(clickedEl);

                //if empty cell not null
                if(emptyCell){

                    var swapPositions = getCellSwapAvailability(cellIdentifier);

                    //We can move the cell
                    if(swapPositions.indexOf(emptyCell.dataset.cell) > -1){
                        emptyCell.innerHTML = clickedEl.innerHTML;

                        //Swap the position as the empty cell is changed;
                        emptyCell = clickedEl;
                        emptyCell.innerHTML = '';
                    }
                }
            }

            function getCellSwapAvailability(identifier){
                //Calculate where cell can be moved
                var positions = [];
                var pos = identifier.row + ',' + (identifier.col-1);
                positions.push(pos);
                var pos = identifier.row + ',' + (identifier.col+1);
                positions.push(pos);
                var pos = (identifier.row-1) + ',' + (identifier.col);
                positions.push(pos);
                var pos = (identifier.row+1) + ',' + (identifier.col);
                positions.push(pos);
                return positions;
            }

            function getCellIdentifier(cell){
                var cellIndex = cell.dataset.cell;
                var identifierArr = cellIndex.split(',');
                var r = Number(identifierArr[0]);
                var c = Number(identifierArr[1]);
                return {row: r, col: c};
            }
        </script>
    </body>
    </html>
</code>```

Changed from jQuery to javascript

Title: Retrieving div "value" to javascript

Body:
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }

  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

Body:
I think you  want this, please try to run this code:

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            div.container {
                display: flex;
                height: 28vh;
            }
            div.number {
                color:  black;
                background-color: rgb(140,0,0);
                margin: 10px;
                border: 10px solid black;
                display: flex;
                flex: 1;
                font-size: 500%;
                text-align: center;
                flex-direction: column;
                justify-content: center;
            }

        </style>
    </head>
    <body>
        <H1> Sliding Puzzle </H1>
        <div class="container">
            <div data-cell="0,0" class="number" >8</div>
            <div data-cell="0,1" class="number">5</div>
            <div data-cell="0,2" class="number">4</div>
        </div>
        <div class="container">
            <div data-cell="1,0" class="number">6</div>
            <div data-cell="1,1" class="number">7</div>
            <div data-cell="1,2" class="number">2</div>
        </div>
        <div class="container">
            <div data-cell="2,0" class="number">1</div>
            <div data-cell="2,1" class="number">3</div>
            <div data-cell="2,2" class="number"></div>
        </div>
        <script>

            //By defaul to null as we will calculate
            var emptyCell = null;
            var numbersEls = document.getElementsByClassName('number');
            for (var counter = 0, max = numbersEls.length; counter < max; counter++) {
                var el = numbersEls[counter];
                el.addEventListener('click', onNumberCellClick);
                if(el.innerHTML == ''){
                    emptyCell = el;
                }
            }

            function onNumberCellClick(clickedEl){
                var clickedEl = this;
                var cellIdentifier = getCellIdentifier(clickedEl);

                //if empty cell not null
                if(emptyCell){

                    var swapPositions = getCellSwapAvailability(cellIdentifier);

                    //We can move the cell
                    if(swapPositions.indexOf(emptyCell.dataset.cell) > -1){
                        emptyCell.innerHTML = clickedEl.innerHTML;

                        //Swap the position as the empty cell is changed;
                        emptyCell = clickedEl;
                        emptyCell.innerHTML = '';
                    }
                }
            }

            function getCellSwapAvailability(identifier){
                //Calculate where cell can be moved
                var positions = [];
                var pos = identifier.row + ',' + (identifier.col-1);
                positions.push(pos);
                var pos = identifier.row + ',' + (identifier.col+1);
                positions.push(pos);
                var pos = (identifier.row-1) + ',' + (identifier.col);
                positions.push(pos);
                var pos = (identifier.row+1) + ',' + (identifier.col);
                positions.push(pos);
                return positions;
            }

            function getCellIdentifier(cell){
                var cellIndex = cell.dataset.cell;
                var identifierArr = cellIndex.split(',');
                var r = Number(identifierArr[0]);
                var c = Number(identifierArr[1]);
                return {row: r, col: c};
            }
        </script>
    </body>
    </html>

Changed from jQuery to javascript


问:
Use variable for filepath parameter of Start-Process
I'd like run a .exe which could be in a number of locations.

```<code>$runpath = "$servicepackfolder\SQLServer2008SP1-KB968369-IA64-ENU.exe"

Start-Process -FilePath $runpath -arg "/x:.\$buildfolder\PCU"
</code>```

Or this way, specifying the WorkingDirectory:

```<code>Start-Process 'SQLServer2008SP1-KB968369-IA64-ENU.exe' -WorkingDirectory $servicepackfolder -arg "/x:.\$buildfolder\PCU"
</code>```

But it seems the variables are not being interpreted as strings.

Start-Process : This command cannot be
  executed due to the error: The system
  cannot find the file specified.

I am in the correct directory and if I take the output from the $runpath variable and substitute it for the variable in the Start-Process call, I get the expected behavior.

Will this work, or am I stuck hardcoding these paths.  Trying to automate the slipstream build process for SQL 2008.

答:
I can duplicate the behavior you see if I add -NoNewWindow but if I don't specify that parameter it works as expected for my test case:

```<code>start-process sizeof.exe  -WorkingDirectory C:\temp -ArgumentList 1
</code>```

The new window flashes up and goes away but I can see it is running the specified exe from my temp dir.

ContentLicense: CC BY-SA 2.5

Body:
I'd like run a .exe which could be in a number of locations.

$runpath = "$servicepackfolder\SQLServer2008SP1-KB968369-IA64-ENU.exe"

Start-Process -FilePath $runpath -arg "/x:.\$buildfolder\PCU"

Or this way, specifying the WorkingDirectory:

Start-Process 'SQLServer2008SP1-KB968369-IA64-ENU.exe' -WorkingDirectory $servicepackfolder -arg "/x:.\$buildfolder\PCU"

But it seems the variables are not being interpreted as strings.

Start-Process : This command cannot be
  executed due to the error: The system
  cannot find the file specified.

I am in the correct directory and if I take the output from the $runpath variable and substitute it for the variable in the Start-Process call, I get the expected behavior.

Will this work, or am I stuck hardcoding these paths.  Trying to automate the slipstream build process for SQL 2008.

Body:
I can duplicate the behavior you see if I add -NoNewWindow but if I don't specify that parameter it works as expected for my test case:

start-process sizeof.exe  -WorkingDirectory C:\temp -ArgumentList 1

The new window flashes up and goes away but I can see it is running the specified exe from my temp dir.


问:
XAMPP Apache not working after installing mod_wsgi
Good day.
I am currently trying to host my Django website locally using XAMPP Apache. I have followed several tutorials but one of those works. I was wondering if you could tell me what are the steps I have missed or did wrong. Here is the specs of the installed packages on my Django dev site:

Python = 2.7.12, 32-bit

Apache = 2.4, 32-bit

Visual C++ Version 9

OS: Windows 7 64-bit

Here is the procedure I have followed:

Download mod_wsgi from https://code.google.com/archive/p/modwsgi/downloads. I have tried [mod_wsgi-py26-vc9.so, mod_wsgi-py27-vc9.so, mod_wsgi-win32-ap22py27-3.3.so and mod] **but none seems to work.

Rename the mod_wsgi file to mod_wsgi.so and save it to C:/xampp/apache/modules

Run xampp and edit apache httpd.conf file by adding

```<code>LoadModule wsgi_module modules/mod_wsgi.so
</code>```

I have also tried

```<code>    LoadModule mod_wsgi modules/mod_wsgi.so
</code>```

But still have same result. The XAMPP does not display any errors but does not run Apache even after restarting XAMPP and the machine itself. I have also tried to run the app in administrator privileges but it is still not working. Other XAMPP modules are working except Apache.

答:
I have resolved this problem by downloading the binary file at the author's GitHub account and building my own binary file. To do this, I need to extract the downloaded zip file and open the win32 folder and read the README.rst for the instructions.

Excerpt from the instructions:

Know the windows and python versions you are using (Windows 7 32-bit and Python 2.7 in my case)

Install Microsoft C/C++ compiler suitable for your Python version:

Python 2.6 - VC9

Python 2.7 - VC9

Python 3.3 - VC10

Python 3.4 - VC10

Start Visual C++ Command Prompt and:

Navigate back to the extracted mod_wsgi file and find the appropriate makefile for your combination of Apache and Python (ap22py27-win32-VC9.mk in my case). If you are not sure your Apache version read this for XAMPP or just navigate to localhost for WAMP.

Edit the .mk file and define the correct path for APACHE_ROOTDIR and PYTHON_ROOTDIR. Example:

APACHE_ROOTDIR = C:\xampp\apache

PYTHON_ROOTDIR = C:\Python27

Run nmake -f apXYpyXY-winNN-VC?.mk install. Substitute 'XY' in each
case for the version of Apache and Python being used. Substitute 'NN'
with either '32' or '64' and substitute '?' with '9' or '10'. Example: nmake -f ap22py27-win32-VC9.mk install. The line builds the mod_wsgi for your platform and installs it to the modules directory of your Apache installation

Add the following line in your WAMP/XAMPP http.conf: LoadModule wsgi_module modules/mod_wsgi.so and

WSGIPythonHome "C:/Python27"

WSGIPythonPath "ProjectPath"

WSGIApplicationGroup "%{GLOBAL}"

WSGIPassAuthorization "On"

Restart your Apache or your computer and you're good to go.

Note: There's no need for you to add mod_wsgi in the installed apps of your python since it was already installed in your Apache server

Body:
Good day.
I am currently trying to host my Django website locally using XAMPP Apache. I have followed several tutorials but one of those works. I was wondering if you could tell me what are the steps I have missed or did wrong. Here is the specs of the installed packages on my Django dev site:

Python = 2.7.12, 32-bit

Apache = 2.4, 32-bit

Visual C++ Version 9

OS: Windows 7 64-bit

Here is the procedure I have followed:

Download mod_wsgi from https://code.google.com/archive/p/modwsgi/downloads. I have tried [mod_wsgi-py26-vc9.so, mod_wsgi-py27-vc9.so, mod_wsgi-win32-ap22py27-3.3.so and mod] **but none seems to work.

Rename the mod_wsgi file to mod_wsgi.so and save it to C:/xampp/apache/modules

Run xampp and edit apache httpd.conf file by adding

LoadModule wsgi_module modules/mod_wsgi.so

I have also tried

    LoadModule mod_wsgi modules/mod_wsgi.so

But still have same result. The XAMPP does not display any errors but does not run Apache even after restarting XAMPP and the machine itself. I have also tried to run the app in administrator privileges but it is still not working. Other XAMPP modules are working except Apache.


问:
Disable OK button in alert
Is there any way to disable 'Ok' button of alert in java script?

I have a java script function which calls two different window , the second window pop up is delayed by an alert as I need to open it after some operation is complete in the first window opened . I need to disable the alert till some operation in complete in first window. Please suggest some way.

Below is the js function(myFunction()) which is called on a button click an opens two window :

```<code>    function myFunction() {
        myFunction2();
        alert("Please wait...");
        myFunction1();
    }

    function myFunction2() {
        var x ="sce";
        var URL ="Multiple.jsp?viewStatus="+x;
        var windowName = "showDeb";
          var width  = screen.availWidth;
          var height = screen.availHeight;
          var w = 900;
          var h =   500;
          var features =
            'width='          + w +
            ',height='        + h +
            ',left='          + ((width - w - 10) * .5)  +
            ',top='           + ((height - h - 30) * .5) +
            ',directories=no' +
            ',location=no'    +
            ',menubar=no'     +
            ',scrollbars=yes' +
            ',status=no'      +
            ',toolbar=no'     +
            ',resizable=false';

           var strOpen = window.open (URL, windowName, features);
           strOpen.focus();
           myFunction1();
    }
    function myFunction1() {
        var x ="deb";
        var URL ="Multiple.jsp?viewStatus="+x;
        var windowName = "showSce";
           var width  = screen.availWidth;
           var height = screen.availHeight;
           var w = 900;
           var h =  500;
           var features =
               'width='          + w +
               ',height='         + h +
               ',left='       + ((width - w - 10) * .5)  +
               ',top='            + ((height - h - 30) * .5) +
               ',directories=no' +
               ',location=no'     +
               ',menubar=no'      +
               ',scrollbars=yes' +
               ',status=no'   +
               ',toolbar=no'      +
               ',resizable=false';

            var strOpen = window.open (URL, windowName, features);
            strOpen.focus();
    }
</code>```

答:
I would recommend to use cookies to communicate between your windows.
In window 1 set cookie once process is completed.

```<code>var date = new Date();
date.setDate(date.getDate()+1);
document.cookie = "name=win1; path=/; expires="+date.toGMTString()
</code>```

In parent file which will open window 2, add timer to wait until window 1 sets cookie.

```<code>   var myVar = setInterval(myTimer, 1000); // Poll every second to check if window 1 has completed its execution by checking cookie.
   function myTimer() {
      var cookies = document.cookie.split(";");

      for (var i = 0; i < cookies.length; i++) {
        if (cookies[i].trim() == "name=win1") {
          // stop timer and open win 2
          clearTimeout(myVar);
          document.getElementById("msg2").innerHTML = "Process in window 1 completed";

         // <<< Open window 2 here >>>

          var dateNow = new Date();
          document.cookie = "name=win1; path=/; expires="+dateNow.toGMTString();
        }
      }
</code>```

Make sure that you delete the cookie before window one is opened and after window 2 is opened else it will cause issue in re-run as cookie will be already present before window 1 completes the process.
To delete the cookie just set expiry date as current time or privious.

```<code>var dateNow = new Date();
document.cookie = "name=win1; path=/; expires="+dateNow.toGMTString();
</code>```

Here is an example which demonstrates the same. Make sure you allow pop up as it will try to open new window.
http://embed.plnkr.co/MVa45iwYuW9asQuYRzBV/

Title: Disable OK button in alert

Body:
Is there any way to disable 'Ok' button of alert in java script?

I have a java script function which calls two different window , the second window pop up is delayed by an alert as I need to open it after some operation is complete in the first window opened . I need to disable the alert till some operation in complete in first window. Please suggest some way.

Below is the js function(myFunction()) which is called on a button click an opens two window :

    function myFunction() {
        myFunction2();
        alert("Please wait...");
        myFunction1();
    }

    function myFunction2() {
        var x ="sce";
        var URL ="Multiple.jsp?viewStatus="+x;
        var windowName = "showDeb";
          var width  = screen.availWidth;
          var height = screen.availHeight;
          var w = 900;
          var h =   500;
          var features =
            'width='          + w +
            ',height='        + h +
            ',left='          + ((width - w - 10) * .5)  +
            ',top='           + ((height - h - 30) * .5) +
            ',directories=no' +
            ',location=no'    +
            ',menubar=no'     +
            ',scrollbars=yes' +
            ',status=no'      +
            ',toolbar=no'     +
            ',resizable=false';

           var strOpen = window.open (URL, windowName, features);
           strOpen.focus();
           myFunction1();
    }
    function myFunction1() {
        var x ="deb";
        var URL ="Multiple.jsp?viewStatus="+x;
        var windowName = "showSce";
           var width  = screen.availWidth;
           var height = screen.availHeight;
           var w = 900;
           var h =  500;
           var features =
               'width='          + w +
               ',height='         + h +
               ',left='       + ((width - w - 10) * .5)  +
               ',top='            + ((height - h - 30) * .5) +
               ',directories=no' +
               ',location=no'     +
               ',menubar=no'      +
               ',scrollbars=yes' +
               ',status=no'   +
               ',toolbar=no'      +
               ',resizable=false';

            var strOpen = window.open (URL, windowName, features);
            strOpen.focus();
    }

Body:
I would recommend to use cookies to communicate between your windows.
In window 1 set cookie once process is completed.

var date = new Date();
date.setDate(date.getDate()+1);
document.cookie = "name=win1; path=/; expires="+date.toGMTString()

In parent file which will open window 2, add timer to wait until window 1 sets cookie.

   var myVar = setInterval(myTimer, 1000); // Poll every second to check if window 1 has completed its execution by checking cookie.
   function myTimer() {
      var cookies = document.cookie.split(";");

      for (var i = 0; i < cookies.length; i++) {
        if (cookies[i].trim() == "name=win1") {
          // stop timer and open win 2
          clearTimeout(myVar);
          document.getElementById("msg2").innerHTML = "Process in window 1 completed";

         // <<< Open window 2 here >>>

          var dateNow = new Date();
          document.cookie = "name=win1; path=/; expires="+dateNow.toGMTString();
        }
      }

Make sure that you delete the cookie before window one is opened and after window 2 is opened else it will cause issue in re-run as cookie will be already present before window 1 completes the process.
To delete the cookie just set expiry date as current time or privious.

var dateNow = new Date();
document.cookie = "name=win1; path=/; expires="+dateNow.toGMTString();

Here is an example which demonstrates the same. Make sure you allow pop up as it will try to open new window.
http://embed.plnkr.co/MVa45iwYuW9asQuYRzBV/