问:
How to read a sequence of integers from Standard-input with Stdin?
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

```<code>$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1
</code>```

I've tried to convert the Integers to an array

```<code>int[] n = StdIn.readAllInts();
</code>```

but it doesn't work when tried to print it out.
can anybody give me some tips?

答:
Sample program below, this removes the duplicate entries but still retains the order.

```<code>   public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 ");
    String input = sc.nextLine();
    String[] numbers = input.split("\\s+");

    List<String> result = new ArrayList<>();
    for (int x = 0; x < numbers.length; x++) {
        String item = numbers[x];
        if (result.contains(item)) continue;
        result.add(item);
    }
    System.out.println(String.join(" ", result));
}
</code>```

And output sample is:

```<code>Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5
1 1 2 2 1 1 1 3 4 1 1 1 11 11 12 12 1 1 6 6 2 1 //sequence entered
1 2 3 4 11 12 6 // sample result
</code>```

Body:
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1

I've tried to convert the Integers to an array

int[] n = StdIn.readAllInts();

but it doesn't work when tried to print it out.
can anybody give me some tips?

Body:
Sample program below, this removes the duplicate entries but still retains the order.

   public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 ");
    String input = sc.nextLine();
    String[] numbers = input.split("\\s+");

    List<String> result = new ArrayList<>();
    for (int x = 0; x < numbers.length; x++) {
        String item = numbers[x];
        if (result.contains(item)) continue;
        result.add(item);
    }
    System.out.println(String.join(" ", result));
}

And output sample is:

Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5
1 1 2 2 1 1 1 3 4 1 1 1 11 11 12 12 1 1 6 6 2 1 //sequence entered
1 2 3 4 11 12 6 // sample result


来源: stackexchange

问:
Regex \b followed by symbol in Keyboard Maestro
I'm sure there's a really simple answer to this, but I can't find it!

In Keyboard Maestro, I'm trying to set the trigger as a regular expression of semicolon followed by one of a few characters, like this:

```<code>;[.,\s]
</code>```

When I put it like that, it works, but I only want the trigger to fire when the semicolon is on its own (at the beginning of a sentence, or after a space). I would think this would do the trick:

```<code>\b;[,.\s]
</code>```

...but when I put the boundary character in, it doesn't work. What am I doing wrong? Thanks!

(I should add that the boundary character works fine when followed by an alphanumeric character, so it seems to just be an issue with symbols)

答:
You should use the opposite construct as there is no word boundary between a space or start of string and a semi-colon:

```<code>\B;[,.\s]
^^
</code>```

Here, \B is a non-word boundary that matches at all the locations where a word boundary does not match. In this specific case, ; will be matches only at the start of the string or if preceded with a non-word char (any char other than a letter/digit/_ and, depending on the regex library, other (very rare) chars that are consider "word" chars.

ContentLicense: CC BY-SA 3.0

Body:
I'm sure there's a really simple answer to this, but I can't find it!

In Keyboard Maestro, I'm trying to set the trigger as a regular expression of semicolon followed by one of a few characters, like this:

;[.,\s]

When I put it like that, it works, but I only want the trigger to fire when the semicolon is on its own (at the beginning of a sentence, or after a space). I would think this would do the trick:

\b;[,.\s]

...but when I put the boundary character in, it doesn't work. What am I doing wrong? Thanks!

(I should add that the boundary character works fine when followed by an alphanumeric character, so it seems to just be an issue with symbols)

Body:
You should use the opposite construct as there is no word boundary between a space or start of string and a semi-colon:

\B;[,.\s]
^^

Here, \B is a non-word boundary that matches at all the locations where a word boundary does not match. In this specific case, ; will be matches only at the start of the string or if preceded with a non-word char (any char other than a letter/digit/_ and, depending on the regex library, other (very rare) chars that are consider "word" chars.


问:
Parser in C#. How to populate a class from strings
I'm trying to do a simple parser that receive an array and return a class with populated members.

I have the following class implementing the following interface.

```<code>    public class ReturnedObject : IReturnedObject
{
        public string Source { get; set; }
        public string Destination { get; set; }
}

    public interface IReturnedObject
{
        string Source { get; set; }
        string Destination { get; set; }
}
</code>```

If for example I receive the following line:

command -source value1 -destination value2

I would like to be able to associate the source value and the destination value.

The main method look like this:

```<code>        private static IReturnedObject Parse<T>(string[] userArgs, ICommandesUtils commandUtils) where T : IReturnedObject, new()
    {
    //userArgs contains the folling array
    //command
    //-source
    //value1
    //-destination
    //value2

    //some work...

    IReturnedObject returnedObject = new T();

    returnedObject.Source = userArgs[2];
    returnedObject.Destination = userArgs[4];
    }
</code>```

What i'm looking for is a way to replace the two following lines :

```<code>returnedObject.Source = userArgs[2];
returnedObject.Destination = userArgs[4];
</code>```

I want to do something like:

For each member of the class returnedObject

Look the name of the member (for example, "Destination")

Find in the userArgs the good value to assiociate (the one after "-destination" in this example)

Associate the value.

Is that possible ?
Thank you by advance :)

答:
Try out Go Commando - http://mookid.dk/oncode/gocommando

```<code>Install-Package GoCommando
</code>```

Code:

```<code>class Program
{
    static void Main()
    {
        Go.Run();
    }
}

[Command("do-stuff")]
[Description("I've no idea what we're doing")]
public class WhiteRussian : ICommand
{
    [Parameter("Source")]
    public double Source { get; set; }

    [Parameter("Destination")]
    public double Destination { get; set; }

    public void Run()
    {
        // Do stuff with Source and Destination.
    }
}
</code>```

Then run

```<code>stuff.exe do-stuff -source ketchup -destination italy
</code>```

Body:
I'm trying to do a simple parser that receive an array and return a class with populated members.

I have the following class implementing the following interface.

    public class ReturnedObject : IReturnedObject
{
        public string Source { get; set; }
        public string Destination { get; set; }
}

    public interface IReturnedObject
{
        string Source { get; set; }
        string Destination { get; set; }
}

If for example I receive the following line:

command -source value1 -destination value2

I would like to be able to associate the source value and the destination value.

The main method look like this:

        private static IReturnedObject Parse<T>(string[] userArgs, ICommandesUtils commandUtils) where T : IReturnedObject, new()
    {
    //userArgs contains the folling array
    //command
    //-source
    //value1
    //-destination
    //value2

    //some work...

    IReturnedObject returnedObject = new T();

    returnedObject.Source = userArgs[2];
    returnedObject.Destination = userArgs[4];
    }

What i'm looking for is a way to replace the two following lines :

returnedObject.Source = userArgs[2];
returnedObject.Destination = userArgs[4];

I want to do something like:

For each member of the class returnedObject

Look the name of the member (for example, "Destination")

Find in the userArgs the good value to assiociate (the one after "-destination" in this example)

Associate the value.

Is that possible ?
Thank you by advance :)

Body:
Try out Go Commando - http://mookid.dk/oncode/gocommando

Install-Package GoCommando

Code:

class Program
{
    static void Main()
    {
        Go.Run();
    }
}

[Command("do-stuff")]
[Description("I've no idea what we're doing")]
public class WhiteRussian : ICommand
{
    [Parameter("Source")]
    public double Source { get; set; }

    [Parameter("Destination")]
    public double Destination { get; set; }

    public void Run()
    {
        // Do stuff with Source and Destination.
    }
}

Then run

stuff.exe do-stuff -source ketchup -destination italy


问:
Convert repeating decimal to fraction
I am using a button on a JavaScript scientific calculator to convert decimal to fractions via this code:

```<code>$('#button-frac').click(function(){
var factor;

    // Finds the highest common factor of 2 numbers
    function highestCommonFactor() {
        for (factor = numerator; factor > 0; factor--) {
            if ((numerator % factor == 0) && (denominator % factor == 0)) {
                return factor;
            }
        }
    }

    // Enter a decimal to convert to a fraction
    var decimal = this.form.display.value;

    // Split the decimal
    var decimalArray = decimal.split(".");

    var leftDecimalPart = decimalArray[0];
    var rightDecimalPart = decimalArray[1];

    // Save decimal part only for later use
    var decimalOnly = "0." + rightDecimalPart;

    // Find the decimal multiplier
    var multiplier = "1";

    for (var i = 0; i < rightDecimalPart.length; i++) {
        multiplier += "0";
    }

    // Create numerator by multiplying the multiplier and decimal part together
    var numerator = Number(multiplier) * Number(decimalOnly);

    var denominator = multiplier;

    // Find the highest common factor for the numerator and denominator
    highestCommonFactor();

    // Simplify the fraction by dividing the numerator and denominator by the factor
    var numerator = Number(numerator) / Number(factor);
    var denominator = Number(denominator) / Number(factor);

    // Output as a mixed number fraction (depending on input)
    var mixedNumber = leftDecimalPart + " " + numerator + "/" + denominator;

    // Output as a proper fraction or improper fraction (depending on input)
    var numerator = numerator + (leftDecimalPart * denominator);
    var fraction = numerator + "/" + denominator;

    // Display solution in input #disp
    $('#disp').val(fraction);
});
</code>```

This works well, but if the decimal is non-terminating and repeating the script crashes. Any idea how I might remedy this problem? Perhaps there's a way to check if a decimal repeats and to determine the length of the string that repeats, then take that string and express it over a number with equal number of digits, all 9s? Being relatively new to JavaScript, I am at a loss.

答:
Use this and round the decimal after at most 20 repeated chars.

```<code>Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}
</code>```

Call it with Math.fraction(2.56)

It will:

return NaN if the input is not a number

return undefined if the input is undefined

reduce the fraction

return a string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator)

Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers.

Test it here

Title: Convert repeating decimal to fraction

Body:
I am using a button on a JavaScript scientific calculator to convert decimal to fractions via this code:

$('#button-frac').click(function(){
var factor;

    // Finds the highest common factor of 2 numbers
    function highestCommonFactor() {
        for (factor = numerator; factor > 0; factor--) {
            if ((numerator % factor == 0) && (denominator % factor == 0)) {
                return factor;
            }
        }
    }

    // Enter a decimal to convert to a fraction
    var decimal = this.form.display.value;

    // Split the decimal
    var decimalArray = decimal.split(".");

    var leftDecimalPart = decimalArray[0];
    var rightDecimalPart = decimalArray[1];

    // Save decimal part only for later use
    var decimalOnly = "0." + rightDecimalPart;

    // Find the decimal multiplier
    var multiplier = "1";

    for (var i = 0; i < rightDecimalPart.length; i++) {
        multiplier += "0";
    }

    // Create numerator by multiplying the multiplier and decimal part together
    var numerator = Number(multiplier) * Number(decimalOnly);

    var denominator = multiplier;

    // Find the highest common factor for the numerator and denominator
    highestCommonFactor();

    // Simplify the fraction by dividing the numerator and denominator by the factor
    var numerator = Number(numerator) / Number(factor);
    var denominator = Number(denominator) / Number(factor);

    // Output as a mixed number fraction (depending on input)
    var mixedNumber = leftDecimalPart + " " + numerator + "/" + denominator;

    // Output as a proper fraction or improper fraction (depending on input)
    var numerator = numerator + (leftDecimalPart * denominator);
    var fraction = numerator + "/" + denominator;

    // Display solution in input #disp
    $('#disp').val(fraction);
});

This works well, but if the decimal is non-terminating and repeating the script crashes. Any idea how I might remedy this problem? Perhaps there's a way to check if a decimal repeats and to determine the length of the string that repeats, then take that string and express it over a number with equal number of digits, all 9s? Being relatively new to JavaScript, I am at a loss.

Body:
Use this and round the decimal after at most 20 repeated chars.

Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}

Call it with Math.fraction(2.56)

It will:

return NaN if the input is not a number

return undefined if the input is undefined

reduce the fraction

return a string (use Math.fraction(2.56).split("/") for an array containing the numerator and denominator)

Please note that this uses the deprecated arguments.callee, and thus may be incompatible in some browsers.

Test it <a href="https://ayunami2000.github.io/?html=&css=&js=TWF0aC5mcmFjdGlvbj1mdW5jdGlvbih4KXsKcmV0dXJuIHg/K3g/eC50b1N0cmluZygpLmluY2x1ZGVzKCIuIik/eC50b1N0cmluZygpLnJlcGxhY2UoIi4iLCIiKS8oZnVuY3Rpb24oYSxiKXtyZXR1cm4gYj9hcmd1bWVudHMuY2FsbGVlKGIsYSViKTphO30pKHgudG9TdHJpbmcoKS5yZXBsYWNlKCIuIiwiIiksIjEiKyIwIi5yZXBlYXQoeC50b1N0cmluZygpLnNwbGl0KCIuIilbMV0ubGVuZ3RoKSkrIi8iKygiMSIrIjAiLnJlcGVhdCh4LnRvU3RyaW5nKCkuc3BsaXQoIi4iKVsxXS5sZW5ndGgpKS8oZnVuY3Rpb24oYSxiKXtyZXR1cm4gYj9hcmd1bWVudHMuY2FsbGVlKGIsYSViKTphO30pKHgudG9TdHJpbmcoKS5yZXBsYWNlKCIuIiwiIiksIjEiKyIwIi5yZXBlYXQoeC50b1N0cmluZygpLnNwbGl0KCIuIilbMV0ubGVuZ3RoKSk6eCsiLzEiOk5hTjp2b2lkIDA7Cn0KCmFsZXJ0KE1hdGguZnJhY3Rpb24od2luZG93LnByb21wdCgiZW50ZXIgZGVjaW1hbCIpKSk7&tab=3" rel="nofollow noreferrer">here


问:
How do I mirror Github page for local browsing?
Let's say I have an internal web server (nginx) and I want it to serve a page with the content of the GITHUB repository, e.g. https://github.com/vibranze/test. Page from the repository must be served locally.

I've tried the article from https://help.github.com/articles/duplicating-a-repository/ but the synced repository is not browseable due to no index file.

How do I make the local repo browseable internally and looks exactly the same like what its master copy in github.com or if I've done it wrongly, what's the correct way to achieve it?

Any pointer or advice are greatly appreciated.

Thank you.

答:
Short answer:

You need a local Git server which hosts a clone of your example repository from GitHub.

If your local Git server includes a web UI, you can probably see something similar like what you see on GitHub.

If you want future changes in the GitHub repo in your local repo as well, you need to pull periodically from the GitHub repo to your local repo.

Long version:

1. Hosting Git repos on your local server

There are a lot of options (paid and free) for running a Git server on your own machine.

Some of them contain web UIs which look similar (but not exactly the same) like GitHub.

There's only one option to get 100% the same look: by spending money for a private installation of GitHub (but it's not cheap).

If you don't want to spend that much, there are free alternatives, for example GitLab. This is a hosted service like GitHub, but the code is open source and you can install a free version on your local server.

Here's an example of a "repository overview" page:

https://gitlab.com/gitlab-org/gitlab-shell

GitLab is only one example, there's a lot more - just google for "self hosted git" and you will find plenty.

2. Getting a clone of the repository from GitHub to your local server

To set this up, clone the repo from Github to your local machine once with the --mirror option:

```<code>git clone --mirror https://github.com/user/repo some/local/path
</code>```

To update your local repo with the newest changes from GitHub, you need to run git remote update periodically.

Body:
Short answer:

You need a local Git server which hosts a clone of your example repository from GitHub.

If your local Git server includes a web UI, you can probably see something similar like what you see on GitHub.

If you want future changes in the GitHub repo in your local repo as well, you need to pull periodically from the GitHub repo to your local repo.

Long version:

1. Hosting Git repos on your local server

There are a lot of options (paid and free) for running a Git server on your own machine.

Some of them contain web UIs which look similar (but not exactly the same) like GitHub.

There's only one option to get 100% the same look: by spending money for a private installation of GitHub (but it's not cheap).

If you don't want to spend that much, there are free alternatives, for example GitLab. This is a hosted service like GitHub, but the code is open source and you can install a free version on your local server.

Here's an example of a "repository overview" page:

https://gitlab.com/gitlab-org/gitlab-shell

GitLab is only one example, there's a lot more - just google for "self hosted git" and you will find plenty.

2. Getting a clone of the repository from GitHub to your local server

To set this up, clone the repo from Github to your local machine once with the --mirror option:

git clone --mirror https://github.com/user/repo some/local/path

To update your local repo with the newest changes from GitHub, you need to run git remote update periodically.


问:
Using JACOB SafeArray getDoubles() method
I'm trying to extract from an Excel Workbook a vector of double values.
Excel looks like does not return a unidimensional array, but a multidimensional one (number of dimensions is 2).

The data I have from Excel is in SafeArray format (I can have Variant too, but it's basically the same problem).

I'm looking for a fast way to extract the doubles array into a Java object, without needing to loop all the values in the SafeArray.

Looking at the methods in SafeArray there is this one:
getDoubles(int sa_idx, int nelems, double[] ja, int ja_start)

Obviously documentation is null, and I can't make up my mind of what this method does, since trying to use it gave me no results.

Thanks.

答:
I'm assuming here your data comes from a spreadsheet (Range object), not VBA code.

In that case, Excel will hand you a SafeArray of Variants (Variant() in VBA terminology), not a SafeArray of doubles (Double()), no matter what the contents of the cells happen to be. And you are correct that the array will always be two-dimensional (or it will return a single Variant if the range size is exactly 1x1).

I'm not familiar with JACOB, and yes, the documentation looks rather lacking. Could it be that getDoubles() only works when the SafeArray is a SafeArray of Doubles? Did you try to use getVariants()? If you get something back we'll know we're on the right track.

Keep in mind that performance-wise, you are stuck. somebody (you or the library) is going to have to write that loop. The Variants won't magically become doubles; someone will have to loop through the array, call Win32 VariantChangeType() or an equivalent method, extract the double field from the Variant (apparently in JACOB you call changeType() then getDouble()), and finally put the results in a Java double array. Whether JACOB will do this for you or you have to do it yourself, I have no idea.

Not being familiar with JACOB I'm not sure I I'm making sense, but I hope this helps. Good luck.

[PS:]

I feel I need to clarify that comment on calling VariantChangeType(). This is technically optional, but I find it generally healthy to explicitly convert variants to the data type I'm interested in via VariantChangeType() or an equivalent method. It's too easy for numbers to be stored as strings or something else, particularly when the source is something as free-form as Excel. This API call is exactly what VB/VBA calls when you use a function like CDbl(). Be aware that a bit of errant formatting is all it takes for you to be provided with a DATE instead of a Double.

If you are absolutely, positive beyond sure that all the cells will contain numbers (doubles) and Excel will never return to you anything else, then by all means call JACOB's getDouble() directly and skip the conversion step.

ContentLicense: CC BY-SA 2.5


问:
How to deploy singleton legacy code in EJB to be instantiated multiple times?
We have a legacy validation framework that is singleton only and can not be used in a multi threaded way. We would like to instantiate multiple instances of singletons in stateless EJB's to speed up batch processing of files, however we are legally not allowed to change the source code of said framework.

Is there any workaround here to solve this problem? Thanks!

EDIT: Lots of subclasses in this framework are using singletons as well as static attributes, so no multi threading possible :-/

答:
Need more details about this legacy framework, but there is no relationship between singleton objects and multithreading performance. If this objects are stateless, you can process your files in paralel with no performance problems.

So, if you, for example, implement a Message Queue and Message Driven Beans, each process will be a MDB instance that will work at the same time. Work with threads API directly on server is not good.


问:
how JVM handel internally if two user defined class loader loads same class?
How JVM managing internally

If load same version of class loads in two different user defined class loader?

2 . If load different version of class loads in two different user defined class loader (same class name and package). If JVM loads both classes which will be referred in my application.

We know JVM loads the class in the combination of class, package & Klass loader.

I want to know how internally JVM handle these situations.

答:
JVM treats them as different classes. The metadata of different classloaders is isolated, so it does not matter whether the classes have the same name or not.

Each ClassLoader has its own Metachunk to store class metadata.


问:
Get a data from app-root to component
```<code><body>
  <app-root data="myData"></app-root>
</body>
</code>```

I need to retrieve myData that I will manually add at index.html and use it into a component.

How can I retrieve this data?

Thanks.

答:
I believe this answer has what you need:

https://stackoverflow.com/a/43544999/3581932

Use @Attribute (for Angular 4)

index.html :

```<code><my-app myAttribute="myAttributeValue">
    <div>Loading...</div>
</my-app>
</code>```

app.component.ts :

```<code>@Component({
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']
})
export class AppComponent {
    constructor(private elementRef:ElementRef) {
        let myAttribute = this.elementRef.nativeElement.getAttribute('myAttribute');
    }
}
</code>```

[Copied directly from above post]

Title: Get a data from app-root to component

Body:
  <app-root data="myData"></app-root>

I need to retrieve myData that I will manually add at index.html and use it into a component.

How can I retrieve this data?

Thanks.

Body:
I believe this answer has what you need:

https://stackoverflow.com/a/43544999/3581932

Use @Attribute (for Angular 4)

index.html :

<my-app myAttribute="myAttributeValue">
    <div>Loading...</div>
</my-app>

app.component.ts :

@Component({
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']
})
export class AppComponent {
    constructor(private elementRef:ElementRef) {
        let myAttribute = this.elementRef.nativeElement.getAttribute('myAttribute');
    }
}

[Copied directly from above post]


问:
Given a list of coefficients, create a polynomial
I want to create a polynomial with given coefficients. This seems very simple but what I have found till now did not appear to be the thing I desired.
For example in such an environment;

```<code>n = 11
K = GF(4,'a')
R = PolynomialRing(GF(4,'a'),"x")
x = R.gen()
a = K.gen()
v = [1,a,0,0,1,1,1,a,a,0,1]
</code>```

Given a list/vector v of length n (I will set this n and v at the begining), I want to get the polynomial v(x) as v[i]*x^i.
(Actually after that I am going to build the quotient ring GF(4,'a')[x] /< x^n-v(x) > after getting this v(x) from above) then I will say;

```<code>S = R.quotient(x^n-v(x), 'y')
y = S.gen()
</code>```

But I couldn't write it.

答:
Basically (that is, ignoring the specifics of your polynomial ring) you have a list/vector v of length n and you require a polynomial which is the sum of all v[i]*x^i. Note that this sum equals the matrix product V.X where V is a one row matrix (essentially equal to the vector v) and X is a column matrix consisting of powers of x. In Maxima you could write

v: [1,a,0,0,1,1,1,a,a,0,1]$
n: length(v)$
V: matrix(v)$
X: genmatrix(lambda([i,j], x^(i-1)), n, 1)$
V.X;

The output is

x^10+ax^8+ax^7+x^6+x^5+x^4+a*x+1

Body:
I want to create a polynomial with given coefficients. This seems very simple but what I have found till now did not appear to be the thing I desired.
For example in such an environment;

n = 11
K = GF(4,'a')
R = PolynomialRing(GF(4,'a'),"x")
x = R.gen()
a = K.gen()
v = [1,a,0,0,1,1,1,a,a,0,1]

Given a list/vector v of length n (I will set this n and v at the begining), I want to get the polynomial v(x) as v[i]*x^i.
(Actually after that I am going to build the quotient ring GF(4,'a')[x] /< x^n-v(x) > after getting this v(x) from above) then I will say;

S = R.quotient(x^n-v(x), 'y')
y = S.gen()

But I couldn't write it.


问:
RegEx for matching UK Postcodes
I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:

Matches

CW3 9SS

SE5 0EG

SE50EG

se5 0eg

WC2H 7LT

No Match

aWC2H 7LT

WC2H 7LTa

WC2H

How do I solve this problem?

答:
What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.

Here is what I've come up with for a good regex:

```<code>^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$
</code>```

OwnerDisplayName: Kieran Benton

ContentLicense: CC BY-SA 4.0

Title: RegEx for matching UK Postcodes

Body:
What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.

Here is what I've come up with for a good regex:

^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$


问:
schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring- beans-4.1.5.xsd
I get an error in spring-dispatcher.xml in eclipse as given below.

```<code>schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-
 beans-4.1.5.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root
 element of the document is not <xsd:schema>.
</code>```

I have latest spring libraries...

```<code>spring-beans-4.1.5.RELEASE.jar
spring-beans-4.1.5.RELEASE-javadoc.jar
spring-beans-4.1.5.RELEASE-sources.jar
spring-context-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE-javadoc.jar
spring-context-4.1.5.RELEASE-sources.jar
spring-context-support-4.1.5.RELEASE.jar
spring-context-support-4.1.5.RELEASE-javadoc.jar
spring-context-support-4.1.5.RELEASE-sources.jar
spring-webmvc-4.1.5.RELEASE.jar
spring-webmvc-4.1.5.RELEASE-javadoc.jar
spring-webmvc-4.1.5.RELEASE-sources.jar
spring-webmvc-portlet-4.1.5.RELEASE.jar
spring-webmvc-portlet-4.1.5.RELEASE-javadoc.jar
spring-webmvc-portlet-4.1.5.RELEASE-sources.jar
</code>```

spring-dispatcher.xml as given below...

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE beans>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.5.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</code>```

It would be great if I get some help... The posts with same subject did not help me to resolve this.Thanks in advance...

答:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

```<code><mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements
</code>```

in my spring configuration file i had these two urls

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
</code>```

in xsi:schemaLocation, which i replaced with

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
</code>```

Actually visit these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd as shown above.

In my opinion specifying version no explicitly is a good practice.
It worked for me, hope this works for you too.
Thank you.

Body:
I get an error in spring-dispatcher.xml in eclipse as given below.

schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-
 beans-4.1.5.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root
 element of the document is not <xsd:schema>.

I have latest spring libraries...

spring-beans-4.1.5.RELEASE.jar
spring-beans-4.1.5.RELEASE-javadoc.jar
spring-beans-4.1.5.RELEASE-sources.jar
spring-context-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE-javadoc.jar
spring-context-4.1.5.RELEASE-sources.jar
spring-context-support-4.1.5.RELEASE.jar
spring-context-support-4.1.5.RELEASE-javadoc.jar
spring-context-support-4.1.5.RELEASE-sources.jar
spring-webmvc-4.1.5.RELEASE.jar
spring-webmvc-4.1.5.RELEASE-javadoc.jar
spring-webmvc-4.1.5.RELEASE-sources.jar
spring-webmvc-portlet-4.1.5.RELEASE.jar
spring-webmvc-portlet-4.1.5.RELEASE-javadoc.jar
spring-webmvc-portlet-4.1.5.RELEASE-sources.jar

spring-dispatcher.xml as given below...

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE beans>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.5.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

It would be great if I get some help... The posts with same subject did not help me to resolve this.Thanks in advance...

Body:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements

in my spring configuration file i had these two urls

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd

in xsi:schemaLocation, which i replaced with

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

Actually visit these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd as shown above.

In my opinion specifying version no explicitly is a good practice.
It worked for me, hope this works for you too.
Thank you.


问:
nodemon - app crashed - waiting for file changes before starting
I just started learning Node.js. The idea of this small application is to use express and mongosse to store some users in a based cloud database (mongoDB via mlab).

I have two seperate files :

User.js (models/User.js)

```<code>var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : string ,
   pwd : string

});
</code>```

server.js (dossier root)

```<code>var express = require('express')
var cors = require('cors')
var bparser = require('body-parser')
var mongoose = require('mongoose')

var User = require('./models/User.js')

var app = express()

app.use(cors())
app.use(bparser.json())

app.post('/register', (req,res) => {
    userData = req.body;
    var user = new User(userData);

    user.save((err, result) => {
        if(err) console.log('IL YA UNE ERREUR')
        result.sendStatus(200);
    })

})

mongoose.connect('mongodb://user:pwd@ds261755.mlab.com:61755/myapp', { useMongoClient: true } , (erreur) => {
    if(!erreur)
    console.log('Connexion etablie');
})

app.listen(3000)
</code>```

When I execute : nodemon server.js, I get the error below:

```<code>D:\Bureau\MEAN\appBackend\models\User.js:5
   email : string ,
           ^

ReferenceError: string is not defined
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\models\User.js:5:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\server.js:6:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

Do you have any idea about this error?

答:
Mongoose expects you to specify types using the built-in constructor functions, which are named with capital letters, e.g. String, Number, Boolean, etc.

```<code>var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : String ,
   pwd : String

});
</code>```

Body:
I just started learning Node.js. The idea of this small application is to use express and mongosse to store some users in a based cloud database (mongoDB via mlab).

I have two seperate files :

User.js (models/User.js)

var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : string ,
   pwd : string

});

server.js (dossier root)

var express = require('express')
var cors = require('cors')
var bparser = require('body-parser')
var mongoose = require('mongoose')

var User = require('./models/User.js')

var app = express()

app.use(cors())
app.use(bparser.json())

app.post('/register', (req,res) => {
    userData = req.body;
    var user = new User(userData);

    user.save((err, result) => {
        if(err) console.log('IL YA UNE ERREUR')
        result.sendStatus(200);
    })

})

mongoose.connect('mongodb://user:pwd@ds261755.mlab.com:61755/myapp', { useMongoClient: true } , (erreur) => {
    if(!erreur)
    console.log('Connexion etablie');
})

app.listen(3000)

When I execute : nodemon server.js, I get the error below:

D:\Bureau\MEAN\appBackend\models\User.js:5
   email : string ,
           ^

ReferenceError: string is not defined
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\models\User.js:5:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Bureau\MEAN\appBackend\server.js:6:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
[nodemon] app crashed - waiting for file changes before starting...

Do you have any idea about this error?

Body:
Mongoose expects you to specify types using the built-in constructor functions, which are named with capital letters, e.g. String, Number, Boolean, etc.

var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

   email : String ,
   pwd : String

});


问:
Java: Convert String to TimeStamp
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd and I want to change it to the format of yyyy-MM-dd HH:mm:ss.SSS. So, I use this code:

```<code>final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;

final DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
final Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);

final Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
</code>```

and I get the following result.

2009-10-20 00:00:00.000

2009-10-20 00:00:00.0

but when I try to simply do

```<code>final String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);
</code>```

I get the right result:

2011-10-02 18:48:05.123

Do you know what I might be doing wrong?

Thanks for the help.

答:
I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.

Depending on your situation an exact requirements, there are two natural replacements for Timestamp:

Instant is a point on the time-line. For most purposes I would consider it safest to use this. An Instant is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.

LocalDateTime is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).

A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant or a LocalDateTime into your database column of datatype timestamp. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time or JSR-310.

It’s easiest to convert your string to LocalDateTime, so let’s take that first:

```<code>    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    String text = "2011-10-02 18:48:05.123";
    LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
    System.out.println(dateTime);
</code>```

This prints

```<code>2011-10-02T18:48:05.123
</code>```

If your string was in yyyy-MM-dd format, instead do:

```<code>    String text = "2009-10-20";
    LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
    System.out.println(dateTime);
</code>```

This prints

```<code>2009-10-20T00:00
</code>```

Or still better, take the output from LocalDate.parse() and store it into a database column of datatype date.

In both cases the procedure for converting from a LocalDateTime to an Instant is:

```<code>    Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    System.out.println(ts);
</code>```

I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:

```<code>    Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();
</code>```

Title: Java: Convert String to TimeStamp

Body:
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd and I want to change it to the format of yyyy-MM-dd HH:mm:ss.SSS. So, I use this code:

final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;

final DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
final Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);

final Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);

and I get the following result.

2009-10-20 00:00:00.000

2009-10-20 00:00:00.0

but when I try to simply do

final String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);

I get the right result:

2011-10-02 18:48:05.123

Do you know what I might be doing wrong?

Thanks for the help.

Body:
I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.

Depending on your situation an exact requirements, there are two natural replacements for Timestamp:

Instant is a point on the time-line. For most purposes I would consider it safest to use this. An Instant is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.

LocalDateTime is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).

A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant or a LocalDateTime into your database column of datatype timestamp. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time or JSR-310.

It’s easiest to convert your string to LocalDateTime, so let’s take that first:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    String text = "2011-10-02 18:48:05.123";
    LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
    System.out.println(dateTime);

This prints

2011-10-02T18:48:05.123

If your string was in yyyy-MM-dd format, instead do:

    String text = "2009-10-20";
    LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
    System.out.println(dateTime);

This prints

2009-10-20T00:00

Or still better, take the output from LocalDate.parse() and store it into a database column of datatype date.

In both cases the procedure for converting from a LocalDateTime to an Instant is:

    Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    System.out.println(ts);

I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:

    Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();


问:
How to compare 2 files fast using .NET?
Typical approaches recommend reading the binary via FileStream and comparing it byte-by-byte.

Would a checksum comparison such as CRC be faster?

Are there any .NET libraries that can generate a checksum for a file?

答:
Yet another answer, derived from @chsh.  MD5 with usings and shortcuts for file same, file not exists and differing lengths:</p>

```<code>/// <summary>
/// Performs an md5 on the content of both files and returns true if
/// they match
/// </summary>
/// <param name="file1">first file</param>
/// <param name="file2">second file</param>
/// <returns>true if the contents of the two files is the same, false otherwise</returns>
public static bool IsSameContent(string file1, string file2)
{
    if (file1 == file2)
        return true;

    FileInfo file1Info = new FileInfo(file1);
    FileInfo file2Info = new FileInfo(file2);

    if (!file1Info.Exists && !file2Info.Exists)
       return true;
    if (!file1Info.Exists && file2Info.Exists)
        return false;
    if (file1Info.Exists && !file2Info.Exists)
        return false;
    if (file1Info.Length != file2Info.Length)
        return false;

    using (FileStream file1Stream = file1Info.OpenRead())
    using (FileStream file2Stream = file2Info.OpenRead())
    {
        byte[] firstHash = MD5.Create().ComputeHash(file1Stream);
        byte[] secondHash = MD5.Create().ComputeHash(file2Stream);
        for (int i = 0; i < firstHash.Length; i++)
        {
            if (i>=secondHash.Length||firstHash[i] != secondHash[i])
                return false;
        }
        return true;
    }
}
</code>```

Title: How to compare 2 files fast using .NET?

Body:
Yet another answer, derived from @chsh.  MD5 with usings and shortcuts for file same, file not exists and differing lengths:

/// <summary>
/// Performs an md5 on the content of both files and returns true if
/// they match
/// </summary>
/// <param name="file1">first file</param>
/// <param name="file2">second file</param>
/// <returns>true if the contents of the two files is the same, false otherwise</returns>
public static bool IsSameContent(string file1, string file2)
{
    if (file1 == file2)
        return true;

    FileInfo file1Info = new FileInfo(file1);
    FileInfo file2Info = new FileInfo(file2);

    if (!file1Info.Exists && !file2Info.Exists)
       return true;
    if (!file1Info.Exists && file2Info.Exists)
        return false;
    if (file1Info.Exists && !file2Info.Exists)
        return false;
    if (file1Info.Length != file2Info.Length)
        return false;

    using (FileStream file1Stream = file1Info.OpenRead())
    using (FileStream file2Stream = file2Info.OpenRead())
    {
        byte[] firstHash = MD5.Create().ComputeHash(file1Stream);
        byte[] secondHash = MD5.Create().ComputeHash(file2Stream);
        for (int i = 0; i < firstHash.Length; i++)
        {
            if (i>=secondHash.Length||firstHash[i] != secondHash[i])
                return false;
        }
        return true;
    }
}


问:
Powershell apply action on each subfolder
I need a little help with a PS script I have written. I am inexperienced with Powershell, but based on what I have found online I was able to write a script to accomplish what I want. However, I can't get it to work on any subfolders.

Currently I have a folder called "C:\Temp\Test". Inside of that folder there are numerous subfolders, one for each user, named Greg, Tom, Alice, etc. So the folder structure looks like this

C:\Temp\Test\Greg

C:\Temp\Test\Tom

C:\Temp\Test\Alice

etc...

Each person's subfolder contains dozens and sometimes hundreds of .JPG and .TIF picture files. Each picture file needs to have a .XML file with the same name that contains properties such as name & date of birth and such. I have created the first .XML file for each user and created the following script to scan the folder and create the .XML file for each remaining picture file. Then copy the contents of the first .XML file into the newly created files. Here is what I have so far:

```<code>$sourceFiles = Get-ChildItem -Path "C:\Temp\Test\*" -Recurse -File -Include *.tif,*jpg
$destinationFiles = Get-ChildItem -Path "C:\Temp\Test" -Recurse -File -Filter *.xml

foreach($sourceFile in $sourceFiles) {
  $exists = $destinationFiles | Where-Object {$_.BaseName -eq $sourceFile.BaseName}
  if(!$exists) {
    New-Item -type File "C:\Temp\Test\$($sourceFile.BaseName).xml"
  }
}

$file1 = Get-ChildItem "C:\Temp\Test" -Filter *.xml | Select-Object -First 1
$file2 = Get-ChildItem "C:\Temp\Test" -Filter *.xml -recurse -Exclude $file1

cd "C:\Temp\Test"
Get-Content $file1 | Add-Content $file2
</code>```

When I had the test pictures in the "C:\Temp\Test" directory, the script worked perfectly. What I can't figure out, is how to change the script to run on each person's subfolder and place the new .XML files in the subfolder that the pictures are located in. If anyone has any ideas about how I could do this, or how I could improve this script I would greatly appreciate your thoughts. As I said, I am not very experienced with PS. Thanks!

答:
Thanks for the response Prasoon! I ended up putting this project on hold for awhile and when I picked it back up, I reworked what I had done. After spending some time learning Powershell a little better I came up with something that was almost exactly what I wanted. I felt I should share it in case anyone else is stuck on a similar issue.

```<code>#This is the Template File

$file1 = "C:\Temp\000.xml"

#This browses through each subfolder and finds any files that are JPG or PNG
files.

Get-ChildItem -recurse -force | ForEach {
If (($_.extension -eq ".tif") -or ($_.extension -eq ".jpg"))

#This creates a new XML file for each image file found in the previous step
and gives it the same name as the image file. It then copies the contents of
the XML Template file into the new XML file.

{New-Item -type File -Path $($_.DirectoryName) -Name "$($_.BaseName).xml"
-value "$(Get-Content $file1)" -ErrorAction SilentlyContinue}
}

#After the XML files are created, this finds any XML files in
subdirectories. It then looks for the \record\name element and updates it to
the name of the folder that the file is located in.

Get-ChildItem -include *.xml -recurse | % ($_) {
[xml]$xml = Get-Content ("$($_.Fullname)")
$xml.record.name = (Get-
Culture).TextInfo.ToTitleCase("$($_.Directory.BaseName.ToLower())")
$xml.save("$($_.Fullname)")}
</code>```

The folders that the image and XML files are in are all capital. (i.e JOHN DOE).  I wanted the 'name' element in the XML files to be title case instead of all caps, and so the last part of the code pulls the folder name that XML file resides in and converts it from JOHN DOE to John Doe. Then puts that value in 'name' element of the XML file.

Hopefully someone finds this script useful.

Body:
I need a little help with a PS script I have written. I am inexperienced with Powershell, but based on what I have found online I was able to write a script to accomplish what I want. However, I can't get it to work on any subfolders.

Currently I have a folder called "C:\Temp\Test". Inside of that folder there are numerous subfolders, one for each user, named Greg, Tom, Alice, etc. So the folder structure looks like this

C:\Temp\Test\Greg

C:\Temp\Test\Tom

C:\Temp\Test\Alice

etc...

Each person's subfolder contains dozens and sometimes hundreds of .JPG and .TIF picture files. Each picture file needs to have a .XML file with the same name that contains properties such as name & date of birth and such. I have created the first .XML file for each user and created the following script to scan the folder and create the .XML file for each remaining picture file. Then copy the contents of the first .XML file into the newly created files. Here is what I have so far:

$sourceFiles = Get-ChildItem -Path "C:\Temp\Test\*" -Recurse -File -Include *.tif,*jpg
$destinationFiles = Get-ChildItem -Path "C:\Temp\Test" -Recurse -File -Filter *.xml

foreach($sourceFile in $sourceFiles) {
  $exists = $destinationFiles | Where-Object {$_.BaseName -eq $sourceFile.BaseName}
  if(!$exists) {
    New-Item -type File "C:\Temp\Test\$($sourceFile.BaseName).xml"
  }
}

$file1 = Get-ChildItem "C:\Temp\Test" -Filter *.xml | Select-Object -First 1
$file2 = Get-ChildItem "C:\Temp\Test" -Filter *.xml -recurse -Exclude $file1

cd "C:\Temp\Test"
Get-Content $file1 | Add-Content $file2

When I had the test pictures in the "C:\Temp\Test" directory, the script worked perfectly. What I can't figure out, is how to change the script to run on each person's subfolder and place the new .XML files in the subfolder that the pictures are located in. If anyone has any ideas about how I could do this, or how I could improve this script I would greatly appreciate your thoughts. As I said, I am not very experienced with PS. Thanks!

Body:
Thanks for the response Prasoon! I ended up putting this project on hold for awhile and when I picked it back up, I reworked what I had done. After spending some time learning Powershell a little better I came up with something that was almost exactly what I wanted. I felt I should share it in case anyone else is stuck on a similar issue.

#This is the Template File

$file1 = "C:\Temp\000.xml"

#This browses through each subfolder and finds any files that are JPG or PNG
files.

Get-ChildItem -recurse -force | ForEach {
If (($_.extension -eq ".tif") -or ($_.extension -eq ".jpg"))

#This creates a new XML file for each image file found in the previous step
and gives it the same name as the image file. It then copies the contents of
the XML Template file into the new XML file.

{New-Item -type File -Path $($_.DirectoryName) -Name "$($_.BaseName).xml"
-value "$(Get-Content $file1)" -ErrorAction SilentlyContinue}
}

#After the XML files are created, this finds any XML files in
subdirectories. It then looks for the \record\name element and updates it to
the name of the folder that the file is located in.

Get-ChildItem -include *.xml -recurse | % ($_) {
[xml]$xml = Get-Content ("$($_.Fullname)")
$xml.record.name = (Get-
Culture).TextInfo.ToTitleCase("$($_.Directory.BaseName.ToLower())")
$xml.save("$($_.Fullname)")}

The folders that the image and XML files are in are all capital. (i.e JOHN DOE).  I wanted the 'name' element in the XML files to be title case instead of all caps, and so the last part of the code pulls the folder name that XML file resides in and converts it from JOHN DOE to John Doe. Then puts that value in 'name' element of the XML file.

Hopefully someone finds this script useful.


问:
"hg commit -m 'My changes' " error
I follow this article to create a repository using Mercurial:

```<code>$ hg clone http://selenic.com/repo/hello
$ cd hello
$ hg add a.txt
$ hg commit -m 'My changes'
</code>```

but when i use hg commit -m 'My changes', it shows error :

```<code>abort: changes':
</code>```

What can I do about it?

答: Seems like your single quotes aren't behaving as such, which would hint that you're using a different character. Are you using the standard straight single quote?</p>

Title: "hg commit -m 'My changes' " error

Body:
I follow this article to create a repository using Mercurial:

$ hg clone http://selenic.com/repo/hello
$ cd hello
$ hg add a.txt
$ hg commit -m 'My changes'

but when i use hg commit -m 'My changes', it shows error :

abort: changes':

What can I do about it?


问:
Standardization before or after categorical encoding?
I'm working on a regression algorithm, in this case k-NearestNeighbors to predict a certain price of a product.

So I have a Training set which has only one categorical feature with 4 possible values. I've dealt with it using a one-to-k categorical encoding scheme which means now I have 3 more columns in my Pandas DataFrame with a 0/1 depending the value present.

The other features in the DataFrame are mostly distances like latitud - longitude for locations and prices, all numerical.

Should I standardize (Gaussian distribution with zero mean and unit variance) and normalize before or after the categorical encoding?

I'm thinking it might be benefitial to normalize after encoding so that every feature is to the estimator as important as every other when measuring distances between neighbors but I'm not really sure.

答:
After. Just imagine that you have not numerical variables in your column but strings. You can't standardize strings - right? :)

But given what you wrote about categories. If they are represented with values, I suppose there is some kind of ranking inside. Probably, you can use raw column rather than one-hot-encoded. Just thoughts.


问:
Simulate Push Notification in UITest
We would like to test the receiving of push notifications (while the app is active) in an UITest. The goto solution with sending real push notifications sounds a bit like an overkill (and only works on a real device): see http://www.pixeldock.com/blog/testing-push-notifications-with-xcode-uitests/

My question is: Is it possible to call (directly or indirectly) the UIAppicaltionDelegate's didReceiveRemoteNotification from an (UI) XCTestCase?

答:
You cannot call functions in your app's code from an UITest. UITests run in a separate process and don't have access to your app's functions and methods.

From Apple's Docs:

UI testing differs from unit testing in fundamental ways. Unit testing
  enables you to work within your app's scope and allows you to exercise
  functions and methods with full access to your app's variables and
  state. UI testing exercises your app's UI in the same way that users
  do without access to your app's internal methods, functions, and
  variables. This enables your tests to see the app the same way a user
  does, exposing UI problems that users encounter.

Directly calling didReceiveRemoteNotification from a test is possible in a UnitTest. I don't know how your app handles push notifications but if you can test the desired outcome with a unit test that might be a valid alternative.

Title: Simulate Push Notification in UITest


问:
How to get the name of the method resulting from a lambda
From a simple point of view, lambda expressions are compiled into static methods, since they don’t capture this (i.e. do not access instance members).

```<code>public class App {
  public static void foo(){
      Consumer<Integer> c1 = n -> {};
      Consumer<Integer> c2 = n -> {};
  }

  public static void main(String [] args) {
    Supplier<String> sup1 = () -> "I am sup1";
    Supplier<String> sup2 = () -> "I am sup2";
    Supplier<String> sup3 = () -> "I am sup3";

    Stream.of(App.class.getDeclaredMethods()).forEach(System.out::println);
  }
}
</code>```

Running the previous example and checking the generated bytecodes with the javap tool, we can see that lambdas referred by variables c1, c2, sup1, sup2, sup3 are compiled to methods with names:

lambda$foo$0

lambda$foo$1

lambda$main$2

lambda$main$3

lambda$main$4

However, if we print the getClass() for each object referred by those variables (c1, c2, sup1, sup2, sup3) we will get, respectively:

class App$$Lambda$5/1705736037

class App$$Lambda$6/455659002

class App$$Lambda$1/791452441

class App$$Lambda$2/531885035

class App$$Lambda$3/1418481495

So, how can we make the correspondence between the runtime class names and the name of the methods resulting from the lambdas?

UPDATE

None of the solutions pointed in the following duplicated questions helps me to solve the problem that I am asking in my question:

How to get the MethodInfo of a Java 8 method reference?

Printing debug info on errors with java 8 lambda expressions 1 answer

Get MethodHandle from lambda object

The only way that I found was to adapt the solution of @Holger from its answer (not the accepted one) to the question Java 8: convert lambda to a Method instance with clousure included. However, in my case, instead of a Method object I am just looking for the name of the method. So, adapting that lambdaToMethod() to the following methodNameFromLambda() I got a solution:

```<code>static String methodNameFromLambda(Serializable lambda) {
  try {
    Method m = lambda.getClass().getDeclaredMethod("writeReplace");
    m.setAccessible(true);
    SerializedLambda sl=(SerializedLambda)m.invoke(lambda);
    return sl.getImplMethodName();
  } catch(ReflectiveOperationException ex) {
    throw new RuntimeException(ex);
  }
}
</code>```

Now, lambdas of the example must be cast to Consumer<Integer>&Serializable or Supplier<String>&Serializable as describe in @Holger answer.

I am not aware if this solution is correct, but it works for my example and for the cases that I am working on.

答: This is subject to change from version to version - there is no specification that says what the exact names would be - and it's done on purpose; well to protect against code that might find clever things to do with these names.

Body:
From a simple point of view, lambda expressions are compiled into static methods, since they don’t capture this (i.e. do not access instance members).

public class App {
  public static void foo(){
      Consumer<Integer> c1 = n -> {};
      Consumer<Integer> c2 = n -> {};
  }

  public static void main(String [] args) {
    Supplier<String> sup1 = () -> "I am sup1";
    Supplier<String> sup2 = () -> "I am sup2";
    Supplier<String> sup3 = () -> "I am sup3";

    Stream.of(App.class.getDeclaredMethods()).forEach(System.out::println);
  }
}

Running the previous example and checking the generated bytecodes with the javap tool, we can see that lambdas referred by variables c1, c2, sup1, sup2, sup3 are compiled to methods with names:

lambda$foo$0

lambda$foo$1

lambda$main$2

lambda$main$3

lambda$main$4

However, if we print the getClass() for each object referred by those variables (c1, c2, sup1, sup2, sup3) we will get, respectively:

class App$$Lambda$5/1705736037

class App$$Lambda$6/455659002

class App$$Lambda$1/791452441

class App$$Lambda$2/531885035

class App$$Lambda$3/1418481495

So, how can we make the correspondence between the runtime class names and the name of the methods resulting from the lambdas?

UPDATE

None of the solutions pointed in the following duplicated questions helps me to solve the problem that I am asking in my question:

How to get the MethodInfo of a Java 8 method reference?

Printing debug info on errors with java 8 lambda expressions 1 answer

Get MethodHandle from lambda object

The only way that I found was to adapt the solution of @Holger from its answer (not the accepted one) to the question Java 8: convert lambda to a Method instance with clousure included. However, in my case, instead of a Method object I am just looking for the name of the method. So, adapting that lambdaToMethod() to the following methodNameFromLambda() I got a solution:

static String methodNameFromLambda(Serializable lambda) {
  try {
    Method m = lambda.getClass().getDeclaredMethod("writeReplace");
    m.setAccessible(true);
    SerializedLambda sl=(SerializedLambda)m.invoke(lambda);
    return sl.getImplMethodName();
  } catch(ReflectiveOperationException ex) {
    throw new RuntimeException(ex);
  }
}

Now, lambdas of the example must be cast to Consumer<Integer>&Serializable or Supplier<String>&Serializable as describe in @Holger answer.

I am not aware if this solution is correct, but it works for my example and for the cases that I am working on.


问:
Combine looping array PHP Codeigniter
I have two arrays that are the results of two different database queries. I want to merge those two arrays fin the way I explain in the example below

This is the code that executes the first query:

```<code>$query = $this->db->query("SELECT kec,pilihan,COUNT(pilihan) as total FROM votes GROUP BY pilihan");
$someArray = [];
foreach($query->result_array() as $row){
    array_push($someArray, [
        'data'     => $row['pilihan'],
        'total'    => $row['total'],
        'location' => $row['kec'],
        ]);
    }
</code>```

This is the resulting array:

```<code>[
  {
    "data": "1",
    "total": "2",
    "location": "3524230"
  },
  {
    "data": "2",
    "total": "3",
    "location": "3524230"
  },
  {
    "data": "3",
    "total": "1",
    "location": "3524230"
  }
]
</code>```

This is the code that executes the second query:

```<code>$query = $this->db->query("SELECT * FROM owl_dptmaster GROUP BY kecamatan");
$someArray = [];
foreach($query->result_array() as $row){
    array_push($someArray, [
        'location' => $row['kecamatan']
    ]);
}
</code>```

And the second array looks like this:

```<code>[
  {
    "location": "3524230"
  },
  {
    "location": "3524240"
  },
  {
    "location": "3524250"
  },
  {
    "location": "3524260"
  }
]
</code>```

I want to merge those two arrays so that the result would be this array:

```<code>[
  {
    "location": "3524230",
    "data1": "2",
    "data2": "3",
    "data3": "1"
  },
  {
    "location": "3524240",
    "data1": null,
    "data2": null,
    "data3": null
  },
  {
    "location": "3524250",
    "data1": null,
    "data2": null,
    "data3": null
  },
  {
    "location": "3524260",
    "data1": null,
    "data2": null,
    "data3": null
  }
]
</code>```

How can I achieve this?

答:
Instead of combining arrays, you could do the summarizing in sql with sub queries. Assuming you're using mysql.

```<code>$query = $this->db->query(
 "select owl.kecamatan,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 1) data1,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 2) data2,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 3) data3,
 from owl_dptmaster owl
 order by owl.kecamatan"
 );
</code>```

You could do this query and then build an array of  "data" . $pilihan => $totalPilihan which you push into the $someArray when the $location changes.

```<code>$query = $this->db->query(
"select owl.kecamatan as location, v.pilihan
from owl_dptmaster owl
left join votes v
on owl.kecamatan = v.kec"
order by 1, 2);
</code>```

You have a results set with all the locations and votes.

```<code> // Made of query results...
 $query = [

 [ "location" => "3524230", "pilihan" => "1" ],
 [ "location" => "3524230", "pilihan" => "1" ],
 [ "location" => "3524230", "pilihan" => "2" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "4" ],
 [ "location" => "3524230", "pilihan" => "4" ],
 [ "location" => "3524230", "pilihan" => "5" ],
 [ "location" => "3524240", "pilihan" => null ],
 [ "location" => "3524250", "pilihan" => null ],
 [ "location" => "3524260", "pilihan" => null ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "20" ],
 [ "location" => "3524270", "pilihan" => "20" ],
 [ "location" => "3524270", "pilihan" => "30" ]

 ];
</code>```

And here's a procedural routine to build $someArray[].

```<code> $someArray = [];
 $xRow = [];
 $oldPilihan = '';
 $total = 0;
 $oldLocation = '';

 foreach ($query as $row) {

 //echo $row['location'] . " - " . $row['pilihan'] . '<br>';

 $location = $row['location'];
 $pilihan = $row['pilihan'];

 if ($pilihan !== $oldPilihan) {

 if (! empty($oldPilihan) ) {
   $dataName = 'data' . $oldPilihan;
   $xRow[] = array($dataName => $total);
 }
   $total = 1;
   $oldPilihan = $pilihan;

 } else {

   $total++;
 }

 if ($location !== $oldLocation) {

   if (! empty($oldLocation)) {
     array_push($someArray, $xRow);
   }
   $xRow = [ 'location' => $location ];
   $oldLocation = $location;

   }

 }

 $dataName = 'data' . $oldPilihan;
 $xRow[] = array($dataName => $total);
 array_push($someArray, $xRow);

 var_dump($someArray);
</code>```

Title: Combine looping array PHP Codeigniter

Body:
I have two arrays that are the results of two different database queries. I want to merge those two arrays fin the way I explain in the example below

This is the code that executes the first query:

$query = $this->db->query("SELECT kec,pilihan,COUNT(pilihan) as total FROM votes GROUP BY pilihan");
$someArray = [];
foreach($query->result_array() as $row){
    array_push($someArray, [
        'data'     => $row['pilihan'],
        'total'    => $row['total'],
        'location' => $row['kec'],
        ]);
    }

This is the resulting array:

[
  {
    "data": "1",
    "total": "2",
    "location": "3524230"
  },
  {
    "data": "2",
    "total": "3",
    "location": "3524230"
  },
  {
    "data": "3",
    "total": "1",
    "location": "3524230"
  }
]

This is the code that executes the second query:

$query = $this->db->query("SELECT * FROM owl_dptmaster GROUP BY kecamatan");
$someArray = [];
foreach($query->result_array() as $row){
    array_push($someArray, [
        'location' => $row['kecamatan']
    ]);
}

And the second array looks like this:

[
  {
    "location": "3524230"
  },
  {
    "location": "3524240"
  },
  {
    "location": "3524250"
  },
  {
    "location": "3524260"
  }
]

I want to merge those two arrays so that the result would be this array:

[
  {
    "location": "3524230",
    "data1": "2",
    "data2": "3",
    "data3": "1"
  },
  {
    "location": "3524240",
    "data1": null,
    "data2": null,
    "data3": null
  },
  {
    "location": "3524250",
    "data1": null,
    "data2": null,
    "data3": null
  },
  {
    "location": "3524260",
    "data1": null,
    "data2": null,
    "data3": null
  }
]

How can I achieve this?

Body:
Instead of combining arrays, you could do the summarizing in sql with sub queries. Assuming you're using mysql.

$query = $this->db->query(
 "select owl.kecamatan,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 1) data1,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 2) data2,
  (select count(pilihan) from votes where kec = owl.kecamatan and pilihan = 3) data3,
 from owl_dptmaster owl
 order by owl.kecamatan"
 );

You could do this query and then build an array of  "data" . $pilihan => $totalPilihan which you push into the $someArray when the $location changes.

$query = $this->db->query(
"select owl.kecamatan as location, v.pilihan
from owl_dptmaster owl
left join votes v
on owl.kecamatan = v.kec"
order by 1, 2);

You have a results set with all the locations and votes.

 // Made of query results...
 $query = [

 [ "location" => "3524230", "pilihan" => "1" ],
 [ "location" => "3524230", "pilihan" => "1" ],
 [ "location" => "3524230", "pilihan" => "2" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "3" ],
 [ "location" => "3524230", "pilihan" => "4" ],
 [ "location" => "3524230", "pilihan" => "4" ],
 [ "location" => "3524230", "pilihan" => "5" ],
 [ "location" => "3524240", "pilihan" => null ],
 [ "location" => "3524250", "pilihan" => null ],
 [ "location" => "3524260", "pilihan" => null ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "1" ],
 [ "location" => "3524270", "pilihan" => "20" ],
 [ "location" => "3524270", "pilihan" => "20" ],
 [ "location" => "3524270", "pilihan" => "30" ]

 ];

And here's a procedural routine to build $someArray[].

 $someArray = [];
 $xRow = [];
 $oldPilihan = '';
 $total = 0;
 $oldLocation = '';

 foreach ($query as $row) {

 //echo $row['location'] . " - " . $row['pilihan'] . '<br>';

 $location = $row['location'];
 $pilihan = $row['pilihan'];

 if ($pilihan !== $oldPilihan) {

 if (! empty($oldPilihan) ) {
   $dataName = 'data' . $oldPilihan;
   $xRow[] = array($dataName => $total);
 }
   $total = 1;
   $oldPilihan = $pilihan;

 } else {

   $total++;
 }

 if ($location !== $oldLocation) {

   if (! empty($oldLocation)) {
     array_push($someArray, $xRow);
   }
   $xRow = [ 'location' => $location ];
   $oldLocation = $location;

   }

 }

 $dataName = 'data' . $oldPilihan;
 $xRow[] = array($dataName => $total);
 array_push($someArray, $xRow);

 var_dump($someArray);


问:
Try-Catch-Finally Block
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

```<code>import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}
</code>```

Any Help Please

答:
It won't compile because just as you indicated, the s.close() in your finally block can throw an IOException and you chose to handle that checked exception by specifying the "throws IOException" clause.  Because of that choice, the calling method must handle that checked exception by either catching it or also specifying it will throw the exception.

It is unclear what results you desire other than it must compile, so here are three options:

1) Wrap s.close with it's own try/catch and remove the throws clause.

2) Move "ExHandling ex" definition inside the caller's try/catch.

3) Add a throws clause to the caller (and remove the try/finally if desired).  RECOMMENDED

CAUTION: You really don't want to catch an exception and do "e.printStackTrace();".  All this does is mask issues in your logic.  You should only catch an exception if you plan to handle it in some manner; otherwise, you should allow the exception to propagate up the chain of callers.  Thus, only use options 1 & 2 if you really wish to do something in all the catch clauses.

Option 1: Wrap s.close with it's own try/catch and remove the throws clause.

```<code>

    public void connect() {
        Socket s = new Socket();
        try {
            s.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ExHandling ex = new ExHandling();
        try {
            ex.connect();
        }
        finally {
            System.out.println("Finally");
        }
    }

</code>```

Option 2: Move "ExHandling ex" definition inside the caller's try/catch.  In this case I would recommend using try with resources for the socket.

```<code>

    public void connect() throws IOException {
        Socket s = new Socket();
        s.getInputStream();
        s.close();
    }

    public static void main(String[] args) {
        try {
            ExHandling ex = new ExHandling();
            ex.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            System.out.println("Finally");
        }
    }

</code>```

Option 3: Add a throws clause to the caller (and remove the try/finally if desired).  RECOMMENDED

```<code>

    public void connect() throws IOException {
        Socket s = new Socket();
        s.getInputStream();
        s.close();
    }

    public static void main(String[] args) throws IOException {
        ExHandling ex = new ExHandling();
        ex.connect();
        System.out.println("Finally");
    }

</code>```

Title: Try-Catch-Finally Block

Body:
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}

Any Help Please

Body:
It won't compile because just as you indicated, the s.close() in your finally block can throw an IOException and you chose to handle that checked exception by specifying the "throws IOException" clause.  Because of that choice, the calling method must handle that checked exception by either catching it or also specifying it will throw the exception.

It is unclear what results you desire other than it must compile, so here are three options:

1) Wrap s.close with it's own try/catch and remove the throws clause.

2) Move "ExHandling ex" definition inside the caller's try/catch.

3) Add a throws clause to the caller (and remove the try/finally if desired).  RECOMMENDED

CAUTION: You really don't want to catch an exception and do "e.printStackTrace();".  All this does is mask issues in your logic.  You should only catch an exception if you plan to handle it in some manner; otherwise, you should allow the exception to propagate up the chain of callers.  Thus, only use options 1 & 2 if you really wish to do something in all the catch clauses.

Option 1: Wrap s.close with it's own try/catch and remove the throws clause.

    public void connect() {
        Socket s = new Socket();
        try {
            s.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ExHandling ex = new ExHandling();
        try {
            ex.connect();
        }
        finally {
            System.out.println("Finally");
        }
    }

Option 2: Move "ExHandling ex" definition inside the caller's try/catch.  In this case I would recommend using try with resources for the socket.

    public void connect() throws IOException {
        Socket s = new Socket();
        s.getInputStream();
        s.close();
    }

    public static void main(String[] args) {
        try {
            ExHandling ex = new ExHandling();
            ex.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            System.out.println("Finally");
        }
    }

Option 3: Add a throws clause to the caller (and remove the try/finally if desired).  RECOMMENDED

    public void connect() throws IOException {
        Socket s = new Socket();
        s.getInputStream();
        s.close();
    }

    public static void main(String[] args) throws IOException {
        ExHandling ex = new ExHandling();
        ex.connect();
        System.out.println("Finally");
    }


问:
Clearing (and Resetting) Material Select
I know there's a few questions already on this, but none of the answers seem to work.

I have a series of Angular selects (mat-select). The options chosen in one mat-select effect the options available in subsequent mat-select instances. For instance, if the first mat-select allowed you to choose fruit or vegetable, the second mat-select might have apple and orange if you chose fruit or cucumber and potato if you chose vegetable.

The problem is that if you then go back and change your fruit/vegetable selection, I need to clear the second mat-select (otherwise, it just displays the new item that has the same selected index).

I've tried using patchValue to set the value of the control to null. I've tried calling reset on the control. None of the options I've found seem to work.

Are there any examples of this working to which I can refer?

答: So the answer turned out to be that I needed to use the [(ngModel)] binding on each mat-select and assign a formControlName to each mat-select in order to get it to work within a formGroup.


问:
SQL return the output of SELECT and not the output of another stored procedure
How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!

In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable @StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:

```<code>-- Main stored procedure
BEGIN
    DECLARE @StartDate DATETIME

    EXEC @StartDate = spCuExt_ExtractLog 'Customers'

    SELECT Id, [Name], LogoPath, IsDeleted
    FROM dbo.Customers
    WHERE RecordCreatedDateUTC>= @StartDate
END
</code>```

This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.

How do I do this?

答:
Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)

http://www.sommarskog.se/share_data.html

Body:
How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!

In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable @StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:

-- Main stored procedure
BEGIN
    DECLARE @StartDate DATETIME

    EXEC @StartDate = spCuExt_ExtractLog 'Customers'

    SELECT Id, [Name], LogoPath, IsDeleted
    FROM dbo.Customers
    WHERE RecordCreatedDateUTC>= @StartDate
END

This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.

How do I do this?


问:
Is it possible for an application to fetch a specific location string from Google Maps?
I am trying to develop an android application that uses the location service. I want to get an address of specific place to my application, now I don't want to develop an another activity for fetching string . So I want to use an existing maps app to get location string. So could anyone please help me with some idea.</p>

答:
If I understand it right you just need a geocoding API, like google do https://developers.google.com/maps/documentation/geocoding/intro

But did you search on google first ?


问:
Power BI - control the drill up behaviour in matrix
I am having data such that multiple currencies are present in single column

As one can see above in the Vested Value column , Now I needed subtotals currency wise but since I am appending the currency symbols alongside values , therefore the datatype of columns is text , so cannot use automatic subtotals. So , I precalculated the subtotal and inserted it as  a row inside the table as you can see the "SUBtotal-YEN" row . but since these are text formats , so when I drill up , it gives wrong answers. Thats why I need to cutomise the drill behaviour.Any suggestions on how to go about this?

答:
I would recommend creating an explicit measure instead of using the automatic implicit measure. If your VestedValue column is numeric, then you can use the following measure to get the subtotals working as well. (The currency formatting is done after the summing happens.)

```<code>VestedMeasure = SWITCH(SELECTEDVALUE(TableName[Home Currency]),
    "USD",FORMAT(SUM(TableName[VestedValue]),"$#,##0"),
    "YEN",FORMAT(SUM(TableName[VestedValue]),"¥#,##0"))
</code>```

If that column is not numeric, then create a calculated column that is and use that in the measure instead. The following formula strips off the currency symbol and converts to a numeric value:

```<code>VestedNumeric = VALUE(RIGHT(TableName[VestedValue], LEN(TableName[VestedValue])-1))
</code>```

Body:
I would recommend creating an explicit measure instead of using the automatic implicit measure. If your VestedValue column is numeric, then you can use the following measure to get the subtotals working as well. (The currency formatting is done after the summing happens.)

VestedMeasure = SWITCH(SELECTEDVALUE(TableName[Home Currency]),
    "USD",FORMAT(SUM(TableName[VestedValue]),"$#,##0"),
    "YEN",FORMAT(SUM(TableName[VestedValue]),"¥#,##0"))

If that column is not numeric, then create a calculated column that is and use that in the measure instead. The following formula strips off the currency symbol and converts to a numeric value:

VestedNumeric = VALUE(RIGHT(TableName[VestedValue], LEN(TableName[VestedValue])-1))


问:
Large Navigation Bar Text With Multiple Colors
iOS 11 introduces the option for larger text in the Navigation Bar. I would like to have a title that uses multiple colors. For example:

It's fairly easy to set the title, and even to change the color of the entire title:

```<code>[[self navigationItem] setTitle: @"Colors"];
[[[self navigationController] navigationBar] setLargeTitleTextAttributes: @{NSForegroundColorAttributeName: [UIColor colorFromHex: redColor]}];
</code>```

What I can't figure out is how to change just part of the title. For example, a way to select the range like this – NSRangeMake(0, 1) – so that I could apply a color to it.

This must be possible, right?

答:
There is no public API to set your own attributed text for the large title.

The solution is to navigate down the view hierarchy. You specifically mentioned you wanted to avoid this, but it's the only way to modify the colors while getting the rest of the UINavigationBar behavior for free.

Of course, you can always create your own UILabel and set its attributedText, but you will have to re-create any navigation bar animations and other behavior yourself.

Honestly the simplest solution is to modify your design so it doesn't require a multi-colored large title, as this is currently not supported.

I took a dive down the "spelunking" path, and there are a variety of visual issues with animations snapping back to the original text color.

Here is the code I used if it's useful for anyone trying to achieve a similar effect:

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    applyColorStyle(toLabels: findTitleLabels())
}

private func applyColorStyle(toLabels labels: [UILabel]) {
    for titleLabel in labels {
        let attributedString = NSMutableAttributedString(string: titleLabel.text ?? "")
        let fullRange = NSRange(location: 0, length: attributedString.length)
        attributedString.addAttribute(NSAttributedStringKey.font, value: titleLabel.font, range: fullRange)
        let colors = [UIColor.red, UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple]
        for (index, color) in colors.enumerated() {
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSRange(location: index, length: 1))
        }
        titleLabel.attributedText = attributedString
    }
}

private func findTitleLabels() -> [UILabel] {
    guard let navigationController = navigationController else { return [] }
    var labels = [UILabel]()
    for view in navigationController.navigationBar.subviews {
        for subview in view.subviews {
            if let label = subview as? UILabel {
                if label.text == title { labels.append(label) }
            }
        }
    }
    return labels
}
</code>```

The downside of the "spelunking" approach is it's not a supported API, meaning that it could easily break in a future update or not work as intended in various edge cases.

Body:
iOS 11 introduces the option for larger text in the Navigation Bar. I would like to have a title that uses multiple colors. For example:

It's fairly easy to set the title, and even to change the color of the entire title:

[[self navigationItem] setTitle: @"Colors"];
[[[self navigationController] navigationBar] setLargeTitleTextAttributes: @{NSForegroundColorAttributeName: [UIColor colorFromHex: redColor]}];

What I can't figure out is how to change just part of the title. For example, a way to select the range like this – NSRangeMake(0, 1) – so that I could apply a color to it.

This must be possible, right?

Body:
There is no public API to set your own attributed text for the large title.

The solution is to navigate down the view hierarchy. You specifically mentioned you wanted to avoid this, but it's the only way to modify the colors while getting the rest of the UINavigationBar behavior for free.

Of course, you can always create your own UILabel and set its attributedText, but you will have to re-create any navigation bar animations and other behavior yourself.

Honestly the simplest solution is to modify your design so it doesn't require a multi-colored large title, as this is currently not supported.

I took a dive down the "spelunking" path, and there are a variety of visual issues with animations snapping back to the original text color.

Here is the code I used if it's useful for anyone trying to achieve a similar effect:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    applyColorStyle(toLabels: findTitleLabels())
}

private func applyColorStyle(toLabels labels: [UILabel]) {
    for titleLabel in labels {
        let attributedString = NSMutableAttributedString(string: titleLabel.text ?? "")
        let fullRange = NSRange(location: 0, length: attributedString.length)
        attributedString.addAttribute(NSAttributedStringKey.font, value: titleLabel.font, range: fullRange)
        let colors = [UIColor.red, UIColor.orange, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.purple]
        for (index, color) in colors.enumerated() {
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSRange(location: index, length: 1))
        }
        titleLabel.attributedText = attributedString
    }
}

private func findTitleLabels() -> [UILabel] {
    guard let navigationController = navigationController else { return [] }
    var labels = [UILabel]()
    for view in navigationController.navigationBar.subviews {
        for subview in view.subviews {
            if let label = subview as? UILabel {
                if label.text == title { labels.append(label) }
            }
        }
    }
    return labels
}

The downside of the "spelunking" approach is it's not a supported API, meaning that it could easily break in a future update or not work as intended in various edge cases.