问:
Is there any way to assign an index of my choice to array collection in flex?
I want to give an array index to array collection let say 205 when it is started is it possible to do so in flex or any alternate of this.

actually I need to index the objects with a specific no, in 2D array collection

say

```<code>205 a c d g f d
268 s g h g f f
805 d g h h f f d
</code>```

where integers are indexes and alphabets are object referenced by these integers

答:
ArrayCollections are wrappers for Arrays (with more functionality + binding + all sorts of awesome [if one can use awesome as a noun]).

The Array class is not as "associative" as is the Dictionary class.  So, you could either use a dictionary, which is probably what you're really looking for.  Or you could extend ArrayCollection (which extends ListCollectionView which extends Proxy -- which was @BrianBenisio's suggestion).  So it really depends on your project, what you want to accomplish, if you need binding, and how much time you have.

You gave the example by detailing a 2D collection:

```<code>205 a c d g f d
268 s g h g f f
805 d g h h f f d
</code>```

so I'm going to guess that you are dealing with a datasource that is xml based (or at least based on something similar to SimpleDB, with rows that don't have static columns).  So if it were me, I'd stick with an Array and build an internal "ArrayUtils" class that acts as a means to your end.  Though, if you're using the latest version of Flex, you may want to think about typing your array and going down the path of using the Vector class.  With a customized typed vector, you'll find better performance and customizable functionality that you'd otherwise be missing.

Good luck in any case.

rock on,
Jeremy

Body:
I want to give an array index to array collection let say 205 when it is started is it possible to do so in flex or any alternate of this.

actually I need to index the objects with a specific no, in 2D array collection

say

205 a c d g f d
268 s g h g f f
805 d g h h f f d

where integers are indexes and alphabets are object referenced by these integers

Body:
ArrayCollections are wrappers for Arrays (with more functionality + binding + all sorts of awesome [if one can use awesome as a noun]).

The Array class is not as "associative" as is the Dictionary class.  So, you could either use a dictionary, which is probably what you're really looking for.  Or you could extend ArrayCollection (which extends ListCollectionView which extends Proxy -- which was @BrianBenisio's suggestion).  So it really depends on your project, what you want to accomplish, if you need binding, and how much time you have.

You gave the example by detailing a 2D collection:

205 a c d g f d
268 s g h g f f
805 d g h h f f d

so I'm going to guess that you are dealing with a datasource that is xml based (or at least based on something similar to SimpleDB, with rows that don't have static columns).  So if it were me, I'd stick with an Array and build an internal "ArrayUtils" class that acts as a means to your end.  Though, if you're using the latest version of Flex, you may want to think about typing your array and going down the path of using the Vector class.  With a customized typed vector, you'll find better performance and customizable functionality that you'd otherwise be missing.

Good luck in any case.

rock on,
Jeremy


来源: stackexchange

问:
How can I fail a TestNG test within a listener
Is there a way to, from within an ITestListener implementation, actually fail a test that has already "passed" successfully?

My use case is this: I run all of the tests in my suite and then, at the end of the suite, perform some additional actions. As a result of these actions, I would like for tests that previously "passed" to now be marked as failures.

From within my listener (which is extends TestListenerAdapter), I am calling:

```<code>result.setStatus(ITestResult.FAILURE);
result.setThrowable(t);
</code>```

on some ITestResult objects. Elsewhere in the listener, I have overridden onFinish like so:

```<code>@Override
public void onTestFailure(final ITestResult result) {
    super.onTestFailure(result);

    // TODO: This is updating the state of the test, but NOT causing it to fail
    Reporter.setCurrentTestResult(result);
}
</code>```

When I fail the test, the callback is being executed. The Throwable is added to the test result. Everything happens as I expected it to.

However, both the generated report and the build output are incorrect:

```<code>[testng] ===============================================
[testng] <redacted>Tests
[testng] Total tests run: 51, Failures: 0, Skips: 0
[testng] ===============================================
</code>```

Despite the fact that 3 of these test results are being updated as failures:

Any ideas?

答:
I had success with changing the status from FAILURE to SKIP with this approach using IInvokedMethodListener.

The afterInvocation method, where the status can be changed, will not be invoked after the whole test suite completes but after each test method.

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to, from within an ITestListener implementation, actually fail a test that has already "passed" successfully?

My use case is this: I run all of the tests in my suite and then, at the end of the suite, perform some additional actions. As a result of these actions, I would like for tests that previously "passed" to now be marked as failures.

From within my listener (which is extends TestListenerAdapter), I am calling:

result.setStatus(ITestResult.FAILURE);
result.setThrowable(t);

on some ITestResult objects. Elsewhere in the listener, I have overridden onFinish like so:

@Override
public void onTestFailure(final ITestResult result) {
    super.onTestFailure(result);

    // TODO: This is updating the state of the test, but NOT causing it to fail
    Reporter.setCurrentTestResult(result);
}

When I fail the test, the callback is being executed. The Throwable is added to the test result. Everything happens as I expected it to.

However, both the generated report and the build output are incorrect:

[testng] ===============================================
[testng] <redacted>Tests
[testng] Total tests run: 51, Failures: 0, Skips: 0
[testng] ===============================================

Despite the fact that 3 of these test results are being updated as failures:

Any ideas?


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答: The simple answer is that with line-height the character will be in the vertical middle of the line, so a line with a height of 100px has the text in the middle of, thus 50px.</p>

ContentLicense: CC BY-SA 2.5

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


问:
LINUX ls grep command
I want to know What is the difference between the two command:

ls l file; grep *pl file

ls l file; grep ".*pl" file

答:
First off - ";" is a command separator on shell. So the above will execute two different commands sequentially.

So that makes there are three different commands:

```<code>$ ls l file
</code>```

This command will try to list two files namely "l" and "file". It will display the file names if they exist or error out if they do not.

```<code>$ grep *pl file
</code>```

This is trickier. It will try to first replace * with the contents of the current directory. Whichever way it expands, it will append pl to it and try to grep that entire shell expanded pattern in the file. The output entirely depends upon the contents of your current directory.

```<code>$ grep ".*pl" file
</code>```

This will do a greedy match of the pattern ".*pl" in the file. That means it will match all lines in the file which has a pattern:  followed by "pl"

Try this yourself and you would understand what's happening.

Title: LINUX ls grep command

Body:
First off - ";" is a command separator on shell. So the above will execute two different commands sequentially.

So that makes there are three different commands:

$ ls l file

This command will try to list two files namely "l" and "file". It will display the file names if they exist or error out if they do not.

$ grep *pl file

This is trickier. It will try to first replace * with the contents of the current directory. Whichever way it expands, it will append pl to it and try to grep that entire shell expanded pattern in the file. The output entirely depends upon the contents of your current directory.

$ grep ".*pl" file

This will do a greedy match of the pattern ".*pl" in the file. That means it will match all lines in the file which has a pattern:  followed by "pl"

Try this yourself and you would understand what's happening.


问:
Get HTML with current input values
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

```<code>document.getElementById("htmlId").innerHTML;
</code>```

and this:

```<code>$('html').html();
</code>```

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

答:
If you want to get input values I will do with .attr to change dynamically element value !

```<code>$("ButtonToCatchInputValue").click(function(){
        $("input").each(function(){
            $(this).attr("value",this.value);
        });
        console.log($("html").html());
    });
</code>```

Title: Get HTML with current input values

Body:
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

document.getElementById("htmlId").innerHTML;

and this:

$('html').html();

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

Body:
If you want to get input values I will do with .attr to change dynamically element value !

$("ButtonToCatchInputValue").click(function(){
        $("input").each(function(){
            $(this).attr("value",this.value);
        });
        console.log($("html").html());
    });


问:
Hide 1 line of text with CSS
I have two lines of code in a PHP file

```<code><div align="center">The quick brown fox</div>
<div align="center">jumps over the lazy dog.</div>
</code>```

How can I hide only the first line of text displayed with CSS?

答:
div:first-of-type {
    display: none;
}</p>

Title: Hide 1 line of text with CSS

Body:
I have two lines of code in a PHP file

The quick brown fox

jumps over the lazy dog.

How can I hide only the first line of text displayed with CSS?

Body:
div:first-of-type {
    display: none;
}


问:
Nuclide React Native Inspector change port
I'm using Nuclide 0.178.0 and the React Inspector, but It's listening on port 8097.

I can't find where to change that. There is no mention of inspector in the settings.

Debugger is correctly set and work fine.

Thanks for your help.

答: You can go to the path "node_modules/react-native/local-cli/server/server.js" ,change the default port "8081" to your port</p>


问:
No tag defined in tag library imported with prefix
I am working with Java EE 7 in Intellij IDEA and trying to create and use a custom .tag file. I have followed this answer and created a wrapper.tag file in WEB-INF/tags :

```<code><%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
  <jsp:doBody/>
</body></html>
</code>```

And i have created a .jsp file in my web directory:

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>
    <h1>Welcome</h1>
</t:wrapper>
</code>```

But when loading the page I always one of two following errors:

No tag "wrapper" defined in tag library imported with prefix "t"

lang.ClassNotFoundException: org.apache.jsp.temptest_jsp

Note that my jsp file is called temptest.jsp.
Thanks in advance

答:
Two things you need to check, I was also facing the same problem

<%@ taglib tagdir="/WEB-INF/tags/" prefix="tag" %> add '/' after tags

In the tagdir path there should be no spelling mistakes, I had forgot to add 's' to tags folder.

Body:
I am working with Java EE 7 in Intellij IDEA and trying to create and use a custom .tag file. I have followed this answer and created a wrapper.tag file in WEB-INF/tags :

<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>

  <jsp:doBody/>

And i have created a .jsp file in my web directory:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>

Welcome

</t:wrapper>

But when loading the page I always one of two following errors:

No tag "wrapper" defined in tag library imported with prefix "t"

lang.ClassNotFoundException: org.apache.jsp.temptest_jsp

Note that my jsp file is called temptest.jsp.
Thanks in advance


问:
No automatic update using the Beta test in the Play Store
I have configured the open beta tests in the Google Play Store using a link like https://play.google.com/apps/testing/<my app package name> to invite my users to join the beta.

The users can download the app but when a new update is available the users didn't receive the update. Why ?

The only way for the users to download the update is going in the Play Store page of my app and click on the update button.

答: It seem beta apps doesn't have the same update system than published app.</p>


问:
Thread safe processing
I have an algorithm that recognizes objects in photos. The main problem is that it is not thread safe, so e.x. when you set a new configuartion or when you start processing a new image while there is still processing difference one, the algorithm's behavior is undefined and may crash. Below I put my code and my implementation that didn't work well.

```<code>// config struct
public struct Config {}

