问:
How to call a custom rollback method in Spring Transaction Management?
Environment: Spring 3, Custom Transaction Management, JDBC Transactions

I just read the Spring docs on using the transaction template to handle transaction management. It seemed overly complex so I want to ask:

Most of my transactions are JDBC related, meaning I just declare an @Transactional on my service. But now I am making a REST service call to another site which needs to rollback if any of the following JDBC operations fail, I'll provide the rollback code in this case.

As I progress in my method, in my transaction - I want to save a reference to the REST service call (needed to roll back that action), and upon exception I just want a method myCustomRollback() called which can access the previously stored object.

Why not just provide a map in the transactionTemplate for storing stuff and define a custom rollback method on the @Transactional annotation?

This is the way I think about it, I'm not following the way Spring thinks about this. Can someone help me bridge the gap between what I want and how I accomplish it most efficiently in Spring? I only need to do this for a few special case operations.

答:
To anyone still reading this:

I solved a similar problem with spring events - as suggested by Den Roman in option 3.
Here's the basic idea (scenario is fictional):

Whenever I perform external operations that need to be rolled back together with the transaction, I publish an event inside my @Transactional method using support from spring (org.springframework.context.ApplicationEventPublisher):

```<code>@Transactional
public String placeOrder(Order order) {
    String orderId = orderServiceGateway.createOrder(order);
    applicationEventPublisher.publishEvent(new OrderCreatedEvent(orderId));
    workflowService.startWorkflow(orderId);
    return orderId;
}
</code>```

The event itself can be any object - I created a POJO with details about the remote entity to be deleted.

Then I registered a special event listener that is bound to a transaction phase - in my case to the rollback:

```<code>@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void rollBackOrder(OrderCreatedEvent orderCreatedEvent) {
    String orderId = orderCreatedEvent.getOrderId();
    orderServiceGateway.deleteOrder(orderId);
}
</code>```

Of course, it's recommended to catch & log the exception from rollback operation, not to lose the original exception from the placeOrder() method.

By default these events are synchronous, but they can be made async by additional configuration.

Here's a very good article on this mechanism, including detailed configuration and pitfalls: Transaction Synchronization and Spring Application Events (DZone)

While I don't like the solution 100% because it clutters the business logic with event publishing stuff and binds to spring, it definitely does what I expect it to do and makes it possible to pass context from the transactional method to the rollback method - which is not available through a traditional try/catch block outside of the transactional method (unless you put your context in the exception itself, which is not very nice).

Body:
To anyone still reading this:

I solved a similar problem with spring events - as suggested by Den Roman in option 3.
Here's the basic idea (scenario is fictional):

Whenever I perform external operations that need to be rolled back together with the transaction, I publish an event inside my @Transactional method using support from spring (org.springframework.context.ApplicationEventPublisher):

@Transactional
public String placeOrder(Order order) {
    String orderId = orderServiceGateway.createOrder(order);
    applicationEventPublisher.publishEvent(new OrderCreatedEvent(orderId));
    workflowService.startWorkflow(orderId);
    return orderId;
}

The event itself can be any object - I created a POJO with details about the remote entity to be deleted.

Then I registered a special event listener that is bound to a transaction phase - in my case to the rollback:

@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void rollBackOrder(OrderCreatedEvent orderCreatedEvent) {
    String orderId = orderCreatedEvent.getOrderId();
    orderServiceGateway.deleteOrder(orderId);
}

Of course, it's recommended to catch & log the exception from rollback operation, not to lose the original exception from the placeOrder() method.

By default these events are synchronous, but they can be made async by additional configuration.

Here's a very good article on this mechanism, including detailed configuration and pitfalls: Transaction Synchronization and Spring Application Events (DZone)

While I don't like the solution 100% because it clutters the business logic with event publishing stuff and binds to spring, it definitely does what I expect it to do and makes it possible to pass context from the transactional method to the rollback method - which is not available through a traditional try/catch block outside of the transactional method (unless you put your context in the exception itself, which is not very nice).


来源: stackexchange

问:
Refresh image URL in ionic 2
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

```<code><ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      <font color="White">{{dt.desc}}</font>
    </ion-card-header>
    <img src= {{dt.name}} >
</ion-card>
</code>```

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps

答:
use *ngIf if it only one image
use *ngFor if it array</p>

ContentLicense: CC BY-SA 3.0

Title: Refresh image URL in ionic 2

Body:
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

<ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      {{dt.desc}}
    </ion-card-header>

</ion-card>

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps


问:
how to see the implemented code of a function of a module in haskell?
I am a newbie to Haskell and I know The Haskell standard library is split into modules, each of them contains functions and types that are somehow related and serve some common purpose. I would like to see the implementation(code) of those library functions.where can I see that ? is there any command in ghci so that I can see the implementation or provide me any resources to learn about modules.
Thank you

答:
Probably the most convenient way to do it, is use Hackage. You can for instance inspect the map function, by clicking Source on the right side of the function signature. This then will show the highlighted code fragment. For instance:

```<code>map :: (a -> b) -> [a] -> [b]
{-# NOINLINE [0] map #-}
  -- We want the RULEs "map" and "map/coerce" to fire first.
  -- map is recursive, so won't inline anyway,
  -- but saying so is more explicit, and silences warnings
map _ []     = []
map f (x:xs) = f x : map f xs
</code>```

You can also use Hoogle to search functions by name or signature, and by clicking the results, you will be redirected to the relevant hackage page.

Body:
Probably the most convenient way to do it, is use Hackage. You can for instance inspect the map function, by clicking Source on the right side of the function signature. This then will show the highlighted code fragment. For instance:

map :: (a -> b) -> [a] -> [b]
{-# NOINLINE [0] map #-}
  -- We want the RULEs "map" and "map/coerce" to fire first.
  -- map is recursive, so won't inline anyway,
  -- but saying so is more explicit, and silences warnings
map _ []     = []
map f (x:xs) = f x : map f xs

You can also use Hoogle to search functions by name or signature, and by clicking the results, you will be redirected to the relevant hackage page.


问:
Not able to redirect back to alexa after successful login from my application
When I click "Enable" for my skill from https://alexa.amazon.com I am redirected to my application login page, after entering email/password and successful authentication I am redirecting user to

https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer

but it gives me JSON response

"{"httpRedirectLocation":"https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer"}"

and page stops, it does not enable and redirect back to alexa giving success message.

I have to manually copy-paste the url which I get in above json response, then only my account is linked.

Can anyone help why I am not directly redirect and getting the successfully linked page? Why I have to manually copy-paste the url?

Thanks in advance.

答:
I am able to redirect now.
I missed "#" after vendorId.

"https://pitangui.amazon.com/spa/skill/account-linking-status.html?vendorId=AAAAAAAAAAAAAA#state=xyz&access_token=XXXXX&token_type=Bearer"

Reference url: https://developer.amazon.com/docs/custom-skills/link-an-alexa-user-with-a-user-in-your-system.html#h3_login_req

Thanks all

Body:
When I click "Enable" for my skill from https://alexa.amazon.com I am redirected to my application login page, after entering email/password and successful authentication I am redirecting user to

<a href="https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer" rel="nofollow noreferrer">https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer

but it gives me JSON response

"{"httpRedirectLocation":"<a href="https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer" rel="nofollow noreferrer">https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer"}"

and page stops, it does not enable and redirect back to alexa giving success message.

I have to manually copy-paste the url which I get in above json response, then only my account is linked.

Can anyone help why I am not directly redirect and getting the successfully linked page? Why I have to manually copy-paste the url?

Thanks in advance.


问:
SQL pivot / VLOOKUP query
I have the following simplified table so each stock code has
multiple warehouses and I want to "pivot" it so I can get
the cost for each warehouse just in 1 line for the stockcode

```<code>Stockcode | Warehouse | Cost
A100        WH          100$
A100        ZZ          200$
</code>```

What I would like to have is the following.
So only 1 stockcode line with the warehouse costs pivoted.

```<code>Stockcode | Cost WH | Cost ZZ
A100        100$      200$
</code>```

I currently did it by exporting it to excell, creating a new sheet and add a new column to the sheet using a VLOOKUP to the main table and add the ZZ cost like that.

How would you turn this around in SQL? I am a bit stuck with understanding how to transform this tabular data in such a way.

答:
However, you could also do that by using simple case expression if you don't want to go pivot or dynamic pivot

```<code>SELECT
          Stockcode ,
          MAX( CASE (Warehouse) WHEN 'WH' THEN Cost END)[Cost WH],
          MAX(CASE (Warehouse) WHEN 'ZZ' THEN Cost END) [Cost ZZ]
FROM <table> GROUP BY Stockcode
</code>```

Dynamic pivot way :

```<code>DECLARE @Col nvarchar(max), @query nvarchar(max)

select @Col = STUFF(
                    (SELECT  ',' +QUOTENAME(Warehouse) FROM <table> FOR XML PATH('')),
                    1, 1, ''

                )

SELECT @query = N'select Stockcode, [WH] as CostWH, [ZZ] as CostZZ
             from (
                select Stockcode, Warehouse, Cost
                 from <table>) p
                    pivot (max(Cost) for Warehouse in ('+@Col+')
                    ) as pvt order by Stockcode;'

                    exec(@query)
</code>```

Result :

```<code>Stockcode  Cost WH  Cost ZZ
A100       100$    200$
</code>```

Title: SQL pivot / VLOOKUP query

Body:
I have the following simplified table so each stock code has
multiple warehouses and I want to "pivot" it so I can get
the cost for each warehouse just in 1 line for the stockcode

Stockcode | Warehouse | Cost
A100        WH          100$
A100        ZZ          200$

What I would like to have is the following.
So only 1 stockcode line with the warehouse costs pivoted.

Stockcode | Cost WH | Cost ZZ
A100        100$      200$

I currently did it by exporting it to excell, creating a new sheet and add a new column to the sheet using a VLOOKUP to the main table and add the ZZ cost like that.

How would you turn this around in SQL? I am a bit stuck with understanding how to transform this tabular data in such a way.

Body:
However, you could also do that by using simple case expression if you don't want to go pivot or dynamic pivot

SELECT
          Stockcode ,
          MAX( CASE (Warehouse) WHEN 'WH' THEN Cost END)[Cost WH],
          MAX(CASE (Warehouse) WHEN 'ZZ' THEN Cost END) [Cost ZZ]
FROM <table> GROUP BY Stockcode

Dynamic pivot way :

DECLARE @Col nvarchar(max), @query nvarchar(max)

select @Col = STUFF(
                    (SELECT  ',' +QUOTENAME(Warehouse) FROM <table> FOR XML PATH('')),
                    1, 1, ''

                )

SELECT @query = N'select Stockcode, [WH] as CostWH, [ZZ] as CostZZ
             from (
                select Stockcode, Warehouse, Cost
                 from <table>) p
                    pivot (max(Cost) for Warehouse in ('+@Col+')
                    ) as pvt order by Stockcode;'

                    exec(@query)

Result :

Stockcode  Cost WH  Cost ZZ
A100       100$    200$


问:
UITableViewCell indentation works only for default cell textLabel
I have got custom UITableViewCell and not able set indentation in cellForRow: atIndexPath:.

```<code>cell.indentationWidth = 10.0
cell.indentationLevel = indexTuples.count //Dynamic
</code>```

However, this works if iOS provided default cell label :

cell.textLabel?.text = "TEST"

Is there any restriction? How can I solve this ?

Note: I have to use Autolayout.

UPDATE:

As per comments, I referred here, I gave a try with below code which doesn't seems to be helpful.

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    self.contentView.layoutMargins.left = CGFloat(self.indentationLevel) * self.indentationWidth
    self.contentView.layoutIfNeeded()
}
</code>```

答:
In short  :  With the help of Autolayout leading constraint, I am able to solve this problem.

First I created a UIView say containerView inside cell contentView & moved all the elements of cell contentView into  containerView. Later I made  IBOutlet of "constainerView leading constraint".

Then in the cellForRow: atIndexPath table view delegate updated its constant as :

```<code>cell.indentViewLeading.constant = 5 + CGFloat(10 * indexTuples.count - 1)  //indexTuples.count gives dynamic values
cell.indentationWidth = 10.0
cell.indentationLevel = indexTuples.count
</code>```

In my UITableViewCell subclass :

```<code>@IBOutlet weak var indentViewLeading: NSLayoutConstraint!
</code>```

Body:
I have got custom UITableViewCell and not able set indentation in cellForRow: atIndexPath:.

cell.indentationWidth = 10.0
cell.indentationLevel = indexTuples.count //Dynamic

However, this works if iOS provided default cell label :

cell.textLabel?.text = "TEST"

Is there any restriction? How can I solve this ?

Note: I have to use Autolayout.

UPDATE:

As per comments, I referred here, I gave a try with below code which doesn't seems to be helpful.

override func layoutSubviews() {
    super.layoutSubviews()
    self.contentView.layoutMargins.left = CGFloat(self.indentationLevel) * self.indentationWidth
    self.contentView.layoutIfNeeded()
}

Body:
In short  :  With the help of Autolayout leading constraint, I am able to solve this problem.

First I created a UIView say containerView inside cell contentView & moved all the elements of cell contentView into  containerView. Later I made  IBOutlet of "constainerView leading constraint".

Then in the cellForRow: atIndexPath table view delegate updated its constant as :

cell.indentViewLeading.constant = 5 + CGFloat(10 * indexTuples.count - 1)  //indexTuples.count gives dynamic values
cell.indentationWidth = 10.0
cell.indentationLevel = indexTuples.count

In my UITableViewCell subclass :

@IBOutlet weak var indentViewLeading: NSLayoutConstraint!


答:
Here's how to do this query using PIVOT:

```<code>select Stockcode, [WH] as CostWH, [ZZ] as CostZZ
from (
  select Stockcode, Warehouse, Cost
  from MyTable
) p
pivot (
  MAX(Cost)
  for Warehouse in ([WH], [ZZ])
) as pvt
order by Stockcode;
</code>```

Test it on SQLFiddle

Title: SQL pivot / VLOOKUP query

Body:
Here's how to do this query using PIVOT:

select Stockcode, [WH] as CostWH, [ZZ] as CostZZ
from (
  select Stockcode, Warehouse, Cost
  from MyTable
) p
pivot (
  MAX(Cost)
  for Warehouse in ([WH], [ZZ])
) as pvt
order by Stockcode;

Test it on SQLFiddle


问:
How i can split array in js?
How i can split string in js for result:

```<code>result = ["post_address", "location", "area"]
</code>```

This is problem? Need help with re

```<code>let re = ???
let arr = "post_address[location][area]".split(re)
</code>```

答:
You can use regexp like this :</p>

```<code>var re = /^(\w*)\[(\w*)\]\[(\w*)\]$/gi;
</code>```

Title: How i can split array in js?

Body:
How i can split string in js for result:

result = ["post_address", "location", "area"]

This is problem? Need help with re

let re = ???
let arr = "post_address[location][area]".split(re)

Body:
You can use regexp like this :

var re = /^(\w*)\[(\w*)\]\[(\w*)\]$/gi;


问:
How to import an individual local html file in angular4
There is a iframe:

```<code><iframe></iframe>
</code>```

another js will add "src=xxx.html" dynamically into the iframe label.
And the xxx.html is a local file,  the web console shows:

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'xxx.html'
</code>```

which directory should I put the individual local html file in, for angular4 project?

答:
Where your xxx.html files?</p>

```<code><iframe name="xxx" src="location your xxx.html files"></iframe>
</code>```

Body:
There is a iframe:

another js will add "src=xxx.html" dynamically into the iframe label.
And the xxx.html is a local file,  the web console shows:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'xxx.html'

which directory should I put the individual local html file in, for angular4 project?

Body:
Where your xxx.html files?

<iframe name="xxx" src="location your xxx.html files"></iframe>


问:
Nodejs async each inside each inside waterfall
I have been banging my head with this for way too long. Perhaps someone in here could help me a bit?

I have an object containing arrays of objects, and I need to do some manipulation for each object in turn before proceeding. Here's simplified example, one of many I've been trying:

```<code>    var demo = {
        one: ['1'],
        two: ['2'],
        three: ['3', '4', '5']
    };

    async.waterfall([
        function(callback) {
            console.log("Step 1");
            setTimeout(function() {
                    console.log("Doing stuff...");
                    callback(null, demo);
            }, 1000);
        },
        function(prevData, callback) {
            console.log("Step 2");
            async.each(prevData, function(obj) {
                async.each(obj, function(item, callback2) {
                    setTimeout(function() {
                            console.log("Doing stuff for item: "+item);
                            callback2(null, demo);
                    }, 1000);
                });
            });
            callback(null, demo);
        }
    ], function(err) {
        if(err) {
            alertify.error("Unhandled exception: "+err);
        } else {
            console.log("All stuff done.");
        }
    });
</code>```

What I am expecting, is:

```<code>Step 1
Doing stuff...
Step 2
Doing stuff for item: 1
Doing stuff for item: 2
Doing stuff for item: 3
Doing stuff for item: 4
Doing stuff for item: 5
All stuff done.
</code>```

But what I get:

```<code>Step 1
Doing stuff...
Step 2
All stuff done.
Doing stuff for item: 1
Doing stuff for item: 2
Doing stuff for item: 3
Doing stuff for item: 4
Doing stuff for item: 5
</code>```

If been trying, probably, every combination of callbacks from each level that I can think of, except the correct one. Must be obvious but I just don't get it...

The sequence itself is right but the function that should manipulate the items does not execute before later.

答:
The problem is in this portion:

```<code>    function(prevData, callback) {
        console.log("Step 2");
        async.each(prevData, function(obj) {
            async.each(obj, function(item, callback2) {
                setTimeout(function() {
                        console.log("Doing stuff for item: "+item);
                        callback2(null, demo);
                }, 1000);
            });
        });
        callback(null, demo);
    }
</code>```

Immediately after the async.each, you call callback(null, demo);. This is before async.each is done. You need to call callback only once the async.each is done. you do this by adding another  callback as a third parameter to the async.each, like so:

```<code>function (prevData, callback) {
    console.log("Step 2");
    async.each(prevData, function (obj) {
        async.each(obj, function (item, callback2) {
            setTimeout(function () {
                console.log("Doing stuff for item: " + item);
                callback2(null, demo);
            }, 1000);
        });
    }, function asyncEachDone(err) {
        callback(err, prevData)
    })
}
</code>```

Body:
I have been banging my head with this for way too long. Perhaps someone in here could help me a bit?

I have an object containing arrays of objects, and I need to do some manipulation for each object in turn before proceeding. Here's simplified example, one of many I've been trying:

    var demo = {
        one: ['1'],
        two: ['2'],
        three: ['3', '4', '5']
    };

    async.waterfall([
        function(callback) {
            console.log("Step 1");
            setTimeout(function() {
                    console.log("Doing stuff...");
                    callback(null, demo);
            }, 1000);
        },
        function(prevData, callback) {
            console.log("Step 2");
            async.each(prevData, function(obj) {
                async.each(obj, function(item, callback2) {
                    setTimeout(function() {
                            console.log("Doing stuff for item: "+item);
                            callback2(null, demo);
                    }, 1000);
                });
            });
            callback(null, demo);
        }
    ], function(err) {
        if(err) {
            alertify.error("Unhandled exception: "+err);
        } else {
            console.log("All stuff done.");
        }
    });

What I am expecting, is:

Step 1
Doing stuff...
Step 2
Doing stuff for item: 1
Doing stuff for item: 2
Doing stuff for item: 3
Doing stuff for item: 4
Doing stuff for item: 5
All stuff done.

But what I get:

Step 1
Doing stuff...
Step 2
All stuff done.
Doing stuff for item: 1
Doing stuff for item: 2
Doing stuff for item: 3
Doing stuff for item: 4
Doing stuff for item: 5

If been trying, probably, every combination of callbacks from each level that I can think of, except the correct one. Must be obvious but I just don't get it...

The sequence itself is right but the function that should manipulate the items does not execute before later.

Body:
The problem is in this portion:

    function(prevData, callback) {
        console.log("Step 2");
        async.each(prevData, function(obj) {
            async.each(obj, function(item, callback2) {
                setTimeout(function() {
                        console.log("Doing stuff for item: "+item);
                        callback2(null, demo);
                }, 1000);
            });
        });
        callback(null, demo);
    }

Immediately after the async.each, you call callback(null, demo);. This is before async.each is done. You need to call callback only once the async.each is done. you do this by adding another  callback as a third parameter to the async.each, like so:

function (prevData, callback) {
    console.log("Step 2");
    async.each(prevData, function (obj) {
        async.each(obj, function (item, callback2) {
            setTimeout(function () {
                console.log("Doing stuff for item: " + item);
                callback2(null, demo);
            }, 1000);
        });
    }, function asyncEachDone(err) {
        callback(err, prevData)
    })
}


问:
openssl -decrypt by Java
all!
I am trying to resolve the issue.

I have bat-file with command:

```<code>openssl smime -decrypt -binary -inform DER -recip [path to certificate] -inkey  [path to private key] <[path to encoded file] >[path to decoded file]
</code>```

I have implement it on Java.

So I need decode file with RSA private key.

First, I tried this way:

```<code>package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Test decrypt
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypded.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            //get private key
            File keyFl = new File(PRIVATE_KEY_FILE);
            Security.addProvider(new BouncyCastleProvider());
            PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            PrivateKey key = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());

            //decrypt file
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            InputStream is = new FileInputStream(ENCRYPTED_FILE);
            OutputStream out = new FileOutputStream(DECRYPTED_FILE);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = cis.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
            cis.close();
            is.close();
            out.close();
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }

        System.out.println("THE END");
    }

}
</code>```

But I get error:

javax.crypto.IllegalBlockSizeException: Data must not be longer than
  128 bytes

Also I tried use this solution. I implemented it that way:

```<code>package javatest;

//some imports...

/**
 * Test decrypt main class
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypded.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            RSA rsa = RSA.getInstance(PRIVATE_KEY_FILE);
            rsa.decrypt(ENCRYPTED_FILE, DECRYPTED_FILE);
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }

        System.out.println("THE END");
    }

}
</code>```

And:

```<code>package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Decrypt class
 *
 * @link http://coding.westreicher.org/?p=23
 * @author a.chernyy
 */
public class RSA {

    /**
     * Singleton class object RSA
     */
    private static volatile RSA instance;

    /**
     * Private key
     */
    private final PrivateKey privateKey;

    /**
     * Cipher
     */
    private final Cipher cipher;

    /**
     * Constructor
     *
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    private RSA(String privateKeyPath) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException {
        //create cipher
        this.cipher = Cipher.getInstance("RSA");

        //get private key
        File keyFl = new File(privateKeyPath);
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
        PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        this.privateKey = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());
    }

    //Static methods
    /**
     * Static method getInstance return single refer on object RSA. If object
     * not exists, it will be created
     *
     * @param privateKeyPath
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws java.io.FileNotFoundException
     * @return RSA
     */
    public static RSA getInstance(String privateKeyPath) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException {
        if (instance == null) {
            synchronized (RSA.class) {
                if (instance == null) {
                    instance = new RSA(privateKeyPath);
                }
            }
        }
        return instance;
    }

    /**
     * Block chipher
     *
     * @param bytes
     * @param mode
     * @return
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException {
        // string initialize 2 buffers.
        // scrambled will hold intermediate results
        byte[] scrambled = new byte[0];

        // toReturn will hold the total result
        byte[] toReturn = new byte[0];
        // if we encrypt we use 100 byte long blocks. Decryption requires 128 byte long blocks (because of RSA)
        int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128;

        // another buffer. this one will hold the bytes that have to be modified in this step
        byte[] buffer = new byte[length];

        for (int i = 0; i < bytes.length; i++) {

            // if we filled our buffer array we have our block ready for de- or encryption
            if ((i > 0) && (i % length == 0)) {
                //execute the operation
                scrambled = cipher.doFinal(buffer);
                // add the result to our total result.
                toReturn = append(toReturn, scrambled);
                // here we calculate the length of the next buffer required
                int newlength = length;

                // if newlength would be longer than remaining bytes in the bytes array we shorten it.
                if (i + length > bytes.length) {
                    newlength = bytes.length - i;
                }
                // clean the buffer array
                buffer = new byte[newlength];
            }
            // copy byte into our buffer.
            buffer[i % length] = bytes[i];
        }

        // this step is needed if we had a trailing buffer. should only happen when encrypting.
        // example: we encrypt 110 bytes. 100 bytes per run means we "forgot" the last 10 bytes. they are in the buffer array
        scrambled = cipher.doFinal(buffer);

        // final step before we can return the modified data.
        toReturn = append(toReturn, scrambled);

        return toReturn;
    }

    /**
     * Concatinate bytes
     *
     * @param prefix
     * @param suffix
     * @return
     */
    private byte[] append(byte[] prefix, byte[] suffix) {
        byte[] toReturn = new byte[prefix.length + suffix.length];
        for (int i = 0; i < prefix.length; i++) {
            toReturn[i] = prefix[i];
        }
        for (int i = 0; i < suffix.length; i++) {
            toReturn[i + prefix.length] = suffix[i];
        }
        return toReturn;
    }

    public void decrypt(String filePath, String fileDecryptPath) throws Exception {
        //Convert file into bytes
        this.cipher.init(Cipher.DECRYPT_MODE, this.privateKey);
        File encryptedFile = new File(filePath);
        FileInputStream isEncryptedFile = new FileInputStream(encryptedFile);
        byte encryptedFileData[] = new byte[(int) encryptedFile.length()];
        isEncryptedFile.read(encryptedFileData);
        byte[] bts = encryptedFileData;

        //decrypt
        byte[] decrypted = blockCipher(bts, Cipher.DECRYPT_MODE);

        //Push decrypted data into file
        //...
    }
}
</code>```

But I got the error:

Decryption error

Can anyone suggest a solution?

答:
I've found the solution for my question!
Thank you all for your advises.

I've found the source.
Thank you very much to author of this source.

I implemented it that way:

package javatest;

import org.bouncycastle.cms.*;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OutputEncryptor;

import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

/**
 *
 * @author kagkarlsson
 * @link https://github.com/kagkarlsson/cms-decrypt-example/blob/master/src/main/java/no/posten/dpost/EncryptAndDecrypt.java
 */
public class EncryptAndDecrypt {
    public static void decrypt(PrivateKey privateKey, File encrypted, File decryptedDestination) throws IOException, CMSException {
        byte[] encryptedData = Files.readAllBytes(encrypted.toPath());

        CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(encryptedData);

        RecipientInformation recInfo = getSingleRecipient(parser);
        Recipient recipient = new JceKeyTransEnvelopedRecipient(privateKey);

        try (InputStream decryptedStream = recInfo.getContentStream(recipient).getContentStream()) {
            Files.copy(decryptedStream, decryptedDestination.toPath());
        }

        System.out.println(String.format("Decrypted '%s' to '%s'", encrypted.getAbsolutePath(), decryptedDestination.getAbsolutePath()));
    }

    public static void encrypt(X509Certificate cert, File source, File destination) throws CertificateEncodingException, CMSException, IOException {
        CMSEnvelopedDataStreamGenerator gen = new CMSEnvelopedDataStreamGenerator();
        gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

        try (FileOutputStream fileStream = new FileOutputStream(destination);
                OutputStream encryptingStream = gen.open(fileStream, encryptor)) {

            byte[] unencryptedContent = Files.readAllBytes(source.toPath());
            encryptingStream.write(unencryptedContent);
        }

        System.out.println(String.format("Encrypted '%s' to '%s'", source.getAbsolutePath(), destination.getAbsolutePath()));
    }

    public static X509Certificate getX509Certificate(File certificate) throws IOException, CertificateException {
        try (InputStream inStream = new FileInputStream(certificate)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            return (X509Certificate) cf.generateCertificate(inStream);
        }
    }

    public static PrivateKey getPrivateKey(File file, String password) throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream(file)) {
            ks.load(fis, password.toCharArray());
        }

        Enumeration<String> aliases = ks.aliases();
        String alias = aliases.nextElement();
        return (PrivateKey) ks.getKey(alias, password.toCharArray());
    }

    private static RecipientInformation getSingleRecipient(CMSEnvelopedDataParser parser) {
        Collection recInfos = parser.getRecipientInfos().getRecipients();
        Iterator recipientIterator = recInfos.iterator();
        if (!recipientIterator.hasNext()) {
            throw new RuntimeException("Could not find recipient");
        }
        return (RecipientInformation) recipientIterator.next();
    }
}```
</div>
</div>
</p>

<p>and</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.security.PrivateKey;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Test decrypt file
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypted.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            //get private key
            File keyFl = new File(PRIVATE_KEY_FILE);
            Security.addProvider(new BouncyCastleProvider());
            PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            PrivateKey privateKey = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());

            //Decrypt file
            File encryptedFile = new File(ENCRYPTED_FILE);
            File decryptedFile = new File(DECRYPTED_FILE);
            Files.deleteIfExists(decryptedFile.toPath());
            Security.addProvider(new BouncyCastleProvider());
            EncryptAndDecrypt.decrypt(privateKey, encryptedFile, decryptedFile);
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }
        System.out.println("THE END");
    }

}</code>```

So, it works! :)

Title: openssl -decrypt by Java

Body:
all!
I am trying to resolve the issue.

I have bat-file with command:

openssl smime -decrypt -binary -inform DER -recip [path to certificate] -inkey  [path to private key] <[path to encoded file] >[path to decoded file]

I have implement it on Java.

So I need decode file with RSA private key.

First, I tried this way:

package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Test decrypt
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypded.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            //get private key
            File keyFl = new File(PRIVATE_KEY_FILE);
            Security.addProvider(new BouncyCastleProvider());
            PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            PrivateKey key = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());

            //decrypt file
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            InputStream is = new FileInputStream(ENCRYPTED_FILE);
            OutputStream out = new FileOutputStream(DECRYPTED_FILE);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = cis.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
            cis.close();
            is.close();
            out.close();
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }

        System.out.println("THE END");
    }

}

But I get error:

javax.crypto.IllegalBlockSizeException: Data must not be longer than
  128 bytes

Also I tried use this solution. I implemented it that way:

package javatest;

//some imports...

/**
 * Test decrypt main class
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypded.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            RSA rsa = RSA.getInstance(PRIVATE_KEY_FILE);
            rsa.decrypt(ENCRYPTED_FILE, DECRYPTED_FILE);
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }

        System.out.println("THE END");
    }

}

And:

package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Decrypt class
 *
 * @link http://coding.westreicher.org/?p=23
 * @author a.chernyy
 */
public class RSA {

    /**
     * Singleton class object RSA
     */
    private static volatile RSA instance;

    /**
     * Private key
     */
    private final PrivateKey privateKey;

    /**
     * Cipher
     */
    private final Cipher cipher;

    /**
     * Constructor
     *
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    private RSA(String privateKeyPath) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException {
        //create cipher
        this.cipher = Cipher.getInstance("RSA");

        //get private key
        File keyFl = new File(privateKeyPath);
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
        PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        this.privateKey = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());
    }

    //Static methods
    /**
     * Static method getInstance return single refer on object RSA. If object
     * not exists, it will be created
     *
     * @param privateKeyPath
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws java.io.FileNotFoundException
     * @return RSA
     */
    public static RSA getInstance(String privateKeyPath) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException {
        if (instance == null) {
            synchronized (RSA.class) {
                if (instance == null) {
                    instance = new RSA(privateKeyPath);
                }
            }
        }
        return instance;
    }

    /**
     * Block chipher
     *
     * @param bytes
     * @param mode
     * @return
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException {
        // string initialize 2 buffers.
        // scrambled will hold intermediate results
        byte[] scrambled = new byte[0];

        // toReturn will hold the total result
        byte[] toReturn = new byte[0];
        // if we encrypt we use 100 byte long blocks. Decryption requires 128 byte long blocks (because of RSA)
        int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128;

        // another buffer. this one will hold the bytes that have to be modified in this step
        byte[] buffer = new byte[length];

        for (int i = 0; i < bytes.length; i++) {

            // if we filled our buffer array we have our block ready for de- or encryption
            if ((i > 0) && (i % length == 0)) {
                //execute the operation
                scrambled = cipher.doFinal(buffer);
                // add the result to our total result.
                toReturn = append(toReturn, scrambled);
                // here we calculate the length of the next buffer required
                int newlength = length;

                // if newlength would be longer than remaining bytes in the bytes array we shorten it.
                if (i + length > bytes.length) {
                    newlength = bytes.length - i;
                }
                // clean the buffer array
                buffer = new byte[newlength];
            }
            // copy byte into our buffer.
            buffer[i % length] = bytes[i];
        }

        // this step is needed if we had a trailing buffer. should only happen when encrypting.
        // example: we encrypt 110 bytes. 100 bytes per run means we "forgot" the last 10 bytes. they are in the buffer array
        scrambled = cipher.doFinal(buffer);

        // final step before we can return the modified data.
        toReturn = append(toReturn, scrambled);

        return toReturn;
    }

    /**
     * Concatinate bytes
     *
     * @param prefix
     * @param suffix
     * @return
     */
    private byte[] append(byte[] prefix, byte[] suffix) {
        byte[] toReturn = new byte[prefix.length + suffix.length];
        for (int i = 0; i < prefix.length; i++) {
            toReturn[i] = prefix[i];
        }
        for (int i = 0; i < suffix.length; i++) {
            toReturn[i + prefix.length] = suffix[i];
        }
        return toReturn;
    }

    public void decrypt(String filePath, String fileDecryptPath) throws Exception {
        //Convert file into bytes
        this.cipher.init(Cipher.DECRYPT_MODE, this.privateKey);
        File encryptedFile = new File(filePath);
        FileInputStream isEncryptedFile = new FileInputStream(encryptedFile);
        byte encryptedFileData[] = new byte[(int) encryptedFile.length()];
        isEncryptedFile.read(encryptedFileData);
        byte[] bts = encryptedFileData;

        //decrypt
        byte[] decrypted = blockCipher(bts, Cipher.DECRYPT_MODE);

        //Push decrypted data into file
        //...
    }
}

But I got the error:

Decryption error

Can anyone suggest a solution?

Body:
I've found the solution for my question!
Thank you all for your advises.

I've found the source.
Thank you very much to author of this source.

I implemented it that way:

package javatest;

import org.bouncycastle.cms.*;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OutputEncryptor;

import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

/**
 *
 * @author kagkarlsson
 * @link https://github.com/kagkarlsson/cms-decrypt-example/blob/master/src/main/java/no/posten/dpost/EncryptAndDecrypt.java
 */
public class EncryptAndDecrypt {
    public static void decrypt(PrivateKey privateKey, File encrypted, File decryptedDestination) throws IOException, CMSException {
        byte[] encryptedData = Files.readAllBytes(encrypted.toPath());

        CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(encryptedData);

        RecipientInformation recInfo = getSingleRecipient(parser);
        Recipient recipient = new JceKeyTransEnvelopedRecipient(privateKey);

        try (InputStream decryptedStream = recInfo.getContentStream(recipient).getContentStream()) {
            Files.copy(decryptedStream, decryptedDestination.toPath());
        }

        System.out.println(String.format("Decrypted '%s' to '%s'", encrypted.getAbsolutePath(), decryptedDestination.getAbsolutePath()));
    }

    public static void encrypt(X509Certificate cert, File source, File destination) throws CertificateEncodingException, CMSException, IOException {
        CMSEnvelopedDataStreamGenerator gen = new CMSEnvelopedDataStreamGenerator();
        gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

        try (FileOutputStream fileStream = new FileOutputStream(destination);
                OutputStream encryptingStream = gen.open(fileStream, encryptor)) {

            byte[] unencryptedContent = Files.readAllBytes(source.toPath());
            encryptingStream.write(unencryptedContent);
        }

        System.out.println(String.format("Encrypted '%s' to '%s'", source.getAbsolutePath(), destination.getAbsolutePath()));
    }

    public static X509Certificate getX509Certificate(File certificate) throws IOException, CertificateException {
        try (InputStream inStream = new FileInputStream(certificate)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            return (X509Certificate) cf.generateCertificate(inStream);
        }
    }

    public static PrivateKey getPrivateKey(File file, String password) throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream(file)) {
            ks.load(fis, password.toCharArray());
        }

        Enumeration<String> aliases = ks.aliases();
        String alias = aliases.nextElement();
        return (PrivateKey) ks.getKey(alias, password.toCharArray());
    }

    private static RecipientInformation getSingleRecipient(CMSEnvelopedDataParser parser) {
        Collection recInfos = parser.getRecipientInfos().getRecipients();
        Iterator recipientIterator = recInfos.iterator();
        if (!recipientIterator.hasNext()) {
            throw new RuntimeException("Could not find recipient");
        }
        return (RecipientInformation) recipientIterator.next();
    }
}

and

package javatest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.security.PrivateKey;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

/**
 * Test decrypt file
 *
 * @author a.chernyy
 */
public class JavaTest {

    /**
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * String to hold the path to the keys' dir.
     */
    public static final String KEYS_DIR = "D:" + File.separator + "keystore" + File.separator;

    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = KEYS_DIR + "priv.key";

    /**
     * String to hold name of the public key file.
     */
    public static final String CERT_FILE = KEYS_DIR + "cert.cer";

    /**
     * String to hold name of the encrypted file.
     */
    public static final String ENCRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "encrypted.xml";

    /**
     * String to hold name of the decrypted file.
     */
    public static final String DECRYPTED_FILE = "D:" + File.separator + "Temp" + File.separator + "decrypted.xml";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            //get private key
            File keyFl = new File(PRIVATE_KEY_FILE);
            Security.addProvider(new BouncyCastleProvider());
            PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFl)));
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            PrivateKey privateKey = converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());

            //Decrypt file
            File encryptedFile = new File(ENCRYPTED_FILE);
            File decryptedFile = new File(DECRYPTED_FILE);
            Files.deleteIfExists(decryptedFile.toPath());
            Security.addProvider(new BouncyCastleProvider());
            EncryptAndDecrypt.decrypt(privateKey, encryptedFile, decryptedFile);
        } catch (Exception e) {
            System.out.println("It's a pity...");
            System.err.println(e.getMessage());
        }
        System.out.println("THE END");
    }

}

So, it works! :)


问:
Hibernate manual and auto-generated primary key
I am having a requirement where if the user enters value for the primary key, then I need to use that when creating an entity and if in case the user does not provide value, the primary key needs to be auto-generated like R00001, R0002 etc.I would like to know how I could achieve this and any guidance on that</p>

答:
Try to take advantage of the IdentifierGenerator interface and define an implementation of your own.

```<code>public class MyEntityIdGenerator implements IdentifierGenerator{

    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {
         MyEntity entity = (MyEntity)object;

         if(entity.getId()==null){
            Connection con = session.connection();
            // retrieve next sequence val from database for example

            return nextSeqValue;
         }
    }
}
</code>```

Then add appropriate annotations on the id field in your entity:

```<code>@Id
@GenericGenerator(name="myCustomGen", strategy="com.example.MyEntityGenerator")
@GeneratedValue(generator="myCustomGen")
</code>```

Body:
Try to take advantage of the IdentifierGenerator interface and define an implementation of your own.

public class MyEntityIdGenerator implements IdentifierGenerator{

    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {
         MyEntity entity = (MyEntity)object;

         if(entity.getId()==null){
            Connection con = session.connection();
            // retrieve next sequence val from database for example

            return nextSeqValue;
         }
    }
}

Then add appropriate annotations on the id field in your entity:

@Id
@GenericGenerator(name="myCustomGen", strategy="com.example.MyEntityGenerator")
@GeneratedValue(generator="myCustomGen")


问:
In Keras, how do imagenet-pretrained models handled input size different from original 224x224 input size?
Since pre-trained models are trained on ImageNet images with a particular width and height, how does Keras model (e.g. ResNet50) allow for a different input_size?

I also would love to know where the magic number '197' comes from:

input_shape: optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 197. E.g. (200, 200, 3) would be one valid value.

Source

答:
to start you have to focus on the include_top part when you specify it as false, you chose to not include the fully connected layers and have more freedom on how to work with the model given you the possibility to retrain (or just readjust the weights) of the model.

and when you look at a deep learning model at this size like the resnet50,
you will notice that nearer the layer is to the input of the model more abstract it is, at each block of the layer it will capture feature like contours, and the increase of the size of the image wouldn't affect much the result from this part of the network.

the most important layer will sit at the end (or what keras refers as top here) of the model where you should concentrate the training, that is why is possible to change the input size when using include_top = false, so you can readjust the FC layers to the proper size.

about the magic number, I'm not really sure but I would guess that is because the model is a big one and each time it does a pooling it reduces the image size and the 197 would be the limit to not arrive with a size 0 at the end.

if you look at the page you sent at the Fine-tune InceptionV3 on a new set of classes you will see a good example of it where it retrains just the last 2 blocks from the inception model but leave the top ones untouched.

ContentLicense: CC BY-SA 4.0


问:
ERROR: LoadError: Tensorflow error: Status: Incompatible shapes: [16] vs. [16,9]
Implementing a model adapted from multilayer CNN Tutorial

I am learning TensorFlow from the example at: MNIST Tutorial - Julia.jl

unlike their tutorial, I am using my own custom images(32 X 32 (RGB) ) format asimular to cifar-10. Each row in the csv is 3073 columns the last one being the label.

And I have 300 rows out of which I used array slicing to select the first 240 rows for training and the remaining for testing. So in a nut shell I have 4 arrays:

images_train = 240 X 3072 labels_train = 240 X 1 images_test = 60 X 3072 labels_test = 60 X 1 .

When I try training the network I get error,

Incompatible shapes: [16] vs. [16,9]

Actually I have nine classes with 240 training set and 60 images for testing.

The code is:

```<code>using TensorFlow
using Distributions
include("loader.jl")

session = Session(Graph())
function weight_variable(shape)
    initial = map(Float32, rand(Normal(0, .001), shape...))
    return Variable(initial)
end

function bias_variable(shape)
    initial = fill(Float32(.1), shape...)
    return Variable(initial)
end

function conv2d(x, W)
    nn.conv2d(x, W, [1, 1, 1, 1], "SAME")

end

function max_pool_2x2(x)
    nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], "SAME")
end

x = placeholder(Float32)
y_ = placeholder(Float32)

W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])

x_image = x #reshape(x, [-1, 32, 32, 3])

h_conv1 = nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([8*8*64, 1024]) #
b_fc1 = bias_variable([1024])

h_pool2_flat = reshape(h_pool2, [-1, 8*8*64])
h_fc1 = nn.relu(h_pool2_flat * W_fc1 + b_fc1)

keep_prob = placeholder(Float32)
h_fc1_drop = nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 9])
b_fc2 = bias_variable([9])

y_conv = nn.softmax(h_fc1_drop * W_fc2 + b_fc2)

cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), axis=[2]))

train_step = train.minimize(train.AdamOptimizer(1e-4), cross_entropy)

correct_prediction = indmax(y_conv, 2) .== indmax(y_, 2)

accuracy = reduce_mean(cast(correct_prediction, Float32))

run(session, global_variables_initializer())

for i in 1:100
    images_train,labels_train = batching(16) # randomly generate batches from training dataset (16,32,32,3)
    if i%4 == 1
        train_accuracy = run(session, accuracy, Dict(x=>images_train, y_=>labels_train, keep_prob=>1.0))
        info("step $i, training accuracy $train_accuracy")
    end
    run(session, train_step, Dict(x=>images_train, y_=>labels_train, keep_prob=>.5))
end

images_test, labels_test = testloader() # (60, 33,32,3), (60,) Arrays

test_accuracy = run(session, accuracy, Dict(x=>images_test, y_=>labels_test, keep_prob=>1.0))
info("test accuracy $test_accuracy")
</code>```

答:
Applying

reshape(A,(16,1))

Solved the issue with the incompatibility.

Body:
Implementing a model adapted from multilayer CNN Tutorial

I am learning TensorFlow from the example at: MNIST Tutorial - Julia.jl

unlike their tutorial, I am using my own custom images(32 X 32 (RGB) ) format asimular to cifar-10. Each row in the csv is 3073 columns the last one being the label.

And I have 300 rows out of which I used array slicing to select the first 240 rows for training and the remaining for testing. So in a nut shell I have 4 arrays:

images_train = 240 X 3072 labels_train = 240 X 1 images_test = 60 X 3072 labels_test = 60 X 1 .

When I try training the network I get error,

Incompatible shapes: [16] vs. [16,9]

Actually I have nine classes with 240 training set and 60 images for testing.

The code is:

using TensorFlow
using Distributions
include("loader.jl")

session = Session(Graph())
function weight_variable(shape)
    initial = map(Float32, rand(Normal(0, .001), shape...))
    return Variable(initial)
end

function bias_variable(shape)
    initial = fill(Float32(.1), shape...)
    return Variable(initial)
end

function conv2d(x, W)
    nn.conv2d(x, W, [1, 1, 1, 1], "SAME")

end

function max_pool_2x2(x)
    nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], "SAME")
end

x = placeholder(Float32)
y_ = placeholder(Float32)

W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])

x_image = x #reshape(x, [-1, 32, 32, 3])

h_conv1 = nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([8*8*64, 1024]) #
b_fc1 = bias_variable([1024])

h_pool2_flat = reshape(h_pool2, [-1, 8*8*64])
h_fc1 = nn.relu(h_pool2_flat * W_fc1 + b_fc1)

keep_prob = placeholder(Float32)
h_fc1_drop = nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 9])
b_fc2 = bias_variable([9])

y_conv = nn.softmax(h_fc1_drop * W_fc2 + b_fc2)

cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), axis=[2]))

train_step = train.minimize(train.AdamOptimizer(1e-4), cross_entropy)

correct_prediction = indmax(y_conv, 2) .== indmax(y_, 2)

accuracy = reduce_mean(cast(correct_prediction, Float32))

run(session, global_variables_initializer())

for i in 1:100
    images_train,labels_train = batching(16) # randomly generate batches from training dataset (16,32,32,3)
    if i%4 == 1
        train_accuracy = run(session, accuracy, Dict(x=>images_train, y_=>labels_train, keep_prob=>1.0))
        info("step $i, training accuracy $train_accuracy")
    end
    run(session, train_step, Dict(x=>images_train, y_=>labels_train, keep_prob=>.5))
end

images_test, labels_test = testloader() # (60, 33,32,3), (60,) Arrays

test_accuracy = run(session, accuracy, Dict(x=>images_test, y_=>labels_test, keep_prob=>1.0))
info("test accuracy $test_accuracy")


问:
removing black dots from image using OpenCV and Python
I am trying to compare two images and need to pre-process/clean one of them which is a scanned copy before comparing with a digital copy.
Scanned copy /
Digital copy

I ran this code on the scanned image and got an output which has numerous black dots. Not sure how to clean these up so that I can compare with the digital copy

```<code>img = cv2.multiply(img, 1.2)
kernel = np.ones((1, 1), np.uint8)
img = cv2.erode(img, kernel, iterations=1)
kernel1 = np.zeros( (9,9), np.float32)
kernel1[4,4] = 2.0
boxFilter = np.ones( (9,9), np.float32) / 81.0
kernel1 = kernel1 - boxFilter
img = cv2.filter2D(img, -1, kernel1)
</code>```

below is the output I got

答:
Yes. @Andrey method is the right way of solving the problem.
I have tried removing the high frequency dots in the frequency domain and here is an example of how it will look like if done correctly

Original Image in grayscale.

After running FFT on the image

Removing all high frequency noise. Of course this is done manually by drawing a black circle around the noise source. You can design your program to detect local bright spot and remove them cleanly.

Here is the final result after inverse FFT of the above frequency image. Some what degraded due to the crude way of me removing the noise but it should give you a rough idea of how it can be done.

Only the area around the dots will be affected by this process, leaving all other pattern in their original form.

Body:
I am trying to compare two images and need to pre-process/clean one of them which is a scanned copy before comparing with a digital copy.
Scanned copy /
Digital copy

I ran this code on the scanned image and got an output which has numerous black dots. Not sure how to clean these up so that I can compare with the digital copy

img = cv2.multiply(img, 1.2)
kernel = np.ones((1, 1), np.uint8)
img = cv2.erode(img, kernel, iterations=1)
kernel1 = np.zeros( (9,9), np.float32)
kernel1[4,4] = 2.0
boxFilter = np.ones( (9,9), np.float32) / 81.0
kernel1 = kernel1 - boxFilter
img = cv2.filter2D(img, -1, kernel1)

below is the output I got


问:
jQuery attr() method to change a class name
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}</code>```

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

```

答:
You can either use attr or prop depending on your jQuery version:

```<code>$(selector).attr('class', 'className'); // jQuery < 1.6
$(selector).prop('class', 'className'); // jQuery >= 1.6
</code>```

To add a class to existing classes

```<code>var classes = $(selector).prop('class');
$(selector).prop('class', classes + ' className');
</code>```

To remove a class

```<code>var classes = $(selector).prop('class').replace('notNeededClass', '');
$(selector).prop('class', classes);
</code>```

but jQuery offers classManipulation directly

```<code>$(selector).addClass('className');
$(selector).removeClass('className');
$(selector).toggleClass('className');
</code>```

Body:
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();

.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

Body:
You can either use attr or prop depending on your jQuery version:

$(selector).attr('class', 'className'); // jQuery < 1.6
$(selector).prop('class', 'className'); // jQuery >= 1.6

To add a class to existing classes

var classes = $(selector).prop('class');
$(selector).prop('class', classes + ' className');

To remove a class

var classes = $(selector).prop('class').replace('notNeededClass', '');
$(selector).prop('class', classes);

but jQuery offers classManipulation directly

$(selector).addClass('className');
$(selector).removeClass('className');
$(selector).toggleClass('className');


问:
Can I cancel just the array job in slurm?
I have a bunch of jobs running as an array job in slurm:

```<code>123_[1-500] PD my_job 0:00 me
123_2       R  my_job 9:99 me
123_3       R  my_job 9:99 me
123_4       R  my_job 9:99 me
123_5       R  my_job 9:99 me
...
</code>```

As I read the man page on scancel, it seems to indicate that if I execute scancel 123 it will stop everything

Am I wrong, or is there another way to stop just the array job? I want the already running jobs to finish, I just don't want any more jobs created by 123, and I really don't want to have to figure out which jobs need to be re-run if I accidentally kill them mid-way

答:
You can issue scancel with the additional --state tag:

```<code> scancel --state=PENDING 123
</code>```

or, in short:

```<code> scancel -t PD 123
</code>```

That will only cancel jobs of the 123 array that are pending and will leave the running the already started ones.

Body:
I have a bunch of jobs running as an array job in slurm:

123_[1-500] PD my_job 0:00 me
123_2       R  my_job 9:99 me
123_3       R  my_job 9:99 me
123_4       R  my_job 9:99 me
123_5       R  my_job 9:99 me
...

As I read the man page on scancel, it seems to indicate that if I execute scancel 123 it will stop everything

Am I wrong, or is there another way to stop just the array job? I want the already running jobs to finish, I just don't want any more jobs created by 123, and I really don't want to have to figure out which jobs need to be re-run if I accidentally kill them mid-way

Body:
You can issue scancel with the additional --state tag:

 scancel --state=PENDING 123

or, in short:

 scancel -t PD 123

That will only cancel jobs of the 123 array that are pending and will leave the running the already started ones.


问:
android.graphics.drawable.TransitionDrawable cannot be cast to com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable
I have loaded remote image to ImageView using below code

```<code>Glide.with(context)
                .load(imageUrl)
                .placeholder(R.drawable.placeholderImage)
                .into(holder.wallPaperImageView);
</code>```

Now I want to get the bitmap from imageview

```<code>  Bitmap bitmap = ((GlideBitmapDrawable)holder.wallPaperImageView.getDrawable()).getBitmap();
</code>```

but above line of code throws below exception:

java.lang.ClassCastException:
  android.graphics.drawable.TransitionDrawable cannot be cast to
  com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable

How to resolve this?

答:
If you use Glide v4

```<code> private BaseTarget target = new BaseTarget<BitmapDrawable>() {
        @Override
        public void onResourceReady(BitmapDrawable bitmap, Transition<? super BitmapDrawable> transition) {
            //here is your integration by ex: activityReference.get().toolbar.setNavigationIcon(bitmap);
        }

        @Override
        public void getSize(SizeReadyCallback cb) {
            cb.onSizeReady(100, 100);
        }

        @Override
        public void removeCallback(SizeReadyCallback cb) {}
    };
</code>```

and after

```<code>Glide.with(activityReference.get().getApplicationContext())
                            .load(url of image)
                            .apply(new RequestOptions()
                                    .placeholder(R.mipmap.img)
                                    .error(R.mipmap.img)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL))
                            .apply(circleCropTransform())
                            .into(target);
</code>```

if you have warning 'Unchecked method ...' add before method @SuppressWarnings("unchecked")

Body:
I have loaded remote image to ImageView using below code

Glide.with(context)
                .load(imageUrl)
                .placeholder(R.drawable.placeholderImage)
                .into(holder.wallPaperImageView);

Now I want to get the bitmap from imageview

  Bitmap bitmap = ((GlideBitmapDrawable)holder.wallPaperImageView.getDrawable()).getBitmap();

but above line of code throws below exception:

java.lang.ClassCastException:
  android.graphics.drawable.TransitionDrawable cannot be cast to
  com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable

How to resolve this?

Body:
If you use Glide v4

 private BaseTarget target = new BaseTarget<BitmapDrawable>() {
        @Override
        public void onResourceReady(BitmapDrawable bitmap, Transition<? super BitmapDrawable> transition) {
            //here is your integration by ex: activityReference.get().toolbar.setNavigationIcon(bitmap);
        }

        @Override
        public void getSize(SizeReadyCallback cb) {
            cb.onSizeReady(100, 100);
        }

        @Override
        public void removeCallback(SizeReadyCallback cb) {}
    };

and after

Glide.with(activityReference.get().getApplicationContext())
                            .load(url of image)
                            .apply(new RequestOptions()
                                    .placeholder(R.mipmap.img)
                                    .error(R.mipmap.img)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL))
                            .apply(circleCropTransform())
                            .into(target);

if you have warning 'Unchecked method ...' add before method @SuppressWarnings("unchecked")


问:
positioning works in ff,chrome but not in ie7
I have some divs which i positioned with

```<code>position:absolute;
width:100px;
margin:-20px 420px;
</code>```

same like this another one also...
the problem is it is looking fine in chrome and firefox ,but in ie7 those divs are being moved away.
how to set it to look perfect in all browsers??thanks
edited:

```
.button {
  display:block;
  position:absolute;
  width:200px;
  height:50px;
  background:url(../images/portfolio.gif) no-repeat 0 -49px;
  margin:-50px 420px;
}
.button a {
  display:block;
  position:absolute;
  width:100%;
  height:100%;
  background:url(../images/portfolio.gif) no-repeat 0 0;
  text-indent:-9999px;
}
.button a:hover {
  background-position: 0 50px;
}

.button1 {
  display:block;
  position:absolute;
  width:200px;
  height:50px;
  background:url(../images/design-brief.gif) no-repeat 0 -49px;
  margin:-20px 420px;
}
.button1 a {
  display:block;
  position:absolute;
  width:100%;
  height:100%;
  background:url(../images/design-brief.gif) no-repeat 0 0;
  text-indent:-9999px;
}
.button1 a:hover {
  background-position: 0 50px;
}
```

these two buttons,button and button1 are inside this div along with some text

```
.cont
{
position:relative;
width:1400px;
height:500px;

}
```

答: Agree with Matt Asbury... If u r using positions then there is no use of margins. and one more thing, u r using position absolute for buttons. in that case don't use position for its child unless and until u want to position its child as well. If u can provide html then it will be easy to understand the code and help.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have some divs which i positioned with

position:absolute;
width:100px;
margin:-20px 420px;

same like this another one also...
the problem is it is looking fine in chrome and firefox ,but in ie7 those divs are being moved away.
how to set it to look perfect in all browsers??thanks
edited:

.button {
  display:block;
  position:absolute;
  width:200px;
  height:50px;
  background:url(../images/portfolio.gif) no-repeat 0 -49px;
  margin:-50px 420px;
}
.button a {
  display:block;
  position:absolute;
  width:100%;
  height:100%;
  background:url(../images/portfolio.gif) no-repeat 0 0;
  text-indent:-9999px;
}
.button a:hover {
  background-position: 0 50px;
}

.button1 {
  display:block;
  position:absolute;
  width:200px;
  height:50px;
  background:url(../images/design-brief.gif) no-repeat 0 -49px;
  margin:-20px 420px;
}
.button1 a {
  display:block;
  position:absolute;
  width:100%;
  height:100%;
  background:url(../images/design-brief.gif) no-repeat 0 0;
  text-indent:-9999px;
}
.button1 a:hover {
  background-position: 0 50px;
}

these two buttons,button and button1 are inside this div along with some text

.cont
{
position:relative;
width:1400px;
height:500px;

}


问:
Set for ruby deploy public key path with homepath
To solve the connection problems in capistrano with the public key i add to deploy.rb

```<code>set :ssh_options, {
  auth_methods: ["publickey"],
  keys: ['c:/users/test/.ssh/id_rsa']
}
</code>```

this works, but i want to make this path with the homepath instead of c:/users/test. I try to add %USERHOME% but so he cant find the key.

How can i say to ruby to use there the homepath of the system?

答:
Can you try something like this, on OS:

export KEY_PATH=${HOME}/.ssh/id_rsa

On ruby code:

```<code>set :ssh_options, {
  auth_methods: ["publickey"],
  keys: ENV['KEY_PATH']
}
</code>```

Body:
To solve the connection problems in capistrano with the public key i add to deploy.rb

set :ssh_options, {
  auth_methods: ["publickey"],
  keys: ['c:/users/test/.ssh/id_rsa']
}

this works, but i want to make this path with the homepath instead of c:/users/test. I try to add %USERHOME% but so he cant find the key.

How can i say to ruby to use there the homepath of the system?

Body:
Can you try something like this, on OS:

export KEY_PATH=${HOME}/.ssh/id_rsa

On ruby code:

set :ssh_options, {
  auth_methods: ["publickey"],
  keys: ENV['KEY_PATH']
}


问:
How to Create Custom Cursor to Grab Colors of ImageView
example of image of color grab application

Hello, I'd like to create an Android application to identify colors from an image. I'd like to use a custom cursor or a visual touch to let the user know the last touched area or simply to let the user know the picked color when they touch around the image. In other words, I'd like to create something like a magnifying glass cursor for the image. I couldn't think of a right name to put it so to make my explanation clear, please check the attached image : https://i.stack.imgur.com/iOA1p.jpg. Thank you

答:
have a look on this class, This is a custom ImageView. get your coordinate in onTouch() and from that coordinate you can get pixel color. feel free to Modify as per your use. </p>

```<code>    <com.xbadal.views.MyImageView
            android:id="@+id/signature_canvas"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:visibility="gone"
            tools:visibility="visible" />

public class MyImageView extends android.support.v7.widget.AppCompatImageView {
private final String TAG = getClass().getName();
private final float TOLERANCE = 20;
private final int defaultWidth = 30;

private Bitmap mBitmap;
private Canvas mCanvas;
private Context context;

private Paint paint;
private Point point;

private float mLastTouchX;
private float mLastTouchY;
private int imageX;
private int imageY;

//Parameter Constructor
public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

// override onSizeChanged
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    Log.d(TAG, "onSizeChanged: " + h + "-" + w);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

//Overriding onTouch
@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    //Invert Matrix to get proper coordinate
    float[] eventXY = new float[]{x, y};
    Matrix invertMatrix = new Matrix();
    getImageMatrix().invert(invertMatrix);
    invertMatrix.mapPoints(eventXY);
    imageX = (int) eventXY[0];
    imageY = (int) eventXY[1];

    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mLastTouchX = x;
            mLastTouchY = y;
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            final float dx = x - mLastTouchX;
            final float dy = y - mLastTouchY;

            if (Math.abs(dx) >= TOLERANCE || Math.abs(dy) >= TOLERANCE) {
                mLastTouchX = x;
                mLastTouchY = y;
                invalidate();
            }
            break;
        case MotionEvent.ACTION_UP:
            mLastTouchX = x;
            mLastTouchY = y;
            invalidate();
            break;
    }
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawShape(canvas, mLastTouchX, mLastTouchY, defaultWidth);
}

//this method will detemine which shape to be drawn on the basis of ShapeId
public void drawShape(Canvas canvas, float x, float y, int width) {
    paint = new Paint();
    point = new Point();
    point.set((int) x, (int) y);

    Bitmap bitmap = ((BitmapDrawable) this.getDrawable()).getBitmap();
    if (x >= 0 && x < bitmap.getWidth() && y >= 0 && y < bitmap.getHeight()) {
        if (imageX >= 0 && imageX < bitmap.getWidth() && imageY >= 0 && imageY < bitmap.getHeight()) {
            int pixel = (bitmap.getPixel(imageX, imageY));
            int redValue = Color.red(pixel);
            int blueValue = Color.blue(pixel);
            int greenValue = Color.green(pixel);
            int alpha = Color.alpha(pixel);

        }
    }
}
</code>```

<p>}</p>

Body:
have a look on this class, This is a custom ImageView. get your coordinate in onTouch() and from that coordinate you can get pixel color. feel free to Modify as per your use.

    <com.xbadal.views.MyImageView
            android:id="@+id/signature_canvas"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:visibility="gone"
            tools:visibility="visible" />

public class MyImageView extends android.support.v7.widget.AppCompatImageView {
private final String TAG = getClass().getName();
private final float TOLERANCE = 20;
private final int defaultWidth = 30;

private Bitmap mBitmap;
private Canvas mCanvas;
private Context context;

private Paint paint;
private Point point;

private float mLastTouchX;
private float mLastTouchY;
private int imageX;
private int imageY;

//Parameter Constructor
public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

// override onSizeChanged
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    Log.d(TAG, "onSizeChanged: " + h + "-" + w);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

//Overriding onTouch
@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    //Invert Matrix to get proper coordinate
    float[] eventXY = new float[]{x, y};
    Matrix invertMatrix = new Matrix();
    getImageMatrix().invert(invertMatrix);
    invertMatrix.mapPoints(eventXY);
    imageX = (int) eventXY[0];
    imageY = (int) eventXY[1];

    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mLastTouchX = x;
            mLastTouchY = y;
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            final float dx = x - mLastTouchX;
            final float dy = y - mLastTouchY;

            if (Math.abs(dx) >= TOLERANCE || Math.abs(dy) >= TOLERANCE) {
                mLastTouchX = x;
                mLastTouchY = y;
                invalidate();
            }
            break;
        case MotionEvent.ACTION_UP:
            mLastTouchX = x;
            mLastTouchY = y;
            invalidate();
            break;
    }
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawShape(canvas, mLastTouchX, mLastTouchY, defaultWidth);
}

//this method will detemine which shape to be drawn on the basis of ShapeId
public void drawShape(Canvas canvas, float x, float y, int width) {
    paint = new Paint();
    point = new Point();
    point.set((int) x, (int) y);

    Bitmap bitmap = ((BitmapDrawable) this.getDrawable()).getBitmap();
    if (x >= 0 && x < bitmap.getWidth() && y >= 0 && y < bitmap.getHeight()) {
        if (imageX >= 0 && imageX < bitmap.getWidth() && imageY >= 0 && imageY < bitmap.getHeight()) {
            int pixel = (bitmap.getPixel(imageX, imageY));
            int redValue = Color.red(pixel);
            int blueValue = Color.blue(pixel);
            int greenValue = Color.green(pixel);
            int alpha = Color.alpha(pixel);

        }
    }
}

}


问:
Java 8 Stream extract datas from Map
I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result.  I'm quite new with the Stream API and I don't understand what I have to do.  I tried with

```<code>public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(...);
}
</code>```

What do I have to put in the Collectors.toMap ?

答:
You simply have to pass the functions that map an element of your Stream to  both the key and the value of the output Map.

In your case it's simply the key and the value of the Map.Entry elements of the Stream.

```<code>public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
}
</code>```

Title: Java 8 Stream extract datas from Map

Body:
I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result.  I'm quite new with the Stream API and I don't understand what I have to do.  I tried with

public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(...);
}

What do I have to put in the Collectors.toMap ?

Body:
You simply have to pass the functions that map an element of your Stream to  both the key and the value of the output Map.

In your case it's simply the key and the value of the Map.Entry elements of the Stream.

public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
}