问:
How to Add a specific number at the end of merging workbooks
I have an excel file that use to merge all the raw data's found in the same folder(Group 1, Group 2, ... Group 15, Group 16), using the code below :

```<code>Sub MergeFiles()
Dim Path, Filename As String, group As Long
group = 1
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = group
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close

Filename = Dir()
group = group + 1
Loop

MsgBox "Files have been copied successfully"
End Sub
</code>```

I am trying to add in the column "O:O" of each file the group number. The problem is that it opens them alphabetically: "Group 1, Group 10, Group 11... Group 2, Group 3..." but the group counter still goes : 1, 2, 3...

Could you please help me, I need the group counter to match the number in the file's name(maybe populate O:O with the first number it encounters?) or make excel open the files after explorer name.

Thank you in advance.

答:
I tried using a function to get the first number(first 1 or 2 digits) and add them in the column that I needed.</p>

```<code>Function Number(txt As String) As String
With CreateObject("VBScript.RegExp")
 .Pattern = "\d{1,2}"
Number = .Execute(txt)(0)
End With
End Function

Sub MergeFiles()
Dim Path, Filename As String
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = Number(Filename)
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close
  Filename = Dir()
Loop

MsgBox "Files have been copied successfully"
End Sub
</code>```

Body:
I have an excel file that use to merge all the raw data's found in the same folder(Group 1, Group 2, ... Group 15, Group 16), using the code below :

Sub MergeFiles()
Dim Path, Filename As String, group As Long
group = 1
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = group
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close

Filename = Dir()
group = group + 1
Loop

MsgBox "Files have been copied successfully"
End Sub

I am trying to add in the column "O:O" of each file the group number. The problem is that it opens them alphabetically: "Group 1, Group 10, Group 11... Group 2, Group 3..." but the group counter still goes : 1, 2, 3...

Could you please help me, I need the group counter to match the number in the file's name(maybe populate O:O with the first number it encounters?) or make excel open the files after explorer name.

Thank you in advance.

Body:
I tried using a function to get the first number(first 1 or 2 digits) and add them in the column that I needed.

Function Number(txt As String) As String
With CreateObject("VBScript.RegExp")
 .Pattern = "\d{1,2}"
Number = .Execute(txt)(0)
End With
End Function

Sub MergeFiles()
Dim Path, Filename As String
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = Number(Filename)
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close
  Filename = Dir()
Loop

MsgBox "Files have been copied successfully"
End Sub


来源: stackexchange

问:
iFrame src change event detection?
Assuming I have no control over the content in the iframe, is there any way that I can detect a src change in it via the parent page? Some sort of onload maybe?

My last resort is to do a 1 second interval test if the iframe src is the same as it was before, but doing this hacky solution would suck.

I'm using the jQuery library if it helps.

答:
Note: The snippet would only work if the iframe is with the same origin.

Other answers proposed the load event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.

Here's a plain JavaScript solution:

function iframeURLChange(iframe, callback) {
    var unloadHandler = function () {
        // Timeout needed because the URL changes immediately after
        // the `unload` event is dispatched.
        setTimeout(function () {
            callback(iframe.contentWindow.location.href);
        }, 0);
    };

    function attachUnload() {
        // Remove the unloadHandler in case it was already attached.
        // Otherwise, the change will be dispatched twice.
        iframe.contentWindow.removeEventListener("unload", unloadHandler);
        iframe.contentWindow.addEventListener("unload", unloadHandler);
    }

    iframe.addEventListener("load", attachUnload);
    attachUnload();
}

iframeURLChange(document.getElementById("mainframe"), function (newURL) {
    console.log("URL changed:", newURL);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="mainframe" src=""></iframe></code>```

This will successfully track the src attribute changes, as well as any URL changes made from within the iframe itself.

Tested in all modern browsers.

I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.

ContentLicense: CC BY-SA 2.5

Title: iFrame src change event detection?

Body:
Note: The snippet would only work if the iframe is with the same origin.

Other answers proposed the load event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.

Here's a plain JavaScript solution:

function iframeURLChange(iframe, callback) {
    var unloadHandler = function () {
        // Timeout needed because the URL changes immediately after
        // the `unload` event is dispatched.
        setTimeout(function () {
            callback(iframe.contentWindow.location.href);
        }, 0);
    };

    function attachUnload() {
        // Remove the unloadHandler in case it was already attached.
        // Otherwise, the change will be dispatched twice.
        iframe.contentWindow.removeEventListener("unload", unloadHandler);
        iframe.contentWindow.addEventListener("unload", unloadHandler);
    }

    iframe.addEventListener("load", attachUnload);
    attachUnload();
}

iframeURLChange(document.getElementById("mainframe"), function (newURL) {
    console.log("URL changed:", newURL);
});

<iframe id="mainframe" src=""></iframe>

This will successfully track the src attribute changes, as well as any URL changes made from within the iframe itself.

Tested in all modern browsers.

I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.

ContentLicense: CC BY-SA 4.0


问:
Spark-shell not overriding method definition
I'm running Spark 2 - shell with scala 2.11.8 and wondering about the the following behavior, where each line is a block of code to be executed in the shell:

```<code>def myMethod()  = "first definition"

val tmp = myMethod(); val out = tmp

println(out) // prints "first definition"

def myMethod()  = "second definition" // override above myMethod

val tmp = myMethod(); val out = tmp

println(out) // should be "second definition" but is "first definition"
</code>```

So if I-redefine myMethod, the implementation seems not to be updated in this case. I figured out that the second-last statement (val out = tmp) causes this behavior, if this is moved in a separate block, the code works just fine.

So my question: Is this the desired behavior or a bug?

答: This is indeed a Spark-Shell bug (or more a Scala REPL bug) and will be resolved in Spark 2.3: https://issues.apache.org/jira/browse/SPARK-20706</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm running Spark 2 - shell with scala 2.11.8 and wondering about the the following behavior, where each line is a block of code to be executed in the shell:

def myMethod()  = "first definition"

val tmp = myMethod(); val out = tmp

println(out) // prints "first definition"

def myMethod()  = "second definition" // override above myMethod

val tmp = myMethod(); val out = tmp

println(out) // should be "second definition" but is "first definition"

So if I-redefine myMethod, the implementation seems not to be updated in this case. I figured out that the second-last statement (val out = tmp) causes this behavior, if this is moved in a separate block, the code works just fine.

So my question: Is this the desired behavior or a bug?


问:
option:disabled css style does not works on Chrome and Safari for MAC
I can not change color for a disabled option on Chrome and Safari for MAC OSx. On firefox this code works. How can i override styles cross browser?

option:disabled {
  color: #a69474;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option value="volvo">Volvo</option>
  <option disabled value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select></code>```

答:
It is working fine in chrome

option:disabled {
        color: #a69474;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option disabled value="audi">Audi</option>
</select></code>```

Body:
I can not change color for a disabled option on Chrome and Safari for MAC OSx. On firefox this code works. How can i override styles cross browser?

option:disabled {
  color: #a69474;
}

<select>
  <option value="volvo">Volvo</option>
  <option disabled value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Body:
It is working fine in chrome

option:disabled {
        color: #a69474;
    }

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option disabled value="audi">Audi</option>
</select>


问:
Oracle pushing me ORA-00902: invalid datatype
```<code>create table accountDetails(
    accountNumber int unique,
    customerId int unique,
    balance int not null,
    password varchar(255) not null,
    type varchar(255) not null check(type in ('Savings','Current')),
    primary key(accountNumber,customerId) )

create table statusDetails(
    customerId int references accountDetails(customerId),
    primarykey(customerId))
</code>```

The last table resulted in an error

答:
Your second table declaration is all wrong.  Try this:

```<code>CREATE TABLE statusdetails (
    customerid   INT,
    CONSTRAINT fk_cust FOREIGN KEY ( customerid )
        REFERENCES accountdetails ( customerid )
)
</code>```

Note: using "int" data type maps to a NUMBER(38), which may not be what you want.  Use the proper oracle data type names.

Body:
create table accountDetails(
    accountNumber int unique,
    customerId int unique,
    balance int not null,
    password varchar(255) not null,
    type varchar(255) not null check(type in ('Savings','Current')),
    primary key(accountNumber,customerId) )

create table statusDetails(
    customerId int references accountDetails(customerId),
    primarykey(customerId))

The last table resulted in an error

Body:
Your second table declaration is all wrong.  Try this:

CREATE TABLE statusdetails (
    customerid   INT,
    CONSTRAINT fk_cust FOREIGN KEY ( customerid )
        REFERENCES accountdetails ( customerid )
)

Note: using "int" data type maps to a NUMBER(38), which may not be what you want.  Use the proper oracle data type names.


问:
Is there used incorrect terminology in description of a compile error as to 'for' syntax in golang?
I tried to use something like

```<code>for i := 0; i < len(bytes); ++i {
        ...
}
</code>```

It is not correct and I got an error

syntax error: unexpected ++, expecting expression

It was because of ++i is not an expression I thought.

Then I found out that i++ (it works in for loop) is not an expression as well according to the documentation.

Also I met that in some cases (now I think in all cases) a statement can not be used instead of expression.

Now if we come back to the error we see that for loop requires an expression. I was confused with that. I checked one more part of the documentation it turns out for requires a statement.

For statements with for clause

A "for" statement with a ForClause is also controlled by its
  condition, but additionally it may specify an init and a post
  statement

I started with question (which I liked more than the final question because it was about language non-acquaintance as I thought)

Is it special case for loop syntax that statement are accepted as expression or are there other cases in golang?

During writing the question and checking the documentation I end up to a questions

Is there used incorrect terminology in description of the error that should be fixed not to confuse? Or is it normally in some cases to substitute such terms as statement and expression?

答:
The Go Programming Language Specification

Primary expressions

Primary expressions are the operands for unary and binary expressions.

```<code>PrimaryExpr =
  Operand |
  Conversion |
  PrimaryExpr Selector |
  PrimaryExpr Index |
  PrimaryExpr Slice |
  PrimaryExpr TypeAssertion |
  PrimaryExpr Arguments .

Selector       = "." identifier .
Index          = "[" Expression "]" .
Slice          = "[" [ Expression ] ":" [ Expression ] "]" |
                 "[" [ Expression ] ":" Expression ":" Expression "]" .
TypeAssertion  = "." "(" Type ")" .
Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
</code>```

Operators and punctuation

The following character sequences represent operators:

```<code>++
--
</code>```

Operators

Operators combine operands into expressions.

```<code>Expression = UnaryExpr | Expression binary_op Expression .
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .

binary_op  = "||" | "&&" | rel_op | add_op | mul_op .
rel_op     = "==" | "!=" | "<" | "<=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
mul_op     = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .

unary_op   = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
</code>```

Operator precedence

The ++ and -- operators form statements, not expressions.

IncDec statements

The "++" and "--" statements increment or decrement their operands by
  the untyped constant 1. As with an assignment, the operand must be
  addressable or a map index expression.

```<code>IncDecStmt = Expression ( "++" | "--" ) .
</code>```

++ and -- are operators. The ++ and -- operators form statements, not expressions.

```<code>IncDecStmt = Expression ( "++" | "--" ) .
</code>```

When the compiler encounters an ++ operator, it expects it to be immediately preceded by an expresssion.

For example,

```<code>package main

func main() {

    // syntax error: unexpected ++, expecting expression
    for i := 0; i < 1; ++i {}
}
</code>```

Playground: https://play.golang.org/p/y2d9ijeMdw

Output:

```<code>main.go:6:21: syntax error: unexpected ++, expecting expression
</code>```

The compiler complains about the syntax. It found a ++ operator without an immediately preceding expression: syntax error: unexpected ++, expecting expression.

Body:
I tried to use something like

for i := 0; i < len(bytes); ++i {
        ...
}

It is not correct and I got an error

syntax error: unexpected ++, expecting expression

It was because of ++i is not an expression I thought.

Then I found out that i++ (it works in for loop) is not an expression as well according to the documentation.

Also I met that in some cases (now I think in all cases) a statement can not be used instead of expression.

Now if we come back to the error we see that for loop requires an expression. I was confused with that. I checked one more part of the documentation it turns out for requires a statement.

For statements with for clause

A "for" statement with a ForClause is also controlled by its
  condition, but additionally it may specify an init and a post
  statement

I started with question (which I liked more than the final question because it was about language non-acquaintance as I thought)

Is it special case for loop syntax that statement are accepted as expression or are there other cases in golang?

During writing the question and checking the documentation I end up to a questions

Is there used incorrect terminology in description of the error that should be fixed not to confuse? Or is it normally in some cases to substitute such terms as statement and expression?

Body:
The Go Programming Language Specification

Primary expressions

Primary expressions are the operands for unary and binary expressions.

PrimaryExpr =
  Operand |
  Conversion |
  PrimaryExpr Selector |
  PrimaryExpr Index |
  PrimaryExpr Slice |
  PrimaryExpr TypeAssertion |
  PrimaryExpr Arguments .

Selector       = "." identifier .
Index          = "[" Expression "]" .
Slice          = "[" [ Expression ] ":" [ Expression ] "]" |
                 "[" [ Expression ] ":" Expression ":" Expression "]" .
TypeAssertion  = "." "(" Type ")" .
Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .

Operators and punctuation

The following character sequences represent operators:

++
--

Operators

Operators combine operands into expressions.

Expression = UnaryExpr | Expression binary_op Expression .
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .

binary_op  = "||" | "&&" | rel_op | add_op | mul_op .
rel_op     = "==" | "!=" | "<" | "<=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
mul_op     = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .

unary_op   = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .

Operator precedence

The ++ and -- operators form statements, not expressions.

IncDec statements

The "++" and "--" statements increment or decrement their operands by
  the untyped constant 1. As with an assignment, the operand must be
  addressable or a map index expression.

IncDecStmt = Expression ( "++" | "--" ) .

++ and -- are operators. The ++ and -- operators form statements, not expressions.

IncDecStmt = Expression ( "++" | "--" ) .

When the compiler encounters an ++ operator, it expects it to be immediately preceded by an expresssion.

For example,

package main

func main() {

    // syntax error: unexpected ++, expecting expression
    for i := 0; i < 1; ++i {}
}

Playground: https://play.golang.org/p/y2d9ijeMdw

Output:

main.go:6:21: syntax error: unexpected ++, expecting expression

The compiler complains about the syntax. It found a ++ operator without an immediately preceding expression: syntax error: unexpected ++, expecting expression.


问:
AEM 6.3: Error while calling POST Servlet
I have created a POST servlet like below:

```<code>package com.aem.sites.servlets;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.SubscriptionConfiguration;

@Component(immediate=true,
service=Servlet.class,
configurationPid="com.aem.sites.servlets.SubscriptionServlet",
property = {
        "sling.servlet.methods=POST",
        "sling.servlet.selectors=newsletters",
        "sling.servlet.resourceTypes=aemsite-project/components/structure/page",
        "sling.servlet.extensions=html"
}
        )
@Designate(ocd=SubscriptionConfiguration.class)
public class SubscriptionServlet extends SlingAllMethodsServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException  {
        logger.info("====================================================SubscriptionServlet::::::::::SubscriptionConfiguration=====================================");
    }

    @Activate
    @Modified
    protected void Activate(SubscriptionConfiguration config) {
        logger.info("********************************inside SubscriptionConfiguration servlet*****************************************");
    }

}
</code>```

I am calling the servlet using resourceType and selector.The servlet is being called through a form:

```<code><div id = "sign-up" style ="padding-top:6%;padding-left:2%">
  <div>
    <h1 style="font-size:2em">Subscribe to Newsletters</h1>
    <form name = "subscriptionForm" method = "POST" action="/content/aemsite/en/subscribe.newsletters.html" id="subscriptionForm">
    <input type="text" name="name" id="name" placeholder="Name" style="margin-bottom:1%;width:30%"/>
    <input type="text" name="email" id="email" placeholder="E-mail" style="margin-bottom:1%;width:30%"/>

    <input type="submit" name="signup_submit" value="Sign me up" style="margin-bottom:3%"/>
    </form>
  </div>

</div>
</code>```

this is the javascript file that is being included as clientlibs

```<code>$(function() {
    $('#subscriptionForm').submit(function(e) {
        e.preventDefault(); //STOP default action
        var formURL = $(this).attr("action");
        var method = $(this).attr("method");
        var name = $('#name').val();
        var email = $('#email').val();
        var form_data = $(this).serialize();
        console.log('inside subscription form '+form_data+' formURL '+formURL);
        $.ajax({
            type:method,
            url:formURL,
            data: form_data, success:function(data){
              }
        });
    });
});
</code>```

I am using the jQuery provided out of the box with AEM. When I submit the form it throws some errors. These are the errors that I am seeing:

```<code>Failed to load resource: the server responded with a status of 500 (Server Error)
</code>```

The above is the error I am seeing on the chrome debuuger. In the error.log file I am seeing this error:

```<code>20.11.2017 22:13:42.802 *ERROR* [0:0:0:0:0:0:0:1 [1511234022796] POST /content/aemsite/en/subscribe.newsletters.html HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing.
javax.jcr.nodetype.ConstraintViolationException: No matching property definition: name = aemsite
</code>```

and

```<code>POST /content/aemsite/en/subscribe.newsletters.html HTTP/1.1] org.apache.sling.jcr.resource.internal.helper.JcrPropertyMapCacheEntry converToType: Cannot convert value of 2017/11/18 02:28:18 to class java.util.Calendar
java.lang.IllegalArgumentException: Not a date string: 2017/11/18 02:28:18
</code>```

It looks like the POST request is trying to save a property but in the servlet all I am trying to do is output the logger message set in the doPost method of the servlet. When I change the type of request from POST to GET, the errors disappear and the servlet is getting called.

I had read that from AEM 6 onwards more security measures are being adopted for POST request and hence a CSRF token is being used but it is mostly handled if AEM's version of jQuery is used.

I am not sure what is it that I am doing incorrectly. Any help is appreciated.

Thanks in advance

UPDATE:

Result of jcrresolver mapping

答:
When you post to a path that resolves to a cq:Page your servlet with resourceType will not get invoked.

Post to - your_page_path/jcr:content to get your resource based servlet to process this request

Also hardcoding the path is not recommended. What I have done in past for such scenarios is to have a component, in your case you could call it subscription component and the form could be posted like -

```<code> <form action="${resource.path}.yourselector.html" method="post">
</code>```

And your servlet resourceType be the component.

Body:
I have created a POST servlet like below:

package com.aem.sites.servlets;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.SubscriptionConfiguration;

@Component(immediate=true,
service=Servlet.class,
configurationPid="com.aem.sites.servlets.SubscriptionServlet",
property = {
        "sling.servlet.methods=POST",
        "sling.servlet.selectors=newsletters",
        "sling.servlet.resourceTypes=aemsite-project/components/structure/page",
        "sling.servlet.extensions=html"
}
        )
@Designate(ocd=SubscriptionConfiguration.class)
public class SubscriptionServlet extends SlingAllMethodsServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException  {
        logger.info("====================================================SubscriptionServlet::::::::::SubscriptionConfiguration=====================================");
    }

    @Activate
    @Modified
    protected void Activate(SubscriptionConfiguration config) {
        logger.info("********************************inside SubscriptionConfiguration servlet*****************************************");
    }

}

I am calling the servlet using resourceType and selector.The servlet is being called through a form:

Subscribe to Newsletters

    <form name = "subscriptionForm" method = "POST" action="/content/aemsite/en/subscribe.newsletters.html" id="subscriptionForm">
    <input type="text" name="name" id="name" placeholder="Name" style="margin-bottom:1%;width:30%"/>
    <input type="text" name="email" id="email" placeholder="E-mail" style="margin-bottom:1%;width:30%"/>

    <input type="submit" name="signup_submit" value="Sign me up" style="margin-bottom:3%"/>
    </form>

this is the javascript file that is being included as clientlibs

$(function() {
    $('#subscriptionForm').submit(function(e) {
        e.preventDefault(); //STOP default action
        var formURL = $(this).attr("action");
        var method = $(this).attr("method");
        var name = $('#name').val();
        var email = $('#email').val();
        var form_data = $(this).serialize();
        console.log('inside subscription form '+form_data+' formURL '+formURL);
        $.ajax({
            type:method,
            url:formURL,
            data: form_data, success:function(data){
              }
        });
    });
});

I am using the jQuery provided out of the box with AEM. When I submit the form it throws some errors. These are the errors that I am seeing:

Failed to load resource: the server responded with a status of 500 (Server Error)

The above is the error I am seeing on the chrome debuuger. In the error.log file I am seeing this error:

20.11.2017 22:13:42.802 *ERROR* [0:0:0:0:0:0:0:1 [1511234022796] POST /content/aemsite/en/subscribe.newsletters.html HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing.
javax.jcr.nodetype.ConstraintViolationException: No matching property definition: name = aemsite

and

POST /content/aemsite/en/subscribe.newsletters.html HTTP/1.1] org.apache.sling.jcr.resource.internal.helper.JcrPropertyMapCacheEntry converToType: Cannot convert value of 2017/11/18 02:28:18 to class java.util.Calendar
java.lang.IllegalArgumentException: Not a date string: 2017/11/18 02:28:18

It looks like the POST request is trying to save a property but in the servlet all I am trying to do is output the logger message set in the doPost method of the servlet. When I change the type of request from POST to GET, the errors disappear and the servlet is getting called.

I had read that from AEM 6 onwards more security measures are being adopted for POST request and hence a CSRF token is being used but it is mostly handled if AEM's version of jQuery is used.

I am not sure what is it that I am doing incorrectly. Any help is appreciated.

Thanks in advance

UPDATE:

Result of jcrresolver mapping

Body:
When you post to a path that resolves to a cq:Page your servlet with resourceType will not get invoked.

Post to - your_page_path/jcr:content to get your resource based servlet to process this request

Also hardcoding the path is not recommended. What I have done in past for such scenarios is to have a component, in your case you could call it subscription component and the form could be posted like -

 <form action="${resource.path}.yourselector.html" method="post">

And your servlet resourceType be the component.


问:
Python: smart way to lowercase transformation of key values from an array of JSON
I am trying to do lowercase data transformation. My input data are in the following format

```<code>ret = { "users":[
             {"EMAIL":"jogn@doe.com","Name":"John Doe"},
             {"EMail":"james@black.com","nAme":"James Black"}
             ]
}
</code>```

and the output should be something like

```<code>ret = { "users":[
                 {"email":"jogn@doe.com","name":"John Doe"},
                 {"email":"james@black.com","name":"James Black"}
                 ]
    }
</code>```

What I did is :

```<code>users = ret['users']
new_array = []
for item in users:
    for key in item:
        k = key.lower()
        new_array.append({k:item[key]})
</code>```

and the result is what I expected but I was wondering if there is a smart and better way to achieve this task. Is there a way to avoid the double loop?

Thanks.

答:
Complex one liner (surely not smart; just a fancy way):</p>

```<code>>>> ret = { "users":[
             {"EMAIL":"jogn@doe.com","Name":"John Doe"},
             {"EMail":"james@black.com","nAme":"James Black"}
             ]
}
>>> lower_cased = {k.lower():[{dk.lower():dv for dk,dv in d.items()} for d in v] for k,v in ret.items()}
>>> lower_cased
{'users': [{'email': 'jogn@doe.com', 'name': 'John Doe'}, {'email': 'james@black.com', 'name': 'James Black'}]}
</code>```

Body:
I am trying to do lowercase data transformation. My input data are in the following format

ret = { "users":[
             {"EMAIL":"jogn@doe.com","Name":"John Doe"},
             {"EMail":"james@black.com","nAme":"James Black"}
             ]
}

and the output should be something like

ret = { "users":[
                 {"email":"jogn@doe.com","name":"John Doe"},
                 {"email":"james@black.com","name":"James Black"}
                 ]
    }

What I did is :

users = ret['users']
new_array = []
for item in users:
    for key in item:
        k = key.lower()
        new_array.append({k:item[key]})

and the result is what I expected but I was wondering if there is a smart and better way to achieve this task. Is there a way to avoid the double loop?

Thanks.

Body:
Complex one liner (surely not smart; just a fancy way):

>>> ret = { "users":[
             {"EMAIL":"jogn@doe.com","Name":"John Doe"},
             {"EMail":"james@black.com","nAme":"James Black"}
             ]
}
>>> lower_cased = {k.lower():[{dk.lower():dv for dk,dv in d.items()} for d in v] for k,v in ret.items()}
>>> lower_cased
{'users': [{'email': 'jogn@doe.com', 'name': 'John Doe'}, {'email': 'james@black.com', 'name': 'James Black'}]}


问:
How do I avoid NullPointerExceptions in lambda comparators?
I want to compare two given objects which might be null at runtime. In my example:

```<code>@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}
</code>```

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...), but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner". I am new to lambda expressions.

答:
If you just want to use this in a JUnit test, why don't you just pass the objects you want to compare directly to the assertEquals method?

```<code>assertEquals("Agent.getId", a1.getId(), a2.getId());
</code>```

This also helps JUnit to generate a useful error message when the test fails.

If you want to do this in production code, you can use Objects.equals:

```<code>if (Objects.equals(a1.getId(), a2.getId())) { ... }
</code>```

which is present since Java 7.

Body:
I want to compare two given objects which might be null at runtime. In my example:

@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...), but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner". I am new to lambda expressions.

Body:
If you just want to use this in a JUnit test, why don't you just pass the objects you want to compare directly to the assertEquals method?

assertEquals("Agent.getId", a1.getId(), a2.getId());

This also helps JUnit to generate a useful error message when the test fails.

If you want to do this in production code, you can use Objects.equals:

if (Objects.equals(a1.getId(), a2.getId())) { ... }

which is present since Java 7.


问:
Rails 4.2.5 - Unable to upgrade "config.serve_static_files" to "config.public_file_server.enabled"
When I configure my production.rb file with the new Rails 5.1 method, 'public_file_server.enabled', I am unable to precompile my assets and then deploy my application (on Heroku).

Here's the error I see after running "RAILS_ENV=production bundle exec rake assets:precompile":

```<code>rake aborted!
NoMethodError: undefined method `public_file_server' for #<Rails::Application::Configuration:0x007f81f0624b60>
/Users/jmarbach/Documents/rubyscripts/concorde/config/environments/production.rb:21:in `block in <top (required)>'
/Users/jmarbach/Documents/rubyscripts/concorde/config/environments/production.rb:1:in `<top (required)>'
/Users/jmarbach/Documents/rubyscripts/concorde/config/environment.rb:5:in `<top (required)>'
</code>```

Here are the relevant lines in my production.rb file:

```<code># Leverage browser caching
config.static_cache_control = 'public, max-age=1000'

# Set header expiray date
config.public_file_server.enabled = true
config.public_file_server.headers = {
  'Cache-Control' => 'public, s-maxage=31536000, maxage=15552000',
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
  }
</code>```

Here is my rails configuration in my gem file:

```<code>gem 'rails', '4.2.5'
gem 'railties', '4.2.5'
</code>```

How can I access the newly merged method, 'public_file_server'?

答:
I have tried everything that belongs to Ruby on Rails but decided to jump over to nginx configurations. Here is what helps me to leverage browser caching:

```<code>location ~* \.(?:jpg|jpeg|gif|png|ico|gz|js|css|ttf)$ {
    expires 1M;
    access_log off;
    add_header Cache-Control "public";
}
</code>```

Hope it helps anybody:)

Body:
When I configure my production.rb file with the new Rails 5.1 method, 'public_file_server.enabled', I am unable to precompile my assets and then deploy my application (on Heroku).

Here's the error I see after running "RAILS_ENV=production bundle exec rake assets:precompile":

rake aborted!
NoMethodError: undefined method `public_file_server' for #<Rails::Application::Configuration:0x007f81f0624b60>
/Users/jmarbach/Documents/rubyscripts/concorde/config/environments/production.rb:21:in `block in <top (required)>'
/Users/jmarbach/Documents/rubyscripts/concorde/config/environments/production.rb:1:in `<top (required)>'
/Users/jmarbach/Documents/rubyscripts/concorde/config/environment.rb:5:in `<top (required)>'

Here are the relevant lines in my production.rb file:

# Leverage browser caching
config.static_cache_control = 'public, max-age=1000'

# Set header expiray date
config.public_file_server.enabled = true
config.public_file_server.headers = {
  'Cache-Control' => 'public, s-maxage=31536000, maxage=15552000',
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
  }

Here is my rails configuration in my gem file:

gem 'rails', '4.2.5'
gem 'railties', '4.2.5'

How can I access the newly merged method, 'public_file_server'?

Body:
I have tried everything that belongs to Ruby on Rails but decided to jump over to nginx configurations. Here is what helps me to leverage browser caching:

location ~* \.(?:jpg|jpeg|gif|png|ico|gz|js|css|ttf)$ {
    expires 1M;
    access_log off;
    add_header Cache-Control "public";
}

Hope it helps anybody:)


问:
How do I delete lines from the canvas in kivy
I'm creating a simple drawing application and in it, i'd like to add an undo button. What I have tried so far is this:

```<code>class DrawScreen(Screen):
    r = NumericProperty(0)
    g = NumericProperty(0)
    b = NumericProperty(0)
    brush_width = NumericProperty(2)

    def on_touch_down(self, touch):
        self.slider = self.ids.slider
        if self.slider.collide_point(touch.x, touch.y):
            self.brush_width = self.slider.value
        else:
            self.undo = [touch.x, touch.y]
            with self.canvas.before:
                Color(self.r, self.g, self.b)
                touch.ud["line"] = Line(points=self.undo, width=self.brush_width)
        return super(DrawScreen, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        if self.slider.collide_point(touch.x, touch.y):
            self.brush_width = self.slider.value
        else:
            try:
                self.undo += [touch.x, touch.y]
                touch.ud["line"].points = self.undo

            except:
                pass
        return super(DrawScreen, self).on_touch_move(touch)

    def color(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

    def undo_draw(self):
        self.undo = []
</code>```

This undo button clears the list but it doesn't affect the canvas in any way and doesn't remove any lines at all. What would be the appropriate way to go about this?

答:
Try putting them in an InstructionGroup then add to canvas, then simply remove the item from the canvas, with canvas.remove(item).

You might want to save the items if you want redo.

Try this example. I had to replace on_touch_down, it kept creating Instructions when I move my cursor with mouse pad, filling canvas with children:

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.graphics import Line, Color, InstructionGroup
from kivy.uix.widget import Widget

class MyWidget(Widget):

    undolist = []
    objects = []
    drawing = False

    def on_touch_up(self, touch):
        self.drawing = False

    def on_touch_move(self, touch):
        if self.drawing:
            self.points.append(touch.pos)
            self.obj.children[-1].points = self.points
        else:
            self.drawing = True
            self.points = [touch.pos]
            self.obj = InstructionGroup()
            self.obj.add(Color(1,0,0))
            self.obj.add(Line())
            self.objects.append(self.obj)
            self.canvas.add(self.obj)

    def undo(self):
        item = self.objects.pop(-1)
        self.undolist.append(item)
        self.canvas.remove(item)

    def redo(self):
        item = self.undolist.pop(-1)
        self.objects.append(item)
        self.canvas.add(item)

KV = """

BoxLayout:
    MyWidget:
        id: widget
    Button:
        text: "undo"
        on_release:
            widget.undo()
    Button:
        text: "redo"
        on_release:
            widget.redo()

"""

class MyApp(App):

    def build(self):
        root = Builder.load_string(KV)
        return root

MyApp().run()
</code>```

Body:
I'm creating a simple drawing application and in it, i'd like to add an undo button. What I have tried so far is this:

class DrawScreen(Screen):
    r = NumericProperty(0)
    g = NumericProperty(0)
    b = NumericProperty(0)
    brush_width = NumericProperty(2)

    def on_touch_down(self, touch):
        self.slider = self.ids.slider
        if self.slider.collide_point(touch.x, touch.y):
            self.brush_width = self.slider.value
        else:
            self.undo = [touch.x, touch.y]
            with self.canvas.before:
                Color(self.r, self.g, self.b)
                touch.ud["line"] = Line(points=self.undo, width=self.brush_width)
        return super(DrawScreen, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        if self.slider.collide_point(touch.x, touch.y):
            self.brush_width = self.slider.value
        else:
            try:
                self.undo += [touch.x, touch.y]
                touch.ud["line"].points = self.undo

            except:
                pass
        return super(DrawScreen, self).on_touch_move(touch)

    def color(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

    def undo_draw(self):
        self.undo = []

This undo button clears the list but it doesn't affect the canvas in any way and doesn't remove any lines at all. What would be the appropriate way to go about this?

Body:
Try putting them in an InstructionGroup then add to canvas, then simply remove the item from the canvas, with canvas.remove(item).

You might want to save the items if you want redo.

Try this example. I had to replace on_touch_down, it kept creating Instructions when I move my cursor with mouse pad, filling canvas with children:

from kivy.app import App
from kivy.lang import Builder
from kivy.graphics import Line, Color, InstructionGroup
from kivy.uix.widget import Widget

class MyWidget(Widget):

    undolist = []
    objects = []
    drawing = False

    def on_touch_up(self, touch):
        self.drawing = False

    def on_touch_move(self, touch):
        if self.drawing:
            self.points.append(touch.pos)
            self.obj.children[-1].points = self.points
        else:
            self.drawing = True
            self.points = [touch.pos]
            self.obj = InstructionGroup()
            self.obj.add(Color(1,0,0))
            self.obj.add(Line())
            self.objects.append(self.obj)
            self.canvas.add(self.obj)

    def undo(self):
        item = self.objects.pop(-1)
        self.undolist.append(item)
        self.canvas.remove(item)

    def redo(self):
        item = self.undolist.pop(-1)
        self.objects.append(item)
        self.canvas.add(item)

KV = """

BoxLayout:
    MyWidget:
        id: widget
    Button:
        text: "undo"
        on_release:
            widget.undo()
    Button:
        text: "redo"
        on_release:
            widget.redo()

"""

class MyApp(App):

    def build(self):
        root = Builder.load_string(KV)
        return root

MyApp().run()


问:
How can I declare a dropdown box in a view to set a value to a model in ASP.NET MVC?
I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.

I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.

Finally, how do I pass the selected id from the dropdown box back to my action in the controller?

答:
If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.

```<code>//Lets assume you retrieve your product types somehow here
ViewData["ProductTypes"] =  new List<ProductType>();
</code>```

Then inside your view type the following

```<code><%= Html.DropDownList("productType",
    new SelectList((IEnumerable)ViewData["ProductTypes"],
    "TypeID", "Description"))%>
</code>```

TypeID and Description refers to the properties of your object of type ProductType

Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.

OwnerDisplayName: Petros

LastEditorDisplayName: Petros

Body:
If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.

//Lets assume you retrieve your product types somehow here
ViewData["ProductTypes"] =  new List<ProductType>();

Then inside your view type the following

<%= Html.DropDownList("productType",
    new SelectList((IEnumerable)ViewData["ProductTypes"],
    "TypeID", "Description"))%>

TypeID and Description refers to the properties of your object of type ProductType

Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.

OwnerDisplayName: Konstantinos


问:
How to pass value from javascript to php file
I am getting value via JQuery as something like this

```<code>var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var id = dim[1].split('=')[1];
</code>```

Now i want to send or get this "id" value into same php file. I think we can only get value on other php page using get method. I want to get value on same php file.

I think we can do with this using AJAX right?

If yes please give me some links or code how to get? I am newbie to ajax.

答:
well, if you only want to send that data to the server and you don't want to retrieve anything else and don't know or don't want to use ajax, a more simpler solution would be to attach the desired url on a hidden dom object. such as :

witch can be added to the dom in multiple ways.

If you want to use ajax, I recommend using a library such as jQuery, wich is optimized for cross-browser web apps. With jQuery, the syntax is very simple :```
$.get(
    "http://my-host.com/my-script.php",
    {"id" : id},
    function(data){
        // do something with the response
    }
);
```
You could use "post" instead of "get" depending on your needs. I recommend you take a peak at jQuery documentation.

Body:
I am getting value via JQuery as something like this

var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var id = dim[1].split('=')[1];

Now i want to send or get this "id" value into same php file. I think we can only get value on other php page using get method. I want to get value on same php file.

I think we can do with this using AJAX right?

If yes please give me some links or code how to get? I am newbie to ajax.

Body:
well, if you only want to send that data to the server and you don't want to retrieve anything else and don't know or don't want to use ajax, a more simpler solution would be to attach the desired url on a hidden dom object. such as :

<img src="http://my-host.com/my-script.php?id="+id style="display:none;"/>

witch can be added to the dom in multiple ways.

If you want to use ajax, I recommend using a library such as jQuery, wich is optimized for cross-browser web apps. With jQuery, the syntax is very simple :

$.get(
    "http://my-host.com/my-script.php",
    {"id" : id},
    function(data){
        // do something with the response
    }
);

You could use "post" instead of "get" depending on your needs. I recommend you take a peak at jQuery documentation.


问:
MYSQL / Query Builder / Eloquent - Transpose rows to columns
** Scheduling System (Number of Appointments by Week):**

I am looking to generate a dashboard showing a list of consultants and the number of appointments they have scheduled over the coming weeks.

So my sql query / eloquent equivalent queries for my specific scenario are as follows:

```<code>select
    consultant_id,
    count(appointment) as num_appointments,
    YEARWEEK(appointment, 1) as year_week
from
    appointments
where
    appointments.deleted_at is null
    and appointments.consultant_id in (25, 29, 19, 38, 37, 32, 14, 21, 12, 40)
    and appointment > '2014-12-07 16:39:07'
    and YEARWEEK(now(), 1) + 4 >= YEARWEEK(appointment, 1)
group by consultant_id, YEARWEEK(appointment, 1)
order by consultant_id, YEARWEEK(appointment, 1) asc;

    $consultants = $this->consultant
        ->with(['appointments' => function($q) {
            $q->scheduled()
                ->where(\DB::raw('YEARWEEK(now(), 1) + 4'), '>=', \DB::raw('YEARWEEK(appointment, 1)'))
                ->select([
                    'consultant_id',
                    \DB::raw('count(appointment) as num_appointments'),
                    \DB::raw('YEARWEEK(appointment, 1) as year_week'),
                ])
                ->groupBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)'))
                ->orderBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)', 'DESC'));
        }])
        ->orderBy('name')
        ->paginate(10);
</code>```

This works in so far as for every consultant, if there are appointments, it will provide information as follows:

```<code>consultant_id   num_appointments    year_week
14                      5            201450
14                      3            201451
29                      4            201450
29                      1            201451
40                      1            201450
40                      1            201452
</code>```

However if there are no appointments, the year_week will be missing.

So in mysql then in Laravel's query builder, I would like to be able to transpose the year_week rows to columns. So that the table will output:

```<code>consultant_id    week0     week1    week2
consultant_id   201450    201451    201452
14                 5         3         NULL
29                 4         1         NULL
40                 1         NULL      1
</code>```

UPDATE

```<code>SELECT
  consultant_id,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 0 WEEK), 1) = YEARWEEK(appointment, 1) THEN 1 END) as this_week,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 1 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week1,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 2 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week2
FROM
  demand as d
WHERE date_created >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
GROUP BY consultant_id;
</code>```

答:
Solution 1: Using transpose in spatie macro collection ?

The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.

```<code>collect([
    ['Jane', 'Bob', 'Mary'],
    ['jane@example.com', 'bob@example.com', 'mary@example.com'],
    ['Doctor', 'Plumber', 'Dentist'],
]
)->transpose()->toArray();

// [
//     ['Jane', 'jane@example.com', 'Doctor'],
//     ['Bob', 'bob@example.com', 'Plumber'],
//     ['Mary', 'mary@example.com', 'Dentist'],
// ]
</code>```

Solution 2: Using group by in collection
The groupBy method groups the collection's items by a given key:

```<code>$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/
</code>```

Body:
** Scheduling System (Number of Appointments by Week):**

I am looking to generate a dashboard showing a list of consultants and the number of appointments they have scheduled over the coming weeks.

So my sql query / eloquent equivalent queries for my specific scenario are as follows:

select
    consultant_id,
    count(appointment) as num_appointments,
    YEARWEEK(appointment, 1) as year_week
from
    appointments
where
    appointments.deleted_at is null
    and appointments.consultant_id in (25, 29, 19, 38, 37, 32, 14, 21, 12, 40)
    and appointment > '2014-12-07 16:39:07'
    and YEARWEEK(now(), 1) + 4 >= YEARWEEK(appointment, 1)
group by consultant_id, YEARWEEK(appointment, 1)
order by consultant_id, YEARWEEK(appointment, 1) asc;

    $consultants = $this->consultant
        ->with(['appointments' => function($q) {
            $q->scheduled()
                ->where(\DB::raw('YEARWEEK(now(), 1) + 4'), '>=', \DB::raw('YEARWEEK(appointment, 1)'))
                ->select([
                    'consultant_id',
                    \DB::raw('count(appointment) as num_appointments'),
                    \DB::raw('YEARWEEK(appointment, 1) as year_week'),
                ])
                ->groupBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)'))
                ->orderBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)', 'DESC'));
        }])
        ->orderBy('name')
        ->paginate(10);

This works in so far as for every consultant, if there are appointments, it will provide information as follows:

consultant_id   num_appointments    year_week
14                      5            201450
14                      3            201451
29                      4            201450
29                      1            201451
40                      1            201450
40                      1            201452

However if there are no appointments, the year_week will be missing.

So in mysql then in Laravel's query builder, I would like to be able to transpose the year_week rows to columns. So that the table will output:

consultant_id    week0     week1    week2
consultant_id   201450    201451    201452
14                 5         3         NULL
29                 4         1         NULL
40                 1         NULL      1

UPDATE

SELECT
  consultant_id,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 0 WEEK), 1) = YEARWEEK(appointment, 1) THEN 1 END) as this_week,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 1 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week1,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 2 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week2
FROM
  demand as d
WHERE date_created >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
GROUP BY consultant_id;

Body:
Solution 1: Using transpose in spatie macro collection ?

The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.

collect([
    ['Jane', 'Bob', 'Mary'],
    ['jane@example.com', 'bob@example.com', 'mary@example.com'],
    ['Doctor', 'Plumber', 'Dentist'],
]
)->transpose()->toArray();

// [
//     ['Jane', 'jane@example.com', 'Doctor'],
//     ['Bob', 'bob@example.com', 'Plumber'],
//     ['Mary', 'mary@example.com', 'Dentist'],
// ]

Solution 2: Using group by in collection
The groupBy method groups the collection's items by a given key:

$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/


问:
angular: Validate multiple dependent fields
Let's say I have the following (very simple) data structure:

```<code>$scope.accounts = [{
   percent: 30,
   name: "Checking"},
 { percent: 70,
   name: "Savings"}];
</code>```

Then I have the following structure as part of a form:

```<code><div ng-repeat="account in accounts">
    <input type="number" max="100" min="0" ng-model="account.percent" />
    <input type="text" ng-model="account.name" />
</div>
</code>```

Now, I want to validate that the percents sum to 100 for each set of accounts, but most of the examples I have seen of custom directives only deal with validating an individual value. What is an idiomatic way to create a directive that would validate multiple dependent fields at once? There are a fair amount of solutions for this in jquery, but I haven't been able to find a good source for Angular.

EDIT: I came up with the following custom directive ("share" is a synonym for the original code's "percent").
The share-validate directive takes a map of the form "{group: accounts, id: $index}" as its value.

```<code>app.directive('shareValidate', function() {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
            params = angular.copy(scope.$eval(attr.shareValidate));
            params.group.splice(params.id, 1);
            var sum = +viewValue;
            angular.forEach(params.group, function(entity, index) {
                sum += +(entity.share);
            });
            ctrl.$setValidity('share', sum === 100);
            return viewValue;
        });
    }
};
});
</code>```

This ALMOST works, but can't handle the case in which a field is invalidated, but a subsequent change in another field makes it valid again. For example:

```<code>Field 1: 61
Field 2: 52
</code>```

If I take Field 2 down to 39, Field 2 will now be valid, but Field 1 is still invalid. Ideas?

答:
You can define a single directive that is only responsible for this check.

```<code><form>
  <div ng-repeat="account in accounts">
    <input type="number" max="100" min="0" ng-model="account.percent" />
    <input type="text" ng-model="account.name" />
  </div>
  <!-- HERE IT IS -->
  <sum-up-to-hundred accounts="accounts"></sum-up-to-hundred>
</form>
</code>```

And here's the simple directive's code.

```<code>app.directive('sumUpToHundred', function() {
  return {
    scope: {
      accounts: '<'
    },
    require: {
      formCtrl: '^form'
    },
    bindToController: true,
    controllerAs: '$ctrl',
    controller: function() {
      var vm = this;

      vm.$doCheck = function(changes) {
        var sum = vm.accounts.map((a)=> a.percent).reduce((total, n)=> total + n);
        if (sum !== 100) {
          vm.formCtrl.$setValidity('sumuptohundred', false);
        } else {
          vm.formCtrl.$setValidity('sumuptohundred', true);
        }
      };
    }
  };
});
</code>```

Here's a plunker.

Body:
Let's say I have the following (very simple) data structure:

$scope.accounts = [{
   percent: 30,
   name: "Checking"},
 { percent: 70,
   name: "Savings"}];

Then I have the following structure as part of a form:

    <input type="number" max="100" min="0" ng-model="account.percent" />
    <input type="text" ng-model="account.name" />

Now, I want to validate that the percents sum to 100 for each set of accounts, but most of the examples I have seen of custom directives only deal with validating an individual value. What is an idiomatic way to create a directive that would validate multiple dependent fields at once? There are a fair amount of solutions for this in jquery, but I haven't been able to find a good source for Angular.

EDIT: I came up with the following custom directive ("share" is a synonym for the original code's "percent").
The share-validate directive takes a map of the form "{group: accounts, id: $index}" as its value.

app.directive('shareValidate', function() {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
            params = angular.copy(scope.$eval(attr.shareValidate));
            params.group.splice(params.id, 1);
            var sum = +viewValue;
            angular.forEach(params.group, function(entity, index) {
                sum += +(entity.share);
            });
            ctrl.$setValidity('share', sum === 100);
            return viewValue;
        });
    }
};
});

This ALMOST works, but can't handle the case in which a field is invalidated, but a subsequent change in another field makes it valid again. For example:

Field 1: 61
Field 2: 52

If I take Field 2 down to 39, Field 2 will now be valid, but Field 1 is still invalid. Ideas?

Body:
You can define a single directive that is only responsible for this check.

<form>
  <div ng-repeat="account in accounts">
    <input type="number" max="100" min="0" ng-model="account.percent" />
    <input type="text" ng-model="account.name" />
  </div>
  <!-- HERE IT IS -->
  <sum-up-to-hundred accounts="accounts"></sum-up-to-hundred>
</form>

And here's the simple directive's code.

app.directive('sumUpToHundred', function() {
  return {
    scope: {
      accounts: '<'
    },
    require: {
      formCtrl: '^form'
    },
    bindToController: true,
    controllerAs: '$ctrl',
    controller: function() {
      var vm = this;

      vm.$doCheck = function(changes) {
        var sum = vm.accounts.map((a)=> a.percent).reduce((total, n)=> total + n);
        if (sum !== 100) {
          vm.formCtrl.$setValidity('sumuptohundred', false);
        } else {
          vm.formCtrl.$setValidity('sumuptohundred', true);
        }
      };
    }
  };
});

Here's a plunker.


问:
JSON.parse is an “undefined” object
I created json with php. Data coming with ajax. But JSON.parse is  giving an “undefined” object. Why ?

Php CODE

```<code> $emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode($emparray);
</code>```

Ajax CODE

```<code>   $.ajax({
        type: "GET",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= JSON.parse(msg);
            alert(obj.name);// giving undefined
        },
        error: function (error) {
        }
    });
</code>```

json

```<code>[{"name":"eng","a":"sdf"}]
</code>```

答:
A better way to get data from server

```<code>$emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode(array("data"=>$emparray));
</code>```

Put all the json response on a key which is data here then at front end define that the server response is in JSON by dataType and then there is no need to parse data by JSON.parse()

msg.data.length will provide you the validaton on if the data received from server is empty or not which will prevent the undefined error

```<code> $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= msg.data;
           if(msg.data.length){
                  alert(msg.data[0].name);// wll give name at 0 index
              }
        },
        error: function (error) {
        }
    });
</code>```

Title: JSON.parse is an “undefined” object

Body:
I created json with php. Data coming with ajax. But JSON.parse is  giving an “undefined” object. Why ?

Php CODE

 $emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode($emparray);

Ajax CODE

   $.ajax({
        type: "GET",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= JSON.parse(msg);
            alert(obj.name);// giving undefined
        },
        error: function (error) {
        }
    });

json

[{"name":"eng","a":"sdf"}]

Body:
A better way to get data from server

$emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode(array("data"=>$emparray));

Put all the json response on a key which is data here then at front end define that the server response is in JSON by dataType and then there is no need to parse data by JSON.parse()

msg.data.length will provide you the validaton on if the data received from server is empty or not which will prevent the undefined error

 $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= msg.data;
           if(msg.data.length){
                  alert(msg.data[0].name);// wll give name at 0 index
              }
        },
        error: function (error) {
        }
    });


问:
How to remove angular expression attributes from element
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

```<code><button myDirective [disabled]="someExpression">Clippy</button>
</code>```

My Directive

```<code>@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}
</code>```

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

答:
You probably need two copies of the button but only one of them displayed at a time</p>

```<code><ng-container *ngIf="showButtonWithDisabledExpr">
        <button [disabled]="someExpression">Clippy</button>
</ng-container>

<ng-container *ngIf="!showButtonWithDisabledExpr">
        <button>Clippy</button>
</ng-container>
</code>```

Body:
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

<button myDirective [disabled]="someExpression">Clippy</button>

My Directive

@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

Body:
You probably need two copies of the button but only one of them displayed at a time

<ng-container *ngIf="showButtonWithDisabledExpr">
        <button [disabled]="someExpression">Clippy</button>
</ng-container>

<ng-container *ngIf="!showButtonWithDisabledExpr">
        <button>Clippy</button>
</ng-container>


问:
out of bounds error when down sampling image
Does anyone know why my index matrix[k][m]=sum/9 is out of range? I'm pretty sure that my solution is correct. I tried debugging it, but I still cannot think
why it's not working.

```<code>def downsample_by_3(image):

    matrix_image = copy.deepcopy(image)
    matrix=[ [], [], [] ]
    k=0
    m=0
    for i in range(0,len(matrix_image),3):

        for j in range(0,len(matrix_image[i]),3):

            sum=0

            for r in range(i,i+3):
                for c in range(j,j+3):
                    sum+=matrix_image[r][c]
            m+=1
            matrix[k][m]=sum/9

        m=0
        k+=1

    return matrix
</code>```

The image is presented as a matrix (list of lists).

Let's say I took this list,

```<code>print(downsample_by_3([[2,2,2],[2,2,2],[2,2,2]]))
</code>```

it should return a list with 18.

Another example of it to understand it better:

答:
You start with matrix hard-coded to a sequence of empty lists matrix=[ [], [], [] ], and then in the

```<code>matrix[k][m]=sum/9
</code>```

line, you try to force a value into one of those slots, but there are no slots. The k will be okay for the first few (from 0 through 2), but the m is going to error right away.  Seems like you need to dynamically create matrix on the fly.  Maybe

```<code>matrix[k].append(sum/9)
</code>```

Also, a return matrix at the end your function wouldn't hurt.  :)

The above should help you move forward. At least it gives running code.

Body:
Does anyone know why my index matrix[k][m]=sum/9 is out of range? I'm pretty sure that my solution is correct. I tried debugging it, but I still cannot think
why it's not working.

def downsample_by_3(image):

    matrix_image = copy.deepcopy(image)
    matrix=[ [], [], [] ]
    k=0
    m=0
    for i in range(0,len(matrix_image),3):

        for j in range(0,len(matrix_image[i]),3):

            sum=0

            for r in range(i,i+3):
                for c in range(j,j+3):
                    sum+=matrix_image[r][c]
            m+=1
            matrix[k][m]=sum/9

        m=0
        k+=1

    return matrix

The image is presented as a matrix (list of lists).

Let's say I took this list,

print(downsample_by_3([[2,2,2],[2,2,2],[2,2,2]]))

it should return a list with 18.

Another example of it to understand it better:

Body:
You start with matrix hard-coded to a sequence of empty lists matrix=[ [], [], [] ], and then in the

matrix[k][m]=sum/9

line, you try to force a value into one of those slots, but there are no slots. The k will be okay for the first few (from 0 through 2), but the m is going to error right away.  Seems like you need to dynamically create matrix on the fly.  Maybe

matrix[k].append(sum/9)

Also, a return matrix at the end your function wouldn't hurt.  :)

The above should help you move forward. At least it gives running code.


问:
Selenium with Crome and Maven not works. ClassNotFoundException: org.apache.http.auth.Credentials
I want to run headless Chrome with Selenium, but this code not works:

```<code>    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    File file = new File("/usr/bin/chromedriver");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver(chromeOptions);
</code>```

It compiles fine, but at runtime crashes with stacktrace:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:62)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:39)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:158)
    at org.chrome.automation.Starter.main(Starter.java:20)
Caused by: java.lang.ClassNotFoundException: org.apache.http.auth.Credentials
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more
</code>```

The POM contains just two dependencies:

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
</code>```

I thought the problem in Selenium dependencies, as they are rely on some apache code but not download dependent components. I tried to add apache dependencies like:

```<code>    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.6</version>
    </dependency>
</code>```

But problem persists.

Please help to run selenium with headless Crome.

答:
I faced the same issue, not only with chrome but with other browses too.
seems, there were some jars missing, do following and it should fix the issue:

Close the eclipse

Go to "C:\Users\myuser.m2\repository" folder and delete all the files and folder from here

Open elclipse, select your project and do alt+f5 and check option Force Update of Snapshots.

Wait till it builds, it should be fixed now.

Worked for me.

Body:
I want to run headless Chrome with Selenium, but this code not works:

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("--headless");
    File file = new File("/usr/bin/chromedriver");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    WebDriver driver = new ChromeDriver(chromeOptions);

It compiles fine, but at runtime crashes with stacktrace:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:62)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:39)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:184)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:171)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:158)
    at org.chrome.automation.Starter.main(Starter.java:20)
Caused by: java.lang.ClassNotFoundException: org.apache.http.auth.Credentials
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more

The POM contains just two dependencies:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>

I thought the problem in Selenium dependencies, as they are rely on some apache code but not download dependent components. I tried to add apache dependencies like:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.6</version>
    </dependency>

But problem persists.

Please help to run selenium with headless Crome.


问:
Swift contentOffset scroll
I am developing a small application for tvOS where I need to show a UITextView.

Unfortunately sometimes this text can't fit inside the screen, that's why I need a way to scroll to the bottom of it programmatically.

I've tried using the following code:

```<code>self.setContentOffset(offset, animated: true)
</code>```

It's actually working as intended, except for the fact that I need to handle the animation speed, so that the user can actually read; at the moment it's too fast.

This is what I tried to do, but with little success:

```<code>let offset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
UIView.animate(withDuration: 4, animations: {
  self.setContentOffset(offset, animated: false)
})
</code>```

I need a way to keep the text in place and scroll it to show the missing lines.

I am using a UITextView inside an UIScrollView.

Thanks.

答:
If anyone is looking for a solution, this is what I ended up using:

```<code>var textTopDistance = 100
//calculate height of the text not being displayed
textNotVisibleHeight = descriptionLabel.contentSize.height - scrollView.bounds.size.height

func scrollText() {
    //start new thread
    DispatchQueue.main.async() {
        //animation
        UIView.animate(withDuration: 6, delay: 2, options: UIViewAnimationOptions.curveLinear, animations: {
            //set scrollView offset to move the text
            self.scrollView.contentOffset.y = CGFloat(self.textNotVisibleHeight - self.textTopDistance)
        }, completion: nil)
    }
}
</code>```

It's not perfect I know, but at least it's working as intended.

Title: Swift contentOffset scroll

Body:
I am developing a small application for tvOS where I need to show a UITextView.

Unfortunately sometimes this text can't fit inside the screen, that's why I need a way to scroll to the bottom of it programmatically.

I've tried using the following code:

self.setContentOffset(offset, animated: true)

It's actually working as intended, except for the fact that I need to handle the animation speed, so that the user can actually read; at the moment it's too fast.

This is what I tried to do, but with little success:

let offset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
UIView.animate(withDuration: 4, animations: {
  self.setContentOffset(offset, animated: false)
})

I need a way to keep the text in place and scroll it to show the missing lines.

I am using a UITextView inside an UIScrollView.

Thanks.

Body:
If anyone is looking for a solution, this is what I ended up using:

var textTopDistance = 100
//calculate height of the text not being displayed
textNotVisibleHeight = descriptionLabel.contentSize.height - scrollView.bounds.size.height

func scrollText() {
    //start new thread
    DispatchQueue.main.async() {
        //animation
        UIView.animate(withDuration: 6, delay: 2, options: UIViewAnimationOptions.curveLinear, animations: {
            //set scrollView offset to move the text
            self.scrollView.contentOffset.y = CGFloat(self.textNotVisibleHeight - self.textTopDistance)
        }, completion: nil)
    }
}

It's not perfect I know, but at least it's working as intended.


问:
Difference between Debug and Release folders
Could you advise me what is the difference between Debug and Release folders?
Thanks
Furqan</p>

答:
The debug folder usually contains your program compiled for debugging, that is there is additional information included, such as variable names, that help you find errors in the program.

The release folder contains your program without any of that. Just what is necessary for the program to run.


问:
Dagger2 Optimal way to inject dependencies from two different classes
After searching and trying too many things i'm stuck in some what seems like an easy problem.
Below is my module which is reponsible for injecting retrofit.

```<code>@Module
public class NetworkingModule
{
    @Provides
    public Retrofit providesRetrofit()
    {
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        Retrofit retrofit = new Retrofit.Builder()
                                        .baseUrl(Constants.BASE_URL)
                                        .addConverterFactory(GsonConverterFactory.create(gson))
                                        .build();

        return retrofit;
    }

}
</code>```

My NetworkComponent

```<code>@Component( modules = NetworkingModule.class)
public interface NetworkingComponent {
    void inject(DashboardPresenterImpl target);

    void inject(PicksPresenterImpl picksPresenter);

    void inject(LoadsPresenterImpl loadsPresenter);

    void inject(ShippingPresenterImpl shippingPresenter);

    void inject(GeneralFilePresenterImpl generalFilePresenter);
}
</code>```

A utility class with constructor injection. Please note this class also has injection of AppPreferences.

```<code>public class AppUtils {
    private Context context;

    @Inject
    AppPreferences preferences;

    @Inject
    public AppUtils(@ActivityContext Context context)
    {
        this.context = context;

        /*ActivityComponent component = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule((Activity) context))
                .build();
        component.inject(this);*/
    }
}
</code>```

Now in my Code i want to achieve this

```<code>Class MyPresenterImpl{
@Inject
    Retrofit retrofit;

    @Inject
    AppUtils appUtils;
}
</code>```

Please suggest an optimize and good way to achieve the above.

EDIT

Added AppPreference.java

```<code>public class AppPreferences {
    @Inject
    SharedPreferences sharedPreferences;

    private SharedPreferences.Editor editor;

    @Inject
    public AppPreferences(@ActivityContext Context context)
    {
        ApplicationComponent component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule((Application) context.getApplicationContext()))
                .build();
        component.inject(this);

        editor = sharedPreferences.edit();
    }

    public void putString(String key, String value)
    {
        editor.putString(key, value).commit();
    }

    public String getString(String key)
    {
        return sharedPreferences.getString(key, null);
    }

}
</code>```

答:
my suggestion:
create context module:

```<code>@Module
public class ContextModule
{
    Context context;

    public ContextModule(Context context) {
        this.context = context;
    }

    @Provides
    @AppScope
    Context context() {
        return context;
    }
}
</code>```

create SharedPreferences module

```<code>@Module
public class SharedPreferencesModule
{

    @Provides
    @AppScope
    AppSharedPreferences provideAppSharedPreferences(Context context) {
        return new AppSharedPreferences(context.getSharedPreferences("App",Context.MODE_PRIVATE));
    }
}
</code>```

same way You can create more modules if you need to (for example for AppUtils)

instead of creating separate component for network, create one for your app

```<code>@Component( modules = {ContextModule.class, NetworkingModule.class, SharedPreferencesModule})
public interface AppComponent {...
</code>```

Body:
After searching and trying too many things i'm stuck in some what seems like an easy problem.
Below is my module which is reponsible for injecting retrofit.

@Module
public class NetworkingModule
{
    @Provides
    public Retrofit providesRetrofit()
    {
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        Retrofit retrofit = new Retrofit.Builder()
                                        .baseUrl(Constants.BASE_URL)
                                        .addConverterFactory(GsonConverterFactory.create(gson))
                                        .build();

        return retrofit;
    }

}

My NetworkComponent

@Component( modules = NetworkingModule.class)
public interface NetworkingComponent {
    void inject(DashboardPresenterImpl target);

    void inject(PicksPresenterImpl picksPresenter);

    void inject(LoadsPresenterImpl loadsPresenter);

    void inject(ShippingPresenterImpl shippingPresenter);

    void inject(GeneralFilePresenterImpl generalFilePresenter);
}

A utility class with constructor injection. Please note this class also has injection of AppPreferences.

public class AppUtils {
    private Context context;

    @Inject
    AppPreferences preferences;

    @Inject
    public AppUtils(@ActivityContext Context context)
    {
        this.context = context;

        /*ActivityComponent component = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule((Activity) context))
                .build();
        component.inject(this);*/
    }
}

Now in my Code i want to achieve this

Class MyPresenterImpl{
@Inject
    Retrofit retrofit;

    @Inject
    AppUtils appUtils;
}

Please suggest an optimize and good way to achieve the above.

EDIT

Added AppPreference.java

public class AppPreferences {
    @Inject
    SharedPreferences sharedPreferences;

    private SharedPreferences.Editor editor;

    @Inject
    public AppPreferences(@ActivityContext Context context)
    {
        ApplicationComponent component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule((Application) context.getApplicationContext()))
                .build();
        component.inject(this);

        editor = sharedPreferences.edit();
    }

    public void putString(String key, String value)
    {
        editor.putString(key, value).commit();
    }

    public String getString(String key)
    {
        return sharedPreferences.getString(key, null);
    }

}

Body:
my suggestion:
create context module:

@Module
public class ContextModule
{
    Context context;

    public ContextModule(Context context) {
        this.context = context;
    }

    @Provides
    @AppScope
    Context context() {
        return context;
    }
}

create SharedPreferences module

@Module
public class SharedPreferencesModule
{

    @Provides
    @AppScope
    AppSharedPreferences provideAppSharedPreferences(Context context) {
        return new AppSharedPreferences(context.getSharedPreferences("App",Context.MODE_PRIVATE));
    }
}

same way You can create more modules if you need to (for example for AppUtils)

instead of creating separate component for network, create one for your app

@Component( modules = {ContextModule.class, NetworkingModule.class, SharedPreferencesModule})
public interface AppComponent {...


问:
Jasypt: how secure master password?
Colleagues, i used Jasypt in my spring-boot project (standalone jar running on Windows).
I need to pass master password via command line to run jar .
It looks like:

java -jar -Djasypt.encryptor.password=masterpass app-1.0.0-RELEASE.jar

So anybody can see masterpass via Windows Task Manager:

How to secure this masterpass?

I have found an example where master password is stored in Windows Environment variable, but, it seems, no good idea.

答:
It is generally very difficult to hide anything when running on the client's workstation. At the end - when passwords/keys are encrypted, you need to store the password or private key somewhere anyway :/

You can encode/encrypt  data to make it more difficult, but once the binaries and configuration reside at the client side, you won't stop a dedicated adversary easily.

If you at least don't want to show the password outside (in the environment or command line) - how about reading the master password from a file and setting a system property in the main before running anything else?

(please let me know if it worked)

Title: Jasypt: how secure master password?


问:
How to update time-to-live(TTL) of existing records in Cassandra DB?
As Cassandra DB is providing a option to set Time-to-live(TTL) value to automatically delete the record on the basis of TTL value set with record. I have a case that user can change the date of data expiry, means user can change the data expiration date any time.

Case:

Suppose default expiration period is 10 days.

Then inserted some records with setting TTL for 10 days.

after 2 days user change expiration period to 30 days.

But the previous data inserted with 10 days TTL period automatically gets deleted after 10 days instead of 30 days.

Requirement: Whenever user changes the expiration period through UI, we wanted to change TTL in database.
    Is there any option to update the TTL for records in Cassandra DB.

答:
This work on Cassandra 2.0.7

You can RE-INSERT the same data changing only TTL.

INSERT INTO Table (col1, col2 ) VALUES ( '001','aaa') USING TTL 200;

INSERT INTO Table (col1, col2 ) VALUES ( '001','aaa') USING TTL 2;
Wait 2 sec and the row disappear;

I found also this by DataStax:
To change the TTL of a specific column, you must re-insert the data with a new TTL. Apache Cassandra™ upserts the column with the new TTL, replacing the old value with the old TTL, if any exists.

See this link


问:
shuffle JavaScript Array
Hy guys. I am making a game of Memory and to achieve that I had to somehow shuffle images in Array. I found an old answer on Stack Overflow, Fisher–Yates shuffle, and used that, and it works but I don't understand how. Can someone explain step by step and what each element represents in this code. Especially first line, how are there three values in a variable. Thank you.

```<code>function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
</code>```

Used like so:

```<code>var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);
</code>```

答:
```<code><p id="result">

<script>
var arrayList= ['a','b','c','d','e','f','g'];
arrayList.sort(function(){
    return 0.5 - Math.random()
})

document.getElementById("result").innerHTML  = arrayList;

</script>
</code>```

Title: shuffle JavaScript Array

Body:
Hy guys. I am making a game of Memory and to achieve that I had to somehow shuffle images in Array. I found an old answer on Stack Overflow, Fisher–Yates shuffle, and used that, and it works but I don't understand how. Can someone explain step by step and what each element represents in this code. Especially first line, how are there three values in a variable. Thank you.

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Used like so:

var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);