// reslut of the algorithm
public struct Product {}

// algorith class
public class Recognizer {
   func apply(config: Config)
   func process(frame: UIImage) -> Product {
       let prodcut = Product()
       return prodcut
   }
}

// protocol for an object interested in the result of the Recognizer
protocol Observer: class {
    func didProcess(frame: UIImage, prodcut: Prodcut)
}

// protocol that wraps Recognizer class
protocol RecognizerService {
    func add(observer: Observer)
    func remove(observer: Observer)
    var recognitionConfig: Config { get set }
    func process(frame: UIImage)
}
</code>```

Below how it looks now.

```<code>let recognizerQueue: DispatchQueue = DispatchQueue.global(qos: .background)

class HumanFaceRecognizer: RecognizerService {
      var recognitionConfig: Config
      var observers: [Observer]
      let algorythm: Recognizer
      private var recognizerQueue: DispatchQueue

      init(recognitionConfig: Config,
           observers: [Observer] = [],
           recognizerQueue: DispatchQueue,
           algorythm: Recognizer) {
           self.recognitionConfig = recognitionConfig
           self.observers = observers
           self.recognizerQueue = recognizerQueue
           self.algorythm = algorythm
      }

      func add(observer: Observer) {
          observers.append(observer)
      }

      func remove(observer: Observer) {
          observers.remove(observer)
      }

      func process(frame: UIImage) {
          recognizerQueue.async { [weak self, currentFrame = frame, currentConfig = recognitionConfig] in
          self?.algorythm.process(frame: currentFrame)
          observers.forEach { $0.didProcess(frame: currentFrame, result: currentConfig) }
      }
}
</code>```

I think I'm doing something wrong with dispatching this computation to background, but I can't find right solution to do this.

答:
I think the code you provided is not sufficient to get a clear answer to your problem. It would be helpful if you posted some call stacks of your crashes etc.

First thoughts are:

Maybe the observers are not capable of being called from an arbitrary thread (global queue), because they perform some UI updates etc. In this case, you could call didProcess from the main queue.

Maybe there is a problem that some observers remove themself from the HumanFaceRecognizer while they are called in didProcess, i.e. the forEach call works on a modified collection. In this case, you should copy the observers array before traversing it.

You could also try to (deep) copy the algorithm class, to make it "more" thread safe

Hope this helps a little :-)

Title: Thread safe processing

Body:
I have an algorithm that recognizes objects in photos. The main problem is that it is not thread safe, so e.x. when you set a new configuartion or when you start processing a new image while there is still processing difference one, the algorithm's behavior is undefined and may crash. Below I put my code and my implementation that didn't work well.

// config struct
public struct Config {}

// reslut of the algorithm
public struct Product {}

// algorith class
public class Recognizer {
   func apply(config: Config)
   func process(frame: UIImage) -> Product {
       let prodcut = Product()
       return prodcut
   }
}

// protocol for an object interested in the result of the Recognizer
protocol Observer: class {
    func didProcess(frame: UIImage, prodcut: Prodcut)
}

// protocol that wraps Recognizer class
protocol RecognizerService {
    func add(observer: Observer)
    func remove(observer: Observer)
    var recognitionConfig: Config { get set }
    func process(frame: UIImage)
}

Below how it looks now.

let recognizerQueue: DispatchQueue = DispatchQueue.global(qos: .background)

class HumanFaceRecognizer: RecognizerService {
      var recognitionConfig: Config
      var observers: [Observer]
      let algorythm: Recognizer
      private var recognizerQueue: DispatchQueue

      init(recognitionConfig: Config,
           observers: [Observer] = [],
           recognizerQueue: DispatchQueue,
           algorythm: Recognizer) {
           self.recognitionConfig = recognitionConfig
           self.observers = observers
           self.recognizerQueue = recognizerQueue
           self.algorythm = algorythm
      }

      func add(observer: Observer) {
          observers.append(observer)
      }

      func remove(observer: Observer) {
          observers.remove(observer)
      }

      func process(frame: UIImage) {
          recognizerQueue.async { [weak self, currentFrame = frame, currentConfig = recognitionConfig] in
          self?.algorythm.process(frame: currentFrame)
          observers.forEach { $0.didProcess(frame: currentFrame, result: currentConfig) }
      }
}

I think I'm doing something wrong with dispatching this computation to background, but I can't find right solution to do this.


问:
Azure Ad machine to machine authentication using client credentials node js
I want to make a non-browser application to authenticate a user to AzureAD without all the re-directions and get the token in the end. I can only use nodeJS.
I found the library on github that supports this scenario NodeJS library.

The system I am trying to use this sample uses azure ad which performs realm discovery and sends the user to ADFS to log in.

When the ADFS server is discovered and asked for metadata it returns the xml but the aplication reloads and the whole process starts again.

This is the last log in the console i can see:
MEX: VERBOSE: Retrieving mex at: https://adfsservername/adfs/services/trust/mex

答:
When using the client credentials flow to authenticate with Azure AD, there is no need to interact with ADFS. You can refer the code sample provided by the azure-activedirectory-library-for-nodejs:

Server to Server via Client Credentials:

```<code>var adal = require('adal-node').AuthenticationContext;

var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant';
var authorityUrl = authorityHostUrl + '/' + tenant;
var clientId = 'yourClientIdHere';
var clientSecret = 'yourAADIssuedClientSecretHere'
var resource = '00000002-0000-0000-c000-000000000000';

var context = new AuthenticationContext(authorityUrl);

context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
  if (err) {
    console.log('well that didn\'t work: ' + err.stack);
  } else {
    console.log(tokenResponse);
  }
});
</code>```

Body:
When using the client credentials flow to authenticate with Azure AD, there is no need to interact with ADFS. You can refer the code sample provided by the azure-activedirectory-library-for-nodejs:

Server to Server via Client Credentials:

var adal = require('adal-node').AuthenticationContext;

var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant';
var authorityUrl = authorityHostUrl + '/' + tenant;
var clientId = 'yourClientIdHere';
var clientSecret = 'yourAADIssuedClientSecretHere'
var resource = '00000002-0000-0000-c000-000000000000';

var context = new AuthenticationContext(authorityUrl);

context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
  if (err) {
    console.log('well that didn\'t work: ' + err.stack);
  } else {
    console.log(tokenResponse);
  }
});


问:
Query Execution Time Varies - IBM Informix - Data Studio
I am executing one SQL statement in Informix Data Studio 12.1. It takes around 50 to 60 ms for execution(One day date).

```<code>SELECT
sum( (esrt.service_price) * (esrt.confirmed_qty +  esrt.pharmacy_confirm_quantity) ) AS net_amount
FROM
 episode_service_rendered_tbl esrt,
 patient_details_tbl pdt,
 episode_details_tbl edt,
 ms_mat_service_header_sp_tbl mmshst
 WHERE
esrt.patient_id = pdt.patient_id
AND edt.patient_id = pdt.patient_id
AND esrt.episode_id = edt.episode_id
AND mmshst.material_service_sp_id = esrt.material_service_sp_id
AND mmshst.bill_heads_id = 1
AND esrt.delete_flag = 1
AND esrt.customer_sp_code != '0110000006'
AND pdt.patient_category_id IN(1001,1002,1003,1004,1005,1012,1013)
AND edt.episode_type ='ipd'
AND esrt.generated_date BETWEEN '2017-06-04' AND '2017-06-04';
</code>```

When i am trying to execute the same by creating function it takes around 35 to 40 Seconds for execution.
Please find the code below.

```<code>CREATE FUNCTION sb_pharmacy_account_summary_report_test1(START_DATE DATE,END_DATE DATE)
RETURNING VARCHAR(100),DECIMAL(10,2);
DEFINE v_sale_credit_amt DECIMAL(10,2);
BEGIN
SELECT
 sum( (esrt.service_price) * (esrt.confirmed_qty +
 esrt.pharmacy_confirm_quantity) ) AS net_amount
 INTO
 v_sale_credit_amt
 FROM
 episode_service_rendered_tbl esrt,
 patient_details_tbl pdt,
 episode_details_tbl edt,
 ms_mat_service_header_sp_tbl mmshst
 WHERE
 esrt.patient_id = pdt.patient_id
 AND edt.patient_id = pdt.patient_id
 AND esrt.episode_id = edt.episode_id
 AND mmshst.material_service_sp_id = esrt.material_service_sp_id
 AND mmshst.bill_heads_id = 1
 AND esrt.delete_flag = 1
 AND esrt.customer_sp_code != '0110000006'
 AND pdt.patient_category_id IN(1001,1002,1003,1004,1005,1012,1013)
 AND edt.episode_type ='ipd'
 AND esrt.generated_date BETWEEN START_DATE AND END_DATE;
 RETURN 'SALE CREDIT','' with resume;
 RETURN 'IP SB Credit Amount',v_sale_credit_amt;
END
END FUNCTION;
</code>```

Can someone tell me what is the reason for this time variation?

答:
..in very easy words.

If you create a function the sql is parsed and stored with some optimization stuff in the database. If you call the function, optimizer knows about the sql and execute it. So optimization is done only once, if you create the function.

If you run the SQL, Optimizer parse the sql, optimizes it and then execute it, every time you execute the SQL.
This explains the time difference.

Body:
I am executing one SQL statement in Informix Data Studio 12.1. It takes around 50 to 60 ms for execution(One day date).

SELECT
sum( (esrt.service_price) * (esrt.confirmed_qty +  esrt.pharmacy_confirm_quantity) ) AS net_amount
FROM
 episode_service_rendered_tbl esrt,
 patient_details_tbl pdt,
 episode_details_tbl edt,
 ms_mat_service_header_sp_tbl mmshst
 WHERE
esrt.patient_id = pdt.patient_id
AND edt.patient_id = pdt.patient_id
AND esrt.episode_id = edt.episode_id
AND mmshst.material_service_sp_id = esrt.material_service_sp_id
AND mmshst.bill_heads_id = 1
AND esrt.delete_flag = 1
AND esrt.customer_sp_code != '0110000006'
AND pdt.patient_category_id IN(1001,1002,1003,1004,1005,1012,1013)
AND edt.episode_type ='ipd'
AND esrt.generated_date BETWEEN '2017-06-04' AND '2017-06-04';

When i am trying to execute the same by creating function it takes around 35 to 40 Seconds for execution.
Please find the code below.

CREATE FUNCTION sb_pharmacy_account_summary_report_test1(START_DATE DATE,END_DATE DATE)
RETURNING VARCHAR(100),DECIMAL(10,2);
DEFINE v_sale_credit_amt DECIMAL(10,2);
BEGIN
SELECT
 sum( (esrt.service_price) * (esrt.confirmed_qty +
 esrt.pharmacy_confirm_quantity) ) AS net_amount
 INTO
 v_sale_credit_amt
 FROM
 episode_service_rendered_tbl esrt,
 patient_details_tbl pdt,
 episode_details_tbl edt,
 ms_mat_service_header_sp_tbl mmshst
 WHERE
 esrt.patient_id = pdt.patient_id
 AND edt.patient_id = pdt.patient_id
 AND esrt.episode_id = edt.episode_id
 AND mmshst.material_service_sp_id = esrt.material_service_sp_id
 AND mmshst.bill_heads_id = 1
 AND esrt.delete_flag = 1
 AND esrt.customer_sp_code != '0110000006'
 AND pdt.patient_category_id IN(1001,1002,1003,1004,1005,1012,1013)
 AND edt.episode_type ='ipd'
 AND esrt.generated_date BETWEEN START_DATE AND END_DATE;
 RETURN 'SALE CREDIT','' with resume;
 RETURN 'IP SB Credit Amount',v_sale_credit_amt;
END
END FUNCTION;

Can someone tell me what is the reason for this time variation?


问:
Print out Average in for loop
This is my question

get to input a positive integer representing a number of weeks, loop
  continuously until the value entered is positive. For each week, enter
  a value for liters and a value for kilometers. For each value, should
  loop until the value entered is positive. both values is a real
  number. Then output the fuel economy for that week (liters divided by
  kilometers). Finally, output the average fuel economy. You must make
  good use of submodules in your answer.

This is my work

```<code>import java.util.*;
public class Exam8 {
    public static void main(String[] args) {
        int numweek = 0;
        double valkms = 0;
        double vallits = 0;
        double average = 0;
        double result = 0;
        int count = 0;
        double sum = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of week: ");
        numweek = sc.nextInt();
        while (numweek < 1) {
            System.out.println("Enter a positive of number week: ");
            numweek = sc.nextInt();
        }
        while (true) {
             count++;
             System.out.print("Enter value of litres: : ");
             vallits = sc.nextDouble();
             while (vallits < 0) {
                 System.out.print("Positive litres: ");
                 vallits= sc.nextDouble();
             }
             System.out.print("Enter value of kilometres: : ");
             valkms = sc.nextDouble();
             while (valkms < 0) {
                 System.out.print("Positive kilometres: ");
                 valkms = sc.nextDouble();
             }
             if (vallits == 0 || valkms == 0) {
                 break;
             }
             result = vallits / valkms;
             sum = result + (double)count;
             System.out.println(result);
        }
        //average = getAverg(sum,count);
        System.out.print("Average of fuel economy is: " + average);
    }

    public static double getAverg(double sum, int count) {
        double average;
        average = sum/count;
        return average;
    }
}
</code>```

I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).

答:
This code should work:

```<code>import java.util.*;
public class App {
    public static void main(String[] args) {
        int numweek = 0;
        double valkms = 0;
        double vallits = 0;
        double average = 0;
        double result = 0;
        int count = 0;
        double sum = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of week: ");
        numweek = sc.nextInt();
        while (numweek < 1) {
            System.out.println("Enter a positive of number week: ");
            numweek = sc.nextInt();
        }
        while (count < numweek) {
             count++;
             System.out.print("Enter value of litres: : ");
             vallits = sc.nextDouble();
             while (vallits < 0) {
                 System.out.print("Positive litres: ");
                 vallits= sc.nextDouble();
             }
             System.out.print("Enter value of kilometres: : ");
             valkms = sc.nextDouble();
             while (valkms < 0) {
                 System.out.print("Positive kilometres: ");
                 valkms = sc.nextDouble();
             }
             if (vallits == 0 || valkms == 0) {
                 break;
             }
             result = vallits / valkms;
             sum += result;
             System.out.println(result);
        }
        System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
    }

    public static double getAverg(double sum, double numOfWeeks) {
        double average;
        average = sum/numOfWeeks;
        return average;
    }
}
</code>```

Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.

Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.

You also didn't use your getAverg function anywhere.

Title: Print out Average in for loop

Body:
This is my question

get to input a positive integer representing a number of weeks, loop
  continuously until the value entered is positive. For each week, enter
  a value for liters and a value for kilometers. For each value, should
  loop until the value entered is positive. both values is a real
  number. Then output the fuel economy for that week (liters divided by
  kilometers). Finally, output the average fuel economy. You must make
  good use of submodules in your answer.

This is my work

import java.util.*;
public class Exam8 {
    public static void main(String[] args) {
        int numweek = 0;
        double valkms = 0;
        double vallits = 0;
        double average = 0;
        double result = 0;
        int count = 0;
        double sum = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of week: ");
        numweek = sc.nextInt();
        while (numweek < 1) {
            System.out.println("Enter a positive of number week: ");
            numweek = sc.nextInt();
        }
        while (true) {
             count++;
             System.out.print("Enter value of litres: : ");
             vallits = sc.nextDouble();
             while (vallits < 0) {
                 System.out.print("Positive litres: ");
                 vallits= sc.nextDouble();
             }
             System.out.print("Enter value of kilometres: : ");
             valkms = sc.nextDouble();
             while (valkms < 0) {
                 System.out.print("Positive kilometres: ");
                 valkms = sc.nextDouble();
             }
             if (vallits == 0 || valkms == 0) {
                 break;
             }
             result = vallits / valkms;
             sum = result + (double)count;
             System.out.println(result);
        }
        //average = getAverg(sum,count);
        System.out.print("Average of fuel economy is: " + average);
    }

    public static double getAverg(double sum, int count) {
        double average;
        average = sum/count;
        return average;
    }
}

I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).

Body:
This code should work:

import java.util.*;
public class App {
    public static void main(String[] args) {
        int numweek = 0;
        double valkms = 0;
        double vallits = 0;
        double average = 0;
        double result = 0;
        int count = 0;
        double sum = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of week: ");
        numweek = sc.nextInt();
        while (numweek < 1) {
            System.out.println("Enter a positive of number week: ");
            numweek = sc.nextInt();
        }
        while (count < numweek) {
             count++;
             System.out.print("Enter value of litres: : ");
             vallits = sc.nextDouble();
             while (vallits < 0) {
                 System.out.print("Positive litres: ");
                 vallits= sc.nextDouble();
             }
             System.out.print("Enter value of kilometres: : ");
             valkms = sc.nextDouble();
             while (valkms < 0) {
                 System.out.print("Positive kilometres: ");
                 valkms = sc.nextDouble();
             }
             if (vallits == 0 || valkms == 0) {
                 break;
             }
             result = vallits / valkms;
             sum += result;
             System.out.println(result);
        }
        System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
    }

    public static double getAverg(double sum, double numOfWeeks) {
        double average;
        average = sum/numOfWeeks;
        return average;
    }
}

Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.

Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.

You also didn't use your getAverg function anywhere.


问:
How to use the PINpad to enter the Password in Ncryptoki
I'm currently using Ncryptoki C# sample project to test the HSM if it's working. I already setup and initialized the slot and token. When I run the sample code, it always tell me wrong PIN. I use the PINpad to enter the password "1111", any help would be really appreciate.</p>

```<code>using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Cryptware.NCryptoki;

namespace USCToolkit.NCryptokiTest
{
    class Program
    {
       static void Main(string[] args)
       {
        // Creates a Cryptoki object related to the specific PKCS#11 native library
        //Cryptoki cryptoki = new Cryptoki("smaoscki.dll");
        Cryptoki cryptoki = new Cryptoki(@"C:\Program Files\SafeNet\LunaClient\cryptoki.dll");

        cryptoki.Initialize();

        // Prints all information relating to the native library
        CryptokiInfo info = cryptoki.Info;
        Console.WriteLine(info.Version);
        Console.WriteLine(info.ManufacturerID);
        Console.WriteLine(info.LibDescription);

        // Reads the set of slots containing a token
        SlotList slots = cryptoki.Slots;
        if(slots.Count == 0)
        {
           Console.WriteLine("No slot available");
           return;
        }

        // Gets the first slot available
        Slot slot = slots[0];

        // Prints all information relating to the slot
        SlotInfo sinfo = slot.Info;
        Console.WriteLine(sinfo.Description);
        Console.WriteLine(sinfo.ManufacturerID);
        ///
        Console.WriteLine("flags: "+sinfo.Flags);

        if (!slot.IsTokenPresent)
        {
            Console.WriteLine("No token inserted in the slot: " + slots[0].Info.Description);
            return;
        }

        // Gets the first token available
        Token token = slot.Token;

        // Prints all information relating to the token
        TokenInfo tinfo = token.Info;
        Console.WriteLine(tinfo.Label);
        Console.WriteLine(tinfo.ManufacturerID);
        Console.WriteLine(tinfo.Model);
        Console.WriteLine(tinfo.SerialNumber);
        Console.WriteLine(tinfo.HardwareVersion);

        // Opens a read/write serial session
        Session session =
            token.OpenSession(Session.CKF_SERIAL_SESSION | Session.CKF_RW_SESSION,
                              null,
                              null);

        /////
        //PIN pin = new PIN();
        /////
        // Executes the login passing the user PIN
        int nRes = session.Login(Session.CKU_USER,"1111");
        if (nRes != 0)
        {
            Console.WriteLine("Wrong PIN");
            return;
        }

        Console.WriteLine("Logged in:" + session.IsLoggedIn);

        // Searchs for an RSA private key object
        // Sets the template with its attributes
        CryptokiCollection template = new CryptokiCollection();
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));

        // Launchs the search specifying the template just created
        CryptokiCollection objects = session.Objects.Find(template, 10);

        foreach (Object obj in objects)
        {
            Console.WriteLine(((PrivateKey)obj).Label);
        }

        for (int i = 0; i < objects.Count; i++)
        {
            Console.WriteLine(((PrivateKey)objects[i]).Label);
        }

        RSAPrivateKey privateKey;
        RSAPublicKey publicKey;

        // If the private key is not found generates the key pair
        if(objects.Count == 0)
        {
            CryptokiCollection templatePub = new CryptokiCollection();
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_KEY));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE, true));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_ID, "1"));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_MODULUS_BITS, 1024));

            CryptokiCollection templatePri = new CryptokiCollection();
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE, true));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_ID, "1"));

            //Generate the key pair
            Key[] keys = session.GenerateKeyPair(Mechanism.RSA_PKCS_KEY_PAIR_GEN, templatePub, templatePri);
            privateKey = (RSAPrivateKey)keys[1];
            publicKey = (RSAPublicKey)keys[0];
        }
        else //If the private key is found gets the corresponding public key
        {
            privateKey = (RSAPrivateKey)objects[objects.Count - 1];
            Console.WriteLine(privateKey.Label);

            // search for the related public key
            template = new CryptokiCollection();
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_KEY));
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));

            // Launchs the search specifying the template just created
            objects = session.Objects.Find(template, 1);
            publicKey = (RSAPublicKey)objects[0];
            Console.WriteLine(publicKey.Label);

            // prepares for the signature
            string helloworld = "Hello World";
            byte[] text = Encoding.ASCII.GetBytes(helloworld);

            // launches the digital signature operation with a RSA_PKCS mechanism
            nRes = session.SignInit(Mechanism.SHA1_RSA_PKCS, privateKey);

            // computes the signature
            byte[] signature = session.Sign(text);

            // launches the digital signature verification with a RSA_PKCS mechanism
            nRes = session.VerifyInit(Mechanism.SHA1_RSA_PKCS, publicKey);

            // verifies the signature
            nRes = session.Verify(text, signature);

            // results if nRes == 0 means that the verification is OK
            Console.Write("Verified " + (nRes == 0));
        }

        // Logouts and closes the session
        session.Logout();
        session.Close();
        cryptoki.Finalize(IntPtr.Zero);
    }

}
}
</code>```

答:
I guess your problem is caused by insufficient validation of return value from Login method:

```<code>int nRes = session.Login(Session.CKU_USER,"1111");
if (nRes != 0)
{
    Console.WriteLine("Wrong PIN");
    return;
}
</code>```

Your code continues only if the value is 0 but underlying PKCS#11 function C_Login returns not only CKR_OK but also CKR_USER_ALREADY_LOGGED_IN and bunch of other codes that do not necessarily indicate error.

Body:
I'm currently using Ncryptoki C# sample project to test the HSM if it's working. I already setup and initialized the slot and token. When I run the sample code, it always tell me wrong PIN. I use the PINpad to enter the password "1111", any help would be really appreciate.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Cryptware.NCryptoki;

namespace USCToolkit.NCryptokiTest
{
    class Program
    {
       static void Main(string[] args)
       {
        // Creates a Cryptoki object related to the specific PKCS#11 native library
        //Cryptoki cryptoki = new Cryptoki("smaoscki.dll");
        Cryptoki cryptoki = new Cryptoki(@"C:\Program Files\SafeNet\LunaClient\cryptoki.dll");

        cryptoki.Initialize();

        // Prints all information relating to the native library
        CryptokiInfo info = cryptoki.Info;
        Console.WriteLine(info.Version);
        Console.WriteLine(info.ManufacturerID);
        Console.WriteLine(info.LibDescription);

        // Reads the set of slots containing a token
        SlotList slots = cryptoki.Slots;
        if(slots.Count == 0)
        {
           Console.WriteLine("No slot available");
           return;
        }

        // Gets the first slot available
        Slot slot = slots[0];

        // Prints all information relating to the slot
        SlotInfo sinfo = slot.Info;
        Console.WriteLine(sinfo.Description);
        Console.WriteLine(sinfo.ManufacturerID);
        ///
        Console.WriteLine("flags: "+sinfo.Flags);

        if (!slot.IsTokenPresent)
        {
            Console.WriteLine("No token inserted in the slot: " + slots[0].Info.Description);
            return;
        }

        // Gets the first token available
        Token token = slot.Token;

        // Prints all information relating to the token
        TokenInfo tinfo = token.Info;
        Console.WriteLine(tinfo.Label);
        Console.WriteLine(tinfo.ManufacturerID);
        Console.WriteLine(tinfo.Model);
        Console.WriteLine(tinfo.SerialNumber);
        Console.WriteLine(tinfo.HardwareVersion);

        // Opens a read/write serial session
        Session session =
            token.OpenSession(Session.CKF_SERIAL_SESSION | Session.CKF_RW_SESSION,
                              null,
                              null);

        /////
        //PIN pin = new PIN();
        /////
        // Executes the login passing the user PIN
        int nRes = session.Login(Session.CKU_USER,"1111");
        if (nRes != 0)
        {
            Console.WriteLine("Wrong PIN");
            return;
        }

        Console.WriteLine("Logged in:" + session.IsLoggedIn);

        // Searchs for an RSA private key object
        // Sets the template with its attributes
        CryptokiCollection template = new CryptokiCollection();
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
        template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));

        // Launchs the search specifying the template just created
        CryptokiCollection objects = session.Objects.Find(template, 10);

        foreach (Object obj in objects)
        {
            Console.WriteLine(((PrivateKey)obj).Label);
        }

        for (int i = 0; i < objects.Count; i++)
        {
            Console.WriteLine(((PrivateKey)objects[i]).Label);
        }

        RSAPrivateKey privateKey;
        RSAPublicKey publicKey;

        // If the private key is not found generates the key pair
        if(objects.Count == 0)
        {
            CryptokiCollection templatePub = new CryptokiCollection();
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_KEY));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE, true));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_ID, "1"));
            templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_MODULUS_BITS, 1024));

            CryptokiCollection templatePri = new CryptokiCollection();
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE, true));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));
            templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_ID, "1"));

            //Generate the key pair
            Key[] keys = session.GenerateKeyPair(Mechanism.RSA_PKCS_KEY_PAIR_GEN, templatePub, templatePri);
            privateKey = (RSAPrivateKey)keys[1];
            publicKey = (RSAPublicKey)keys[0];
        }
        else //If the private key is found gets the corresponding public key
        {
            privateKey = (RSAPrivateKey)objects[objects.Count - 1];
            Console.WriteLine(privateKey.Label);

            // search for the related public key
            template = new CryptokiCollection();
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_KEY));
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "Ugo's new Key"));

            // Launchs the search specifying the template just created
            objects = session.Objects.Find(template, 1);
            publicKey = (RSAPublicKey)objects[0];
            Console.WriteLine(publicKey.Label);

            // prepares for the signature
            string helloworld = "Hello World";
            byte[] text = Encoding.ASCII.GetBytes(helloworld);

            // launches the digital signature operation with a RSA_PKCS mechanism
            nRes = session.SignInit(Mechanism.SHA1_RSA_PKCS, privateKey);

            // computes the signature
            byte[] signature = session.Sign(text);

            // launches the digital signature verification with a RSA_PKCS mechanism
            nRes = session.VerifyInit(Mechanism.SHA1_RSA_PKCS, publicKey);

            // verifies the signature
            nRes = session.Verify(text, signature);

            // results if nRes == 0 means that the verification is OK
            Console.Write("Verified " + (nRes == 0));
        }

        // Logouts and closes the session
        session.Logout();
        session.Close();
        cryptoki.Finalize(IntPtr.Zero);
    }

}
}

Body:
I guess your problem is caused by insufficient validation of return value from Login method:

int nRes = session.Login(Session.CKU_USER,"1111");
if (nRes != 0)
{
    Console.WriteLine("Wrong PIN");
    return;
}

Your code continues only if the value is 0 but underlying PKCS#11 function C_Login returns not only CKR_OK but also CKR_USER_ALREADY_LOGGED_IN and bunch of other codes that do not necessarily indicate error.


问:
JPA type safe order Query
I have

Entity: Users

and

@NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")

Use it like this:

```<code>Query query = em.createNamedQuery("Technologies.findByIsActive", Technologies.class);
query.setFirstResult(technologiesTableModel.getLowItemIndex());
query.setMaxResults(technologiesTableModel.getPageRange().intValue());
List<Technologies> technologies = query.setParameter("isActive", 'Y').getResultList();
</code>```

But I want to sort this result dynamic. I have one String that contains column name that I want to sort(field content come from request). How can I do that without new query for each field and direction and to type safe (without direct append order by clause with field name).

My research show suggestion to use CriteriaQuery(I can't found example with using a NamedQuery defined above entity), TypedQuery(I can't found example with ordering, only with setFirstResult and setMaxResults. But I need both sorting and pagination) or JpaRepository (I can't find full implemented example with good description).

That I want is to sort my data by field name (that I have like String) and after that to paging it (with setFirstResult and setMaxResults). I want to do that with NamedQuery that I was define(in Entity class declaration) and not define query on fly or append order clause to query end with String concatenations.

EDIT:

All I need is a good explanation how this have to be implemented (with all good practices). I didn't have idea how to do that. All I try is:

My queries to be at one place(most of them)

String concatenation is not good practice to create queries.

答:
I resolve my problem with case clause. In my entity I added orderClause field like:

```<code>public static final String orderClause = " order by "
            + "case when :orderField = 'id' and :orderDirection = 'asc' then s.id else 0 end ASC, "
            + "case when :orderField = 'id' and :orderDirection = 'desc' then s.id else 0 end DESC, "
            + "case when :orderField = 'username' and :orderDirection = 'asc' then s.username else '' end ASC, "
            + "case when :orderField = 'username' and :orderDirection = 'desc' then s.username else '' end DESC, "
            + "s.id ASC";
</code>```

And add this field to end of named queries where is needed like:

```<code>@NamedQueries(
{
    @NamedQuery(name = "SysRoles.findAll", query = "SELECT s FROM SysRoles s" + SysRoles.orderClause),
    @NamedQuery(name = "SysRoles.findByIsActive", query = "SELECT s FROM SysRoles s WHERE s.isActive = :isActive " + SysRoles.orderClause)
})
public class SysRoles implements Serializable {
    public static final String orderClause = " order by "
        + "case when :orderField = 'id' and :orderDirection = 'asc' then s.id else 0 end ASC, "
        + "case when :orderField = 'id' and :orderDirection = 'desc' then s.id else 0 end DESC, "
        + "case when :orderField = 'username' and :orderDirection = 'asc' then s.username else '' end ASC, "
        + "case when :orderField = 'username' and :orderDirection = 'desc' then s.username else '' end DESC, "
        + "case when :orderField = 'isActive' and :orderDirection = 'asc' then s.isActive else '' end ASC, "
        + "case when :orderField = 'isActive' and :orderDirection = 'desc' then s.isActive else '' end DESC, "
        + "s.id ASC";
 ...
}
</code>```

And I call my named query like:

```<code>Query query = em.createNamedQuery("SysRoles .findAll", SysRoles.class);
        //Pagination
        query.setFirstResult(lowItemIndex);
        query.setMaxResults(maxResults);
List<SysRoles> sysUsers= query.setParameter("isActive", "Y")
                 //ditection of sorting
                .setParameter("orderDirection", direction)
                 //name of sorting columns
                .setParameter("orderField", orderByColumnName).getResultList();
</code>```

More about ordering by column name and good explantation can be find here in blog asktom.oracle.com.

With this solution we have a little bit ugly queries, but they are in one place and ordering is also there.

Title: JPA type safe order Query

Body:
I have

Entity: Users

and

@NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")

Use it like this:

Query query = em.createNamedQuery("Technologies.findByIsActive", Technologies.class);
query.setFirstResult(technologiesTableModel.getLowItemIndex());
query.setMaxResults(technologiesTableModel.getPageRange().intValue());
List<Technologies> technologies = query.setParameter("isActive", 'Y').getResultList();

But I want to sort this result dynamic. I have one String that contains column name that I want to sort(field content come from request). How can I do that without new query for each field and direction and to type safe (without direct append order by clause with field name).

My research show suggestion to use CriteriaQuery(I can't found example with using a NamedQuery defined above entity), TypedQuery(I can't found example with ordering, only with setFirstResult and setMaxResults. But I need both sorting and pagination) or JpaRepository (I can't find full implemented example with good description).

That I want is to sort my data by field name (that I have like String) and after that to paging it (with setFirstResult and setMaxResults). I want to do that with NamedQuery that I was define(in Entity class declaration) and not define query on fly or append order clause to query end with String concatenations.

EDIT:

All I need is a good explanation how this have to be implemented (with all good practices). I didn't have idea how to do that. All I try is:

My queries to be at one place(most of them)

String concatenation is not good practice to create queries.

Body:
I resolve my problem with case clause. In my entity I added orderClause field like:

public static final String orderClause = " order by "
            + "case when :orderField = 'id' and :orderDirection = 'asc' then s.id else 0 end ASC, "
            + "case when :orderField = 'id' and :orderDirection = 'desc' then s.id else 0 end DESC, "
            + "case when :orderField = 'username' and :orderDirection = 'asc' then s.username else '' end ASC, "
            + "case when :orderField = 'username' and :orderDirection = 'desc' then s.username else '' end DESC, "
            + "s.id ASC";

And add this field to end of named queries where is needed like:

@NamedQueries(
{
    @NamedQuery(name = "SysRoles.findAll", query = "SELECT s FROM SysRoles s" + SysRoles.orderClause),
    @NamedQuery(name = "SysRoles.findByIsActive", query = "SELECT s FROM SysRoles s WHERE s.isActive = :isActive " + SysRoles.orderClause)
})
public class SysRoles implements Serializable {
    public static final String orderClause = " order by "
        + "case when :orderField = 'id' and :orderDirection = 'asc' then s.id else 0 end ASC, "
        + "case when :orderField = 'id' and :orderDirection = 'desc' then s.id else 0 end DESC, "
        + "case when :orderField = 'username' and :orderDirection = 'asc' then s.username else '' end ASC, "
        + "case when :orderField = 'username' and :orderDirection = 'desc' then s.username else '' end DESC, "
        + "case when :orderField = 'isActive' and :orderDirection = 'asc' then s.isActive else '' end ASC, "
        + "case when :orderField = 'isActive' and :orderDirection = 'desc' then s.isActive else '' end DESC, "
        + "s.id ASC";
 ...
}

And I call my named query like:

Query query = em.createNamedQuery("SysRoles .findAll", SysRoles.class);
        //Pagination
        query.setFirstResult(lowItemIndex);
        query.setMaxResults(maxResults);
List<SysRoles> sysUsers= query.setParameter("isActive", "Y")
                 //ditection of sorting
                .setParameter("orderDirection", direction)
                 //name of sorting columns
                .setParameter("orderField", orderByColumnName).getResultList();

More about ordering by column name and good explantation can be find here in blog asktom.oracle.com.

With this solution we have a little bit ugly queries, but they are in one place and ordering is also there.


问:
Replace relative urls to absolute
I have the html source of a page in a form of string with me:

```<code><html>
    <head>
          <link rel="stylesheet" type="text/css" href="/css/all.css" />
    </head>
    <body>
        <a href="/test.aspx">Test</a>
        <a href="http://mysite.com">Test</a>
        <img src="/images/test.jpg"/>
        <img src="http://mysite.com/images/test.jpg"/>
    </body>
</html>
</code>```

I want to convert all the relative paths to absolute. I want the output be:

```<code><html>
    <head>
          <link rel="stylesheet" type="text/css" href="http://mysite.com/css/all.css" />
    </head>
    <body>
        <a href="http://mysite.com/test.aspx">Test</a>
        <a href="http://mysite.com">Test</a>
        <img src="http://mysite.com/images/test.jpg"/>
        <img src="http://mysite.com/images/test.jpg"/>
    </body>
</html>
</code>```

Note: I want only the relative paths to be converted to absolute ones in that string. The absolute ones which are already in that string should not be touched, they are fine to me as they are already absolute.
Can this be done by regex or other means?

答:
This works great for me. I uses it on email templates. I'm using the MVC/Razor "~/" at the beginning of each link.</p>

```<code>' Parse HTML and make relative links absolute with p_basepath
Public Function ParseHTMLLinks(ByVal MailBodyHTML As String) As String
    ' Declare & intialize variables
    Dim strHTMLBody As String = MailBodyHTML

    ' Set regex variables
    Dim strSrcSubMatch As String = ""
    Dim strSrcFullUrl As String = ""
    Dim srcPattern As String = "[=""]\/?([^""\s]*(\.gif|\.jpg|\.jpeg|\.png|\.css|\.js))[""\s]"
    Dim srcOptions As RegexOptions = RegexOptions.IgnoreCase
    Dim regex As Regex = New Regex(srcPattern, srcOptions)
    Dim regexSub As Regex = New Regex(srcPattern, srcOptions)
    Dim Matches As MatchCollection = regex.Matches(strHTMLBody)

    Try
        For Each Match As Match In Matches
            ' filter out absolute links
            If InStr(Match.ToString, "://") = 0 And InStr(LCase(Match.ToString), "mailto:") = 0 And InStr(LCase(Match.ToString), "javascript:") = 0 Then
                ' Remove the " at each end of relative path
                strSrcSubMatch = regexSub.Replace(Match.ToString, "$1")
                ' Concatenate the FullPath
                strSrcFullUrl = p_basePath & strSrcSubMatch
                ' Execute the replace
                strHTMLBody = Replace(strHTMLBody, "/" & strSrcSubMatch, strSrcFullUrl)
            End If
        Next

    Catch e As WebException
        'Add errors to List(Of WebException), if any.
        ErrorCodes.Add(e)
    End Try

    Return strHTMLBody 'MailBodyHTML
End Function
</code>```

Title: Replace relative urls to absolute

Body:
I have the html source of a page in a form of string with me:

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

        Test
        Test

I want to convert all the relative paths to absolute. I want the output be:

          <link rel="stylesheet" type="text/css" href="http://mysite.com/css/all.css" />

        Test
        Test

Note: I want only the relative paths to be converted to absolute ones in that string. The absolute ones which are already in that string should not be touched, they are fine to me as they are already absolute.
Can this be done by regex or other means?

Body:
This works great for me. I uses it on email templates. I'm using the MVC/Razor "~/" at the beginning of each link.

' Parse HTML and make relative links absolute with p_basepath
Public Function ParseHTMLLinks(ByVal MailBodyHTML As String) As String
    ' Declare & intialize variables
    Dim strHTMLBody As String = MailBodyHTML

    ' Set regex variables
    Dim strSrcSubMatch As String = ""
    Dim strSrcFullUrl As String = ""
    Dim srcPattern As String = "[=""]\/?([^""\s]*(\.gif|\.jpg|\.jpeg|\.png|\.css|\.js))[""\s]"
    Dim srcOptions As RegexOptions = RegexOptions.IgnoreCase
    Dim regex As Regex = New Regex(srcPattern, srcOptions)
    Dim regexSub As Regex = New Regex(srcPattern, srcOptions)
    Dim Matches As MatchCollection = regex.Matches(strHTMLBody)

    Try
        For Each Match As Match In Matches
            ' filter out absolute links
            If InStr(Match.ToString, "://") = 0 And InStr(LCase(Match.ToString), "mailto:") = 0 And InStr(LCase(Match.ToString), "javascript:") = 0 Then
                ' Remove the " at each end of relative path
                strSrcSubMatch = regexSub.Replace(Match.ToString, "$1")
                ' Concatenate the FullPath
                strSrcFullUrl = p_basePath & strSrcSubMatch
                ' Execute the replace
                strHTMLBody = Replace(strHTMLBody, "/" & strSrcSubMatch, strSrcFullUrl)
            End If
        Next

    Catch e As WebException
        'Add errors to List(Of WebException), if any.
        ErrorCodes.Add(e)
    End Try

    Return strHTMLBody 'MailBodyHTML
End Function


问:
Best way to implement an Real-Time IP Whitelisting System
I want to set up a IP whitelisting system to protect my web server.

There is 3 Layers I can secure: (Internet =>) Firewall => Nginx Reverse Proxy => Node.js Server

In terms of practicality, I'm securing my Node.js server, because I can dynamically Allow/Deny IPs in a Real-Time Firebase Table I edit via a custom web interface. But It doesn't prevent DDoS cleanly because Even though I will return an error to unauthorized IPs, my node server would handle the load directly which is not good...

I would prefer to protect my server in a upper level, like Nginx or Firewall.
However, the IP lists are files on the server, and it seems complicated to implement a solution as comfortable as the one I use now.

What do you suggest, and what do you think of my current solution ?

Thanks !

答:
There are two ways to build "dynamic" IP filter:

On every request Nginx asks Firebase (or other ip white list source) "does this client in ip white list?". To do so you need one of modules which allow scripting for nginx, like ngx_http_lua_module, ngx_http_perl_module or nginScript;

On every white list update Firebase triggers event, then some application captures event and rebuilds firewall rules or nginx ip filter.

Second way seems stronger to stand before DDoS, but less applicable when ip white list very large and changes are frequent.

ContentLicense: CC BY-SA 4.0


问:
SQL to convert distinct item in row to column
I have a table as

```<code>Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
</code>```

I want below output

```<code>Date        Mango       Orange
20170101    5           6
20170102    7           8
</code>```

for this i used below sql query

```<code>SELECT
   Date,
   SUM(case when Item='Mango' then Quantity else 0 end) AS Mango,
   SUM(case when Item='Orange' then Quantity else 0 end) AS Orange
FROM orderTable
GROUP BY date
</code>```

but this is kind of hard coding for Mango and Orange. What if I need new item in orderTable. Can any one suggest me how can I make this query dynamic. So that if I add new item it automatically create new coulmn having item name as name and it will have 0 value under column against date when order not placed for that item.

like

```<code>Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
20170102      Cherry        9
</code>```

then output should be as ...

```<code>Date        Mango       Orange    Cherry
20170101    5           6         0
20170102    7           8         9
</code>```

答:
```<code>IF OBJECT_ID('Test') IS NOt NUll
DROP TABLE Test

CREATE TABLE Test
(
    Date VARCHAR(100),
    Item VARCHAR(100),
    Quantity INT
)

INSERT Test VALUES
    ('20170101', 'Mango', 5),
    ('20170101', 'Orange', 6),
    ('20170102', 'Mango', 7),
    ('20170102', 'Orange', 8),
    ('20170102', 'Cherry', 9)

DECLARE @SQL AS VARCHAR(MAX)
DECLARE @Columns AS VARCHAR(MAX)
DECLARE @Columns2 AS VARCHAR(MAX)

SELECT @Columns = COALESCE(@Columns + ',','') + QUOTENAME(Item)
FROM (SELECT DISTINCT Item FROM Test) AS B
ORDER BY B.Item

SELECT @Columns2 = COALESCE(@Columns2 + ',','') + 'ISNULL(' + QUOTENAME(Item) + ', 0) AS ' + Item
FROM (SELECT DISTINCT Item FROM Test) AS B
ORDER BY B.Item

SET @SQL = '
WITH PivotData AS
(
    SELECT Date, Item, Quantity FROM Test
)
SELECT
    Date, ' + @Columns2 + '
FROM PivotData
PIVOT
(
    SUM(Quantity)
    FOR Item
    IN (' + @Columns + ')
) AS PivotResult
ORDER BY Date'

EXEC(@SQL);

DROP TABLE Test
</code>```

Result:

```<code>Date        Cherry  Mango   Orange
20170101    0       5       6
20170102    9       7       8
</code>```

Reference (code pic not shown but you can access it if you view source the page) :
http://sqlmag.com/t-sql/pivoting-dynamic-way

Body:
I have a table as

Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8

I want below output

Date        Mango       Orange
20170101    5           6
20170102    7           8

for this i used below sql query

SELECT
   Date,
   SUM(case when Item='Mango' then Quantity else 0 end) AS Mango,
   SUM(case when Item='Orange' then Quantity else 0 end) AS Orange
FROM orderTable
GROUP BY date

but this is kind of hard coding for Mango and Orange. What if I need new item in orderTable. Can any one suggest me how can I make this query dynamic. So that if I add new item it automatically create new coulmn having item name as name and it will have 0 value under column against date when order not placed for that item.

like

Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
20170102      Cherry        9

then output should be as ...

Date        Mango       Orange    Cherry
20170101    5           6         0
20170102    7           8         9

Body:
IF OBJECT_ID('Test') IS NOt NUll
DROP TABLE Test

CREATE TABLE Test
(
    Date VARCHAR(100),
    Item VARCHAR(100),
    Quantity INT
)

INSERT Test VALUES
    ('20170101', 'Mango', 5),
    ('20170101', 'Orange', 6),
    ('20170102', 'Mango', 7),
    ('20170102', 'Orange', 8),
    ('20170102', 'Cherry', 9)

DECLARE @SQL AS VARCHAR(MAX)
DECLARE @Columns AS VARCHAR(MAX)
DECLARE @Columns2 AS VARCHAR(MAX)

SELECT @Columns = COALESCE(@Columns + ',','') + QUOTENAME(Item)
FROM (SELECT DISTINCT Item FROM Test) AS B
ORDER BY B.Item

SELECT @Columns2 = COALESCE(@Columns2 + ',','') + 'ISNULL(' + QUOTENAME(Item) + ', 0) AS ' + Item
FROM (SELECT DISTINCT Item FROM Test) AS B
ORDER BY B.Item

SET @SQL = '
WITH PivotData AS
(
    SELECT Date, Item, Quantity FROM Test
)
SELECT
    Date, ' + @Columns2 + '
FROM PivotData
PIVOT
(
    SUM(Quantity)
    FOR Item
    IN (' + @Columns + ')
) AS PivotResult
ORDER BY Date'

EXEC(@SQL);

DROP TABLE Test

Result:

Date        Cherry  Mango   Orange
20170101    0       5       6
20170102    9       7       8

Reference (code pic not shown but you can access it if you view source the page) :
http://sqlmag.com/t-sql/pivoting-dynamic-way


问:
How to structure BEM modifiers with nested elements in SASS
SASS + BEM is pretty much a match made in heaven most of the time, but a common struggle of mine is understand how to best define BEM modifiers on an element that affects it's child elements while using SASS parent selectors.

I have the following component defined in SASS using BEM style syntax:

```<code>.card {
  background-color: #FFF;

  &__value {
    font-size: 2em;
    color: #000;
  }
}
</code>```

This works well because of SASS's parent selector. It keeps relevant code organized and self-contained.

But when I need to add a modifier that alters a child element using a parent selector, the idea quickly falls apart:

```<code>.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}
</code>```

Nope. It generates this:

```<code>.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big__value {  // Wrong
  font-size: 3em;
}
</code>```

It would make more sense to somehow get this selector:

```<code>.card--big .card__value {
  font-size: 3em;
}
</code>```

The reason for this, is so you can simply add a modifier to the top level element and have it affect any or all of the child elements.

I've tried a couple approaches:

Use two structures

```<code>.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
}

.card--big {
  padding: 2.5em;

  &__value {
    font-size: 3em;
  }
}
</code>```

This works (especially in this simplified demonstration) but in a more complicated set of components with many modifiers this can be a potential pain to maintain and keep bug free. Also, it would nice to continue to use SASS parent selectors if possible.

Use a variable for the element

```<code>.card {
  $component: &;  // Set the variable here

  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    #{$component}__value {  // Use it here
      font-size: 3em;
    }
  }
}
</code>```

This works well. But it seems kind of silly to have to define the element as a variable. Maybe it's the only real way to do this... I'm not sure. Are there better options to how to structure this?

答: Your solution looks quite fine but you may also try @at-root.</p>

Body:
SASS + BEM is pretty much a match made in heaven most of the time, but a common struggle of mine is understand how to best define BEM modifiers on an element that affects it's child elements while using SASS parent selectors.

I have the following component defined in SASS using BEM style syntax:

.card {
  background-color: #FFF;

  &__value {
    font-size: 2em;
    color: #000;
  }
}

This works well because of SASS's parent selector. It keeps relevant code organized and self-contained.

But when I need to add a modifier that alters a child element using a parent selector, the idea quickly falls apart:

.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    &__value {          // Is this going to work?
      font-size: 3em;
    }
  }
}

Nope. It generates this:

.card {
  padding: 2em;
}
.card__value {
  font-size: 1.5em;
  color: #000;
}
.card--big {
  padding: 2.5em;
}
.card--big__value {  // Wrong
  font-size: 3em;
}

It would make more sense to somehow get this selector:

.card--big .card__value {
  font-size: 3em;
}

The reason for this, is so you can simply add a modifier to the top level element and have it affect any or all of the child elements.

I've tried a couple approaches:

Use two structures

.card {
  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }
}

.card--big {
  padding: 2.5em;

  &__value {
    font-size: 3em;
  }
}

This works (especially in this simplified demonstration) but in a more complicated set of components with many modifiers this can be a potential pain to maintain and keep bug free. Also, it would nice to continue to use SASS parent selectors if possible.

Use a variable for the element

.card {
  $component: &;  // Set the variable here

  padding: 2em;

  &__value {
    font-size: 1.5em;
    color: #000;
  }

  &--big {
    padding: 2.5em;

    #{$component}__value {  // Use it here
      font-size: 3em;
    }
  }
}

This works well. But it seems kind of silly to have to define the element as a variable. Maybe it's the only real way to do this... I'm not sure. Are there better options to how to structure this?


问:
Load image with Picasso when offline using SSL
I actually use Picasso in my project. The problem is : it seem there is not cache so the image are reloading all the time the url (https).

I would like to have the images in the disk cache.
I want the cache of the picture when the image was already downloaded, not depending if the WIFI is off or not.

I have created a class (PicassoTrustAll.class) to get my images from a HTTPS url :

```<code>    public class PicassoTrustAll {

        private static Picasso mInstance = null;

        private PicassoTrustAll(Context context) {
            OkHttpClient client = new OkHttpClient();
            client.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] x509Certificates,
                        String s) throws java.security.cert.CertificateException {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] x509Certificates,
                        String s) throws java.security.cert.CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[] {};
                }
            } };
            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                client.setSslSocketFactory(sc.getSocketFactory());
            } catch (Exception e) {
                e.printStackTrace();
            }

            mInstance = new Picasso.Builder(context)
                    .downloader(new OkHttpDownloader(client))
                    .listener(new Picasso.Listener() {
                        @Override
                        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                            Log.e("PICASSO", String.valueOf(exception));
                        }
                    }).build();

        }

        public static Picasso getInstance(Context context) {
            if (mInstance == null) {
                new PicassoTrustAll(context);
            }
            return mInstance;
        }
}
</code>```

And I use it like this :

```<code>PicassoTrustAll.getInstance(v.getContext())
                .load(image_url)
                .placeholder(R.drawable.progress_animation)
                .into(photo);
</code>```

答:
It's working using OKHTTP :</p>

```<code>Picasso.with(context).load("url")
                        .networkPolicy(NetworkPolicy.OFFLINE)
                        .into(photo, new Callback() {
                            @Override
                            public void onSuccess() {

                            }

                            @Override
                            public void onError() {
                                Picasso.with(context)
                                        .load("url")
                                .placeholder(R.mipmap.ic_launcher)
                                .error(R.drawable.user_error)
                                        .into(picture);
                            }
                        });
</code>```

Body:
I actually use Picasso in my project. The problem is : it seem there is not cache so the image are reloading all the time the url (https).

I would like to have the images in the disk cache.
I want the cache of the picture when the image was already downloaded, not depending if the WIFI is off or not.

I have created a class (PicassoTrustAll.class) to get my images from a HTTPS url :

    public class PicassoTrustAll {

        private static Picasso mInstance = null;

        private PicassoTrustAll(Context context) {
            OkHttpClient client = new OkHttpClient();
            client.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] x509Certificates,
                        String s) throws java.security.cert.CertificateException {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] x509Certificates,
                        String s) throws java.security.cert.CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[] {};
                }
            } };
            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                client.setSslSocketFactory(sc.getSocketFactory());
            } catch (Exception e) {
                e.printStackTrace();
            }

            mInstance = new Picasso.Builder(context)
                    .downloader(new OkHttpDownloader(client))
                    .listener(new Picasso.Listener() {
                        @Override
                        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                            Log.e("PICASSO", String.valueOf(exception));
                        }
                    }).build();

        }

        public static Picasso getInstance(Context context) {
            if (mInstance == null) {
                new PicassoTrustAll(context);
            }
            return mInstance;
        }
}

And I use it like this :

PicassoTrustAll.getInstance(v.getContext())
                .load(image_url)
                .placeholder(R.drawable.progress_animation)
                .into(photo);

Body:
It's working using OKHTTP :

Picasso.with(context).load("url")
                        .networkPolicy(NetworkPolicy.OFFLINE)
                        .into(photo, new Callback() {
                            @Override
                            public void onSuccess() {

                            }

                            @Override
                            public void onError() {
                                Picasso.with(context)
                                        .load("url")
                                .placeholder(R.mipmap.ic_launcher)
                                .error(R.drawable.user_error)
                                        .into(picture);
                            }
                        });


问:
How do I calculate totals based on Dropdown ranges in Google sheets?
This is my table:

```<code>Item | Person | Price
Shoes | John | $25
Clothes | John | $25
Pants | John | $50
Bags | Sarah | $50
Watch | Sarah | $150
Aftershave | John | $15
</code>```

The Person table I have managed to make it a dropdown following a tutorial.

I know want another column called totals that will work out the total based on the user:

```<code>Total Sarah:
Total John:
</code>```

It should dynamically find ALL Sarah for example and update the total. I have tried using sumif but how can I do a sumif if all rows in a selected column match the total

This is my sample sheet:

https://docs.google.com/spreadsheets/d/13MwyK-Suvvg9LfvzFcW-ojL9ilvb5OKCFjQwXgI4h70/edit?usp=sharing

I also tried

=query(sum(B:B,"count * where B ='John'" ,-1)) and

=sum(query(B:B, "select B where B='John'")+query(C:C, "select B,C where B='John'"))

答:
Please clear columns  F:G and in F1:

```<code>=query(A2:C30,"select B, sum(C) group by B")
</code>```

In G9: =sum(G2:G6) and format to suit.

Body:
This is my table:

Item | Person | Price
Shoes | John | $25
Clothes | John | $25
Pants | John | $50
Bags | Sarah | $50
Watch | Sarah | $150
Aftershave | John | $15

The Person table I have managed to make it a dropdown following a tutorial.

I know want another column called totals that will work out the total based on the user:

Total Sarah:
Total John:

It should dynamically find ALL Sarah for example and update the total. I have tried using sumif but how can I do a sumif if all rows in a selected column match the total

This is my sample sheet:

https://docs.google.com/spreadsheets/d/13MwyK-Suvvg9LfvzFcW-ojL9ilvb5OKCFjQwXgI4h70/edit?usp=sharing

I also tried

=query(sum(B:B,"count * where B ='John'" ,-1)) and

=sum(query(B:B, "select B where B='John'")+query(C:C, "select B,C where B='John'"))

Body:
Please clear columns  F:G and in F1:

=query(A2:C30,"select B, sum(C) group by B")

In G9: =sum(G2:G6) and format to suit.


问:
Change the uppercase to lowercase using Perl script
I have the file which has uppercase words, and I need to change them to lower case whole through the file. I have used the below code to change them, but only the first character is getting changed. I would like to change the entire content which is available inside the tag SC (globally).</p>

```<code>$xtx1 =~ s/<sc>(.*?)<\/sc>/\l$1/g;
</code>```

答:
Try the next one</p>

```<code>filePath = 'sample.txt';
# Go line by line and change to lowercase
tmpPath = mkstemp()
with open(tmpPath, 'w') as newFile:
    with open(filePath) as oldFile:
        for line in oldFile:
            # Apply pattern
            tmp = re.sub('^(.*?)\<\/sc\>.*', lambda m: m.group(0).lower(), line)
            newFile.write(tmp)

close(oldFile)
close(newFile)

# Remove original file
remove(filePath)

# Move new file
move(tmpPath, filePath)
</code>```

Body:
I have the file which has uppercase words, and I need to change them to lower case whole through the file. I have used the below code to change them, but only the first character is getting changed. I would like to change the entire content which is available inside the tag SC (globally).

$xtx1 =~ s/<sc>(.*?)<\/sc>/\l$1/g;

Body:
Try the next one

filePath = 'sample.txt';
# Go line by line and change to lowercase
tmpPath = mkstemp()
with open(tmpPath, 'w') as newFile:
    with open(filePath) as oldFile:
        for line in oldFile:
            # Apply pattern
            tmp = re.sub('^(.*?)\<\/sc\>.*', lambda m: m.group(0).lower(), line)
            newFile.write(tmp)

close(oldFile)
close(newFile)

# Remove original file
remove(filePath)

# Move new file
move(tmpPath, filePath)


问:
Separate duplicated code in another function (code optimisation)
I have this function which is calculating product tax rates and it has to take in consideration different taxation rules... The problem is that this code is working but now i wan't to make code optimisation since one part is repeating. If you check closely you will see that foreach ($taxationRules as $taxRule) { is repeated twice, but it has to apply different rule (add or remove taxation rates)

Can you guys please help me out how to properly separate duplicated code if its possible..

One more thing is important here!! All taxation rules must first add taxes and then (in another foreach) remove taxes since there are no taxation rule priorities. That's why i have duplicated the code and not just include $taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'] in first foreach

```<code>private static function getProductTaxRatesByTaxationRules($cartItem) {
    $shippingAddressData = self::$cart['ShippingAddress']['UserAddress'];
    $taxationRules = self::$cart['TaxationRules'];
    $currentUser = LoggedInUser::get();

    // Prepare data to compare with taxation rules
    $regularUser = false;
    if (!$currentUser['is_company']) {
        $regularUser = true;
    }
    $compareData = [
        'regular_user' => $regularUser,
        'company' => $currentUser['is_company'],
        'product_id' => $cartItem['product_id'],
        'subtype_id' => $cartItem['productIndex']['subtype_id'],
        'country_id' => $shippingAddressData['country_id'],
        'country_state_id' => $shippingAddressData['country_state_id']
    ];

    $taxRates = $cartItem['productIndex']['tax_rate'];

    foreach ($taxationRules as $taxRule) {

        if ($taxRule['TaxationRule']['user_type'] == 'regular' && !$compareData['regular_user']) {
            continue;
        }
        if ($taxRule['TaxationRule']['user_type'] == 'companies' && !$compareData['company']) {
            continue;
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product'])) {
            if (!in_array($compareData['product_id'], $taxRule['TaxationRule']['Taxation_rule_product'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
            if (!in_array($compareData['subtype_id'], $taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['TaxationRuleCountryState'])) {
            $found = false;
            foreach ($taxRule['TaxationRule']['TaxationRuleCountryState'] as $countryStates) {
                if (isset($countryStates['country_state_id']) && !is_null($countryStates['country_state_id'])) {
                    if ($countryStates['country_state_id'] == $compareData['country_state_id']) {
                        $found = true;
                    }
                } else {
                    if ($countryStates['country_id'] == $compareData['country_id']) {
                        $found = true;
                    }
                }
            }
            if (!$found) {
                continue;
            }
        }
        // If any of flags aren't true, then add Taxation_rule_enabled_tax_rate and
        // check if there are enabled tax rates that needs to be added
        if (!empty($taxRule['TaxationRule']['Taxation_rule_enabled_tax_rate'])) {
            foreach ($taxRule['TaxationRule']['Taxation_rule_enabled_tax_rate'] as $includeTax) {
                foreach ($taxRule['TaxRate'] as $taxData) {
                    if ($taxData['id'] == $includeTax) {
                        $taxRates[] = array(
                            'id' => $taxData['id'],
                            'value' => $taxData['taxrate']
                        );
                    }
                }
            }
        }
    }

    foreach ($taxationRules as $taxRule) {
        if ($taxRule['TaxationRule']['user_type'] == 'regular' && !$compareData['regular_user']) {
            continue;
        }
        if ($taxRule['TaxationRule']['user_type'] == 'companies' && !$compareData['company']) {
            continue;
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product'])) {
            if (!in_array($compareData['product_id'], $taxRule['TaxationRule']['Taxation_rule_product'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
            if (!in_array($compareData['subtype_id'], $taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['TaxationRuleCountryState'])) {
            $found = false;
            foreach ($taxRule['TaxationRule']['TaxationRuleCountryState'] as $countryStates) {
                if (isset($countryStates['country_state_id']) && !is_null($countryStates['country_state_id'])) {
                    if ($countryStates['country_state_id'] == $compareData['country_state_id']) {
                        $found = true;
                    }
                } else {
                    if ($countryStates['country_id'] == $compareData['country_id']) {
                        $found = true;
                    }
                }
            }
            if (!$found) {
                continue;
            }
        }

        // If any of flags aren't true, then remove Taxation_rule_disabled_tax_rate
        // Check if there are disabled tax rates that needed to be removed
        if (!empty($taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'])) {
            foreach ($taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'] as $excludeTaxId) {
                foreach ($taxRates as $key => $value) {
                    if ($value['id'] == $excludeTaxId) {
                        unset($taxRates[$key]);
                        break;
                    }
                }
            }
        }
    }

    return $taxRates;
}
</code>```

If you need any additional information's please let me know and i will provide. Thank you!

答:
For little comparison parts like in foreach:

```<code>foreach ($taxRule['TaxationRule']['Taxation_rule_product'] as $taxProductId) {
        if ($compareData['product_id'] == $taxProductId) {
            $found = true;
        }
}
</code>```

You can use in_array function, more information can be found at in_array function

Body:
I have this function which is calculating product tax rates and it has to take in consideration different taxation rules... The problem is that this code is working but now i wan't to make code optimisation since one part is repeating. If you check closely you will see that foreach ($taxationRules as $taxRule) { is repeated twice, but it has to apply different rule (add or remove taxation rates)

Can you guys please help me out how to properly separate duplicated code if its possible..

One more thing is important here!! All taxation rules must first add taxes and then (in another foreach) remove taxes since there are no taxation rule priorities. That's why i have duplicated the code and not just include $taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'] in first foreach

private static function getProductTaxRatesByTaxationRules($cartItem) {
    $shippingAddressData = self::$cart['ShippingAddress']['UserAddress'];
    $taxationRules = self::$cart['TaxationRules'];
    $currentUser = LoggedInUser::get();

    // Prepare data to compare with taxation rules
    $regularUser = false;
    if (!$currentUser['is_company']) {
        $regularUser = true;
    }
    $compareData = [
        'regular_user' => $regularUser,
        'company' => $currentUser['is_company'],
        'product_id' => $cartItem['product_id'],
        'subtype_id' => $cartItem['productIndex']['subtype_id'],
        'country_id' => $shippingAddressData['country_id'],
        'country_state_id' => $shippingAddressData['country_state_id']
    ];

    $taxRates = $cartItem['productIndex']['tax_rate'];

    foreach ($taxationRules as $taxRule) {

        if ($taxRule['TaxationRule']['user_type'] == 'regular' && !$compareData['regular_user']) {
            continue;
        }
        if ($taxRule['TaxationRule']['user_type'] == 'companies' && !$compareData['company']) {
            continue;
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product'])) {
            if (!in_array($compareData['product_id'], $taxRule['TaxationRule']['Taxation_rule_product'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
            if (!in_array($compareData['subtype_id'], $taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['TaxationRuleCountryState'])) {
            $found = false;
            foreach ($taxRule['TaxationRule']['TaxationRuleCountryState'] as $countryStates) {
                if (isset($countryStates['country_state_id']) && !is_null($countryStates['country_state_id'])) {
                    if ($countryStates['country_state_id'] == $compareData['country_state_id']) {
                        $found = true;
                    }
                } else {
                    if ($countryStates['country_id'] == $compareData['country_id']) {
                        $found = true;
                    }
                }
            }
            if (!$found) {
                continue;
            }
        }
        // If any of flags aren't true, then add Taxation_rule_enabled_tax_rate and
        // check if there are enabled tax rates that needs to be added
        if (!empty($taxRule['TaxationRule']['Taxation_rule_enabled_tax_rate'])) {
            foreach ($taxRule['TaxationRule']['Taxation_rule_enabled_tax_rate'] as $includeTax) {
                foreach ($taxRule['TaxRate'] as $taxData) {
                    if ($taxData['id'] == $includeTax) {
                        $taxRates[] = array(
                            'id' => $taxData['id'],
                            'value' => $taxData['taxrate']
                        );
                    }
                }
            }
        }
    }

    foreach ($taxationRules as $taxRule) {
        if ($taxRule['TaxationRule']['user_type'] == 'regular' && !$compareData['regular_user']) {
            continue;
        }
        if ($taxRule['TaxationRule']['user_type'] == 'companies' && !$compareData['company']) {
            continue;
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product'])) {
            if (!in_array($compareData['product_id'], $taxRule['TaxationRule']['Taxation_rule_product'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
            if (!in_array($compareData['subtype_id'], $taxRule['TaxationRule']['Taxation_rule_product_subtype'])) {
                continue;
            }
        }
        if (!empty($taxRule['TaxationRule']['TaxationRuleCountryState'])) {
            $found = false;
            foreach ($taxRule['TaxationRule']['TaxationRuleCountryState'] as $countryStates) {
                if (isset($countryStates['country_state_id']) && !is_null($countryStates['country_state_id'])) {
                    if ($countryStates['country_state_id'] == $compareData['country_state_id']) {
                        $found = true;
                    }
                } else {
                    if ($countryStates['country_id'] == $compareData['country_id']) {
                        $found = true;
                    }
                }
            }
            if (!$found) {
                continue;
            }
        }

        // If any of flags aren't true, then remove Taxation_rule_disabled_tax_rate
        // Check if there are disabled tax rates that needed to be removed
        if (!empty($taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'])) {
            foreach ($taxRule['TaxationRule']['Taxation_rule_disabled_tax_rate'] as $excludeTaxId) {
                foreach ($taxRates as $key => $value) {
                    if ($value['id'] == $excludeTaxId) {
                        unset($taxRates[$key]);
                        break;
                    }
                }
            }
        }
    }

    return $taxRates;
}

If you need any additional information's please let me know and i will provide. Thank you!

Body:
For little comparison parts like in foreach:

foreach ($taxRule['TaxationRule']['Taxation_rule_product'] as $taxProductId) {
        if ($compareData['product_id'] == $taxProductId) {
            $found = true;
        }
}

You can use in_array function, more information can be found at in_array function


问:
Null values in access vb.net
When I try getting data from Access db And there is actually an empty cell, vs gives me an error . I already tried "tostring()" method but It made thing more complicated

code:

```<code>     While reader.Read
        txtname.Text = reader.GetString(4)
        txtnotes.Text = reader.GetString(5)
    End While
</code>```

Help would be appreciated.

答:
```<code>While reader.Read
    txtname.Text = If(String.IsNullOrEmpty(reader.GetString(4)), "", reader.GetString(4))
    txtnotes.Text = If(String.IsNullOrEmpty(reader.GetString(5)), "", reader.GetString(5))
End While
</code>```

Title: Null values in access vb.net

Body:
When I try getting data from Access db And there is actually an empty cell, vs gives me an error . I already tried "tostring()" method but It made thing more complicated

code:

     While reader.Read
        txtname.Text = reader.GetString(4)
        txtnotes.Text = reader.GetString(5)
    End While

Help would be appreciated.