问:
Removing supplementary characters from a Java string
I have a Java string that contains supplementary characters (characters in the Unicode standard whose code points are above U+FFFF). These characters could for example be emojis. I want to remove those characters from the string, i.e. replace them with the empty string "".

How do I remove supplementary characters from a string?

How do I remove characters from an arbitrary code point range? (For example all characters in the range 1F000–1FFFF)?

答:
Here is a code snippet that collects characters between code point 60 and 100:

```<code>public class Test {

    public static void main(String[] args) {
        new Test().go();
    }

    private void go() {
        String s = "ABC12三￮";
        String ret = "";
        for (int i = 0; i < s.length(); i++) {
            System.out.println(s.codePointAt(i));

            if ((s.codePointAt(i) > 60) & (s.codePointAt(i) < 100)) {
                ret += s.substring(i, i+1);
            }
        }

        System.out.println(ret);
    }
}
</code>```

the result:

```<code>code point: 65
code point: 66
code point: 67
code point: 49
code point: 50
code point: 19977
code point: 65518
result: ABC
</code>```

Hope this helps.

Body:
Here is a code snippet that collects characters between code point 60 and 100:

public class Test {

    public static void main(String[] args) {
        new Test().go();
    }

    private void go() {
        String s = "ABC12三￮";
        String ret = "";
        for (int i = 0; i < s.length(); i++) {
            System.out.println(s.codePointAt(i));

            if ((s.codePointAt(i) > 60) & (s.codePointAt(i) < 100)) {
                ret += s.substring(i, i+1);
            }
        }

        System.out.println(ret);
    }
}

the result:

code point: 65
code point: 66
code point: 67
code point: 49
code point: 50
code point: 19977
code point: 65518
result: ABC

Hope this helps.


来源: stackexchange

问:
Adding Owner Name in the Purchase Order Lookup screen
I would like to add the Owner Name (on the PO Screen) in the Purchase Order>Order Nbr. field lookup screen. I tried to manually add the following in the Data Class for OrdNbr but it didn't bring the Employee name in the lookup screen. Can you please help or let me know if i am missing something.
Here is the full code i am trying(screenshot attached)

```<code>[PXCustomizeSelectorColumns(
typeof(PX.Objects.PO.POOrder.orderType),
typeof(PX.Objects.PO.POOrder.orderNbr),
typeof(PX.Objects.PO.POOrder.vendorRefNbr),
typeof(PX.Objects.PO.POOrder.orderDate),
typeof(PX.Objects.PO.POOrder.status),
typeof(PX.Objects.PO.POOrder.vendorID),
typeof(PX.Objects.PO.POOrder.vendorID_Vendor_acctName),
typeof(PX.Objects.PO.POOrder.vendorLocationID),
typeof(PX.Objects.PO.POOrder.curyID),
typeof(PX.Objects.PO.POOrder.curyOrderTotal),
typeof(PX.Objects.PO.POOrder.sOOrderType),
typeof(PX.Objects.PO.POOrder.sOOrderNbr),
typeof(PX.Objects.PO.POOrder.orderDesc),
typeof(PX.Objects.CR.CREmployee.acctCD),
typeof(PX.Objects.CR.CREmployee.bAccountID),
typeof(PX.Objects.CR.CREmployee.acctName))]
</code>```

Many  Thanksenter image description here

答:
Since POOrder.employeeID has a PXSelector attribute on its definition:

And this Selector has a DescriptionField assigned:

On this case you can add Owner name by adding this line of code to your CacheExtension file(This will obtain that DescriptionField for the EmployeeID field):

```<code>public abstract class employeeID_CREmployee_acctName : PX.Data.IBqlField { }
</code>```

See Snippet below:

```<code>namespace PX.Objects.PO
{
    [PXNonInstantiatedExtension]
    public class PO_POOrder_ExistingColumn : PXCacheExtension<PX.Objects.PO.POOrder>
    {
        #region OwnerName
        public abstract class employeeID_CREmployee_acctName : PX.Data.IBqlField
        { }
        #endregion

        #region OrderNbr
        [PXMergeAttributes(Method = MergeMethod.Append)]

        [PXCustomizeSelectorColumns(
            typeof(PX.Objects.PO.POOrder.orderType),
            typeof(PX.Objects.PO.POOrder.orderNbr),
            typeof(PX.Objects.PO.POOrder.vendorRefNbr),
            typeof(PX.Objects.PO.POOrder.orderDate),
            typeof(PX.Objects.PO.POOrder.status),
            typeof(PX.Objects.PO.POOrder.employeeID),
            typeof(PX.Objects.PO.PO_POOrder_ExistingColumn.employeeID_CREmployee_acctName),
            typeof(PX.Objects.PO.POOrder.vendorID),
            typeof(PX.Objects.PO.POOrder.vendorID_Vendor_acctName),
            typeof(PX.Objects.PO.POOrder.vendorLocationID),
            typeof(PX.Objects.PO.POOrder.curyID),
            typeof(PX.Objects.PO.POOrder.curyOrderTotal),
            typeof(PX.Objects.PO.POOrder.sOOrderType),
            typeof(PX.Objects.PO.POOrder.sOOrderNbr))]
        public string OrderNbr { get; set; }
        #endregion
    }
}
</code>```

Please notice that in case the POOrder.EmployeeID field would not have the "DescriptionField" set on the PXSelector Definition, you would have to modify the PXSelector of the OrderNbr to add a LeftJoin on the Desired Table(CREmployee on this case) so you could use the desired fields and add them to the PXCustomizeSelectorColumns attribute.

ContentLicense: CC BY-SA 3.0

Body:
I would like to add the Owner Name (on the PO Screen) in the Purchase Order>Order Nbr. field lookup screen. I tried to manually add the following in the Data Class for OrdNbr but it didn't bring the Employee name in the lookup screen. Can you please help or let me know if i am missing something.
Here is the full code i am trying(screenshot attached)

[PXCustomizeSelectorColumns(
typeof(PX.Objects.PO.POOrder.orderType),
typeof(PX.Objects.PO.POOrder.orderNbr),
typeof(PX.Objects.PO.POOrder.vendorRefNbr),
typeof(PX.Objects.PO.POOrder.orderDate),
typeof(PX.Objects.PO.POOrder.status),
typeof(PX.Objects.PO.POOrder.vendorID),
typeof(PX.Objects.PO.POOrder.vendorID_Vendor_acctName),
typeof(PX.Objects.PO.POOrder.vendorLocationID),
typeof(PX.Objects.PO.POOrder.curyID),
typeof(PX.Objects.PO.POOrder.curyOrderTotal),
typeof(PX.Objects.PO.POOrder.sOOrderType),
typeof(PX.Objects.PO.POOrder.sOOrderNbr),
typeof(PX.Objects.PO.POOrder.orderDesc),
typeof(PX.Objects.CR.CREmployee.acctCD),
typeof(PX.Objects.CR.CREmployee.bAccountID),
typeof(PX.Objects.CR.CREmployee.acctName))]

Many  Thanksenter image description here

Body:
Since POOrder.employeeID has a PXSelector attribute on its definition:

And this Selector has a DescriptionField assigned:

On this case you can add Owner name by adding this line of code to your CacheExtension file(This will obtain that DescriptionField for the EmployeeID field):

public abstract class employeeID_CREmployee_acctName : PX.Data.IBqlField { }

See Snippet below:

namespace PX.Objects.PO
{
    [PXNonInstantiatedExtension]
    public class PO_POOrder_ExistingColumn : PXCacheExtension<PX.Objects.PO.POOrder>
    {
        #region OwnerName
        public abstract class employeeID_CREmployee_acctName : PX.Data.IBqlField
        { }
        #endregion

        #region OrderNbr
        [PXMergeAttributes(Method = MergeMethod.Append)]

        [PXCustomizeSelectorColumns(
            typeof(PX.Objects.PO.POOrder.orderType),
            typeof(PX.Objects.PO.POOrder.orderNbr),
            typeof(PX.Objects.PO.POOrder.vendorRefNbr),
            typeof(PX.Objects.PO.POOrder.orderDate),
            typeof(PX.Objects.PO.POOrder.status),
            typeof(PX.Objects.PO.POOrder.employeeID),
            typeof(PX.Objects.PO.PO_POOrder_ExistingColumn.employeeID_CREmployee_acctName),
            typeof(PX.Objects.PO.POOrder.vendorID),
            typeof(PX.Objects.PO.POOrder.vendorID_Vendor_acctName),
            typeof(PX.Objects.PO.POOrder.vendorLocationID),
            typeof(PX.Objects.PO.POOrder.curyID),
            typeof(PX.Objects.PO.POOrder.curyOrderTotal),
            typeof(PX.Objects.PO.POOrder.sOOrderType),
            typeof(PX.Objects.PO.POOrder.sOOrderNbr))]
        public string OrderNbr { get; set; }
        #endregion
    }
}

Please notice that in case the POOrder.EmployeeID field would not have the "DescriptionField" set on the PXSelector Definition, you would have to modify the PXSelector of the OrderNbr to add a LeftJoin on the Desired Table(CREmployee on this case) so you could use the desired fields and add them to the PXCustomizeSelectorColumns attribute.


问:
How to get the value of a feature in a layer that match a the state dict in PyTorch?
I have some cnn, and I want to fetch the value of some intermediate layer corresponding to a some key from the state dict.
How could this be done?
Thanks.</p>

答:
I think you need to create a new class that redefines the forward pass through a given model. However, most probably you will need to create the code regarding the architecture of your model. You can find here an example:

```<code>class extract_layers():

    def __init__(self, model, target_layer):
        self.model = model
        self.target_layer = target_layer

    def __call__(self, x):
        return self.forward(x)

    def forward(self, x):
        module = self.model._modules[self.target_layer]

        # get output of the desired layer
        features = module(x)

        # get output of the whole model
        x = self.model(x)

        return x, features

model = models.vgg19(pretrained=True)
target_layer = 'features'
extractor = extract_layers(model, target_layer)

image = Variable(torch.randn(1, 3, 244, 244))
x, features = extractor(image)
</code>```

In this case, I am using the pre-defined vgg19 network given in the pytorch models zoo. The network has the layers structured in two modules the features for the convolutional part and the classifier for the fully-connected part. In this case, since features wraps all the convolutional layers of the network it is straightforward. If your architecture has several layers with different names, you will need to store their output using something similar to this:

```<code> for name, module in self.model._modules.items():
    x = module(x)  # forward the module individually
    if name in self.target_layer:
        features = x  # store the output of the desired layer
</code>```

Also, you should keep in mind that you need to reshape the output of the layer that connects the convolutional part to the fully-connected one. It should be easy to do if you know the name of that layer.

Body:
I think you need to create a new class that redefines the forward pass through a given model. However, most probably you will need to create the code regarding the architecture of your model. You can find here an example:

class extract_layers():

    def __init__(self, model, target_layer):
        self.model = model
        self.target_layer = target_layer

    def __call__(self, x):
        return self.forward(x)

    def forward(self, x):
        module = self.model._modules[self.target_layer]

        # get output of the desired layer
        features = module(x)

        # get output of the whole model
        x = self.model(x)

        return x, features

model = models.vgg19(pretrained=True)
target_layer = 'features'
extractor = extract_layers(model, target_layer)

image = Variable(torch.randn(1, 3, 244, 244))
x, features = extractor(image)

In this case, I am using the pre-defined vgg19 network given in the pytorch models zoo. The network has the layers structured in two modules the features for the convolutional part and the classifier for the fully-connected part. In this case, since features wraps all the convolutional layers of the network it is straightforward. If your architecture has several layers with different names, you will need to store their output using something similar to this:

 for name, module in self.model._modules.items():
    x = module(x)  # forward the module individually
    if name in self.target_layer:
        features = x  # store the output of the desired layer

Also, you should keep in mind that you need to reshape the output of the layer that connects the convolutional part to the fully-connected one. It should be easy to do if you know the name of that layer.


问:
Is it possible to push video content from a mobile app to Instagram stories by using Instagram API?
Is it possible to push video content from a mobile app to Instagram stories by using Instagram API?

Many thanks for your help

答: No, this is not possible. Instagram doesn't allow API calls to post content</p>


问:
Stop virtualhost rewrite rules executing if a rule was matched in the global config
I have the following setup.
Apache running with a separate VirtualHost file for each site.
Each of these has their own set of rewrite rules, for http to https for example which is all running fine.

What we would like to happen is this, from the global config we need to be able to check if a request is for a particular subdirectory. If it is then we should allow this request to process as it should but at that point we do not want the individual virtual host file rewrite rules to kick in. Therefore allowing this directory to be served on non https connections and not be redirected to https.

I have set up the rewrite rules and can match on the directories and redirect to an external url if it matches from the global which shows its inheriting but if I try to just allow it through the virtual hosts rewrites kick in and it redirects.

I have tried using L and END but this did not work either.
Is there any way of achieving this without editing the virtual host files that are already configured?

Main httpd config entry

```<code><Directory "/www">
Options Indexes Includes FollowSymLinks MultiViews
        AllowOverride All
        allow from all
        Order allow,deny
        Require all granted

RewriteEngine On
RewriteOptions InheritDownBefore

RewriteCond %{REQUEST_URI} ^/sub_directory/$ [NC]
RewriteRule ^(.*) $1  [L,END]
#RewriteRule ^(.*) -  [L,END]
#RewriteRule ^(.*) http://www.google.com  [L,END]  # This does get triggered

</Directory>
</code>```

sample virtual host file.

```<code><VirtualHost *:80>
ServerName urlone.com
ServerAlias urltwo.com

DocumentRoot /www/

RewriteEngine On

# redirect to https
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://urlone.com$1 [R=301,L]

</VirtualHost>
</code>```

so if I visit urlone.com it should redirect to https://urlone.com but if I visit urlone.com/sub_directory it needs to not allow the redirect to https.

I hope this makes sense to someone and thanks in advance for any help.

答:
In global httpd.conf:

```<code>RewriteEngine On
RewriteOptions InheritDownBefore
RewriteCond %{REQUEST_URI} ^/sub_directory$ [NC]
RewriteRule ^ - [E=PATH_MATCHED:true]
</code>```

(if needed, you can add additional rules, or additional flags to the above rule)

In virtual_host.conf

```<code>RewriteCond %{ENV:PATH_MATCHED} !=true
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://urlone.com%{REQUEST_URI} [R=301,L]
</code>```

Body:
I have the following setup.
Apache running with a separate VirtualHost file for each site.
Each of these has their own set of rewrite rules, for http to https for example which is all running fine.

What we would like to happen is this, from the global config we need to be able to check if a request is for a particular subdirectory. If it is then we should allow this request to process as it should but at that point we do not want the individual virtual host file rewrite rules to kick in. Therefore allowing this directory to be served on non https connections and not be redirected to https.

I have set up the rewrite rules and can match on the directories and redirect to an external url if it matches from the global which shows its inheriting but if I try to just allow it through the virtual hosts rewrites kick in and it redirects.

I have tried using L and END but this did not work either.
Is there any way of achieving this without editing the virtual host files that are already configured?

Main httpd config entry

<Directory "/www">
Options Indexes Includes FollowSymLinks MultiViews
        AllowOverride All
        allow from all
        Order allow,deny
        Require all granted

RewriteEngine On
RewriteOptions InheritDownBefore

RewriteCond %{REQUEST_URI} ^/sub_directory/$ [NC]
RewriteRule ^(.*) $1  [L,END]
#RewriteRule ^(.*) -  [L,END]
#RewriteRule ^(.*) http://www.google.com  [L,END]  # This does get triggered

</Directory>

sample virtual host file.

<VirtualHost *:80>
ServerName urlone.com
ServerAlias urltwo.com

DocumentRoot /www/

RewriteEngine On

# redirect to https
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://urlone.com$1 [R=301,L]

</VirtualHost>

so if I visit urlone.com it should redirect to https://urlone.com but if I visit urlone.com/sub_directory it needs to not allow the redirect to https.

I hope this makes sense to someone and thanks in advance for any help.

Body:
In global httpd.conf:

RewriteEngine On
RewriteOptions InheritDownBefore
RewriteCond %{REQUEST_URI} ^/sub_directory$ [NC]
RewriteRule ^ - [E=PATH_MATCHED:true]

(if needed, you can add additional rules, or additional flags to the above rule)

In virtual_host.conf

RewriteCond %{ENV:PATH_MATCHED} !=true
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://urlone.com%{REQUEST_URI} [R=301,L]


问:
Angular 4 - Can OnDestroy be run without the OnInit ever being triggered?
Just a generic question regarding the two Lifecycle Hooks OnInit and OnDestroy. As this article mentions, I had always assumed that OnInit is  always run before the OnDestroy.

I have a case where in an ngOnDestroy() I'm stopping a background music track from playing. This sound is loaded the component's ngOnInit(), and because the ngOnDestroy() is being run without the ngOnInit() being run the sound object is undefined.

Code

```<code>ngOnInit() {
    ...

    this.loadSounds();

    ...
}

ngOnDestroy() {
    if (AppSettings.SOUNDS_ENABLED) {
        this.soundService.getSound(Sound.MINI_GAME_BG_MUSIC).fade(0.2, 0, 1500);
    }
}

private loadSounds() {
    this.soundService.loadSound(Sound.MINI_GAME_BG_MUSIC, SoundPathURL.MINI_GAME_BG_MUSIC, true, 0);
}
</code>```

At the moment the code is failing in the ngOnDestroy when trying to .fade() a sound that's undefined. Of course I can easily fix this by checking that the sound is not undefined before executing the .fade() function. My assumption was that if an ngOnDestroy() is run the ngOnInit() must have been run as well - I guess I was wrong.

Now because of this case I'm thinking that in every ngOnDestroy() in my application I should check whether the object being used is undefined before performing any operations. So for example before unsubscribing from a subscription I should check if the subscription is undefined, and so on.

Am I right to assume so?

答:
The reference clearly states that OnInit lifecycle hook precedes OnDestroy. This behaviour is specific to the compiler in general. The article explains the behaviour that is specific to Angular router and the way <router-outlet> directive instantiates components. router.navigateByUrl() in route component constructor triggers its immediate destruction and prevents it from being compiled, so the lifecycle isn't applicable to it. This won't happen under normal circumstances.

The code in the question doesn't imply that ngOnInit doesn't run. ngOnInit call be easily logged to prove that it runs.

The service that is used by this component can cause the problem. The fact that Cannot read property 'fade' of undefined or similar error is thrown in ngOnDestroy means that this.soundService.getSound(Sound.MINI_GAME_BG_MUSIC) is undefined.

This totally depends on what happens inside soundService service. If loadSound is asynchronous, and ngOnDestroy was called before a resource was loaded, there may be problems.

Body:
Just a generic question regarding the two Lifecycle Hooks OnInit and OnDestroy. As this article mentions, I had always assumed that OnInit is  always run before the OnDestroy.

I have a case where in an ngOnDestroy() I'm stopping a background music track from playing. This sound is loaded the component's ngOnInit(), and because the ngOnDestroy() is being run without the ngOnInit() being run the sound object is undefined.

Code

ngOnInit() {
    ...

    this.loadSounds();

    ...
}

ngOnDestroy() {
    if (AppSettings.SOUNDS_ENABLED) {
        this.soundService.getSound(Sound.MINI_GAME_BG_MUSIC).fade(0.2, 0, 1500);
    }
}

private loadSounds() {
    this.soundService.loadSound(Sound.MINI_GAME_BG_MUSIC, SoundPathURL.MINI_GAME_BG_MUSIC, true, 0);
}

At the moment the code is failing in the ngOnDestroy when trying to .fade() a sound that's undefined. Of course I can easily fix this by checking that the sound is not undefined before executing the .fade() function. My assumption was that if an ngOnDestroy() is run the ngOnInit() must have been run as well - I guess I was wrong.

Now because of this case I'm thinking that in every ngOnDestroy() in my application I should check whether the object being used is undefined before performing any operations. So for example before unsubscribing from a subscription I should check if the subscription is undefined, and so on.

Am I right to assume so?


问:
ArgumentOutOfRangeException parameter name: Index
I keep getting this 'ArgumentOutOfRange exception non-negative number required, Parameter name: index', whenever I try to open the page and I can't seem to figure out where/how exactly the negative number is appearing.  Thank you all in advance!!

```<code>var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
var upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));
</code>```

I'm getting the exception when the code reads the 'upcomingMonths' variable.

stack trace:

```<code>[ArgumentOutOfRangeException: Non-negative number required. Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +4951591
InitializeChartBC()
Page_Load(Object sender, EventArgs e)
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811
</code>```

答:
According to Documentation header of the List

```<code>// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     index is less than 0.-or-count is less than 0.
</code>```

So I think months doesn't contain Current Month.
Before you call the months.GetRange check whether it contains current month and then call the GetRange.

```<code>var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
 //Anyone corrent me as the list is converted to **.ToList** it wont throw null error I feel
List<T> upcomingMonths = null;  //Where T is the type of the list
if(months.IndexOf(DateTime.Today.Month)>=0)
      upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));
</code>```

Body:
I keep getting this 'ArgumentOutOfRange exception non-negative number required, Parameter name: index', whenever I try to open the page and I can't seem to figure out where/how exactly the negative number is appearing.  Thank you all in advance!!

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
var upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));

I'm getting the exception when the code reads the 'upcomingMonths' variable.

stack trace:

[ArgumentOutOfRangeException: Non-negative number required. Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +4951591
InitializeChartBC()
Page_Load(Object sender, EventArgs e)
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811

Body:
According to Documentation header of the List

// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     index is less than 0.-or-count is less than 0.

So I think months doesn't contain Current Month.
Before you call the months.GetRange check whether it contains current month and then call the GetRange.

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
 //Anyone corrent me as the list is converted to **.ToList** it wont throw null error I feel
List<T> upcomingMonths = null;  //Where T is the type of the list
if(months.IndexOf(DateTime.Today.Month)>=0)
      upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));


问:
Failed OpenCV install unable to uninstall
While installing opencv_contrib (during make -j5 step), my laptop went to sleep and gave errors on the install, failing with a fatal error.
Retrying make -j5 gave the same error again. trying to uninstall opencv completely using make uninstall also completely fails with a fatal error.

How do I do a fresh install of OpenCV from here?

Error on running make uninstall:

```<code>-- Uninstalling "/usr/local/include/opencv2/cvconfig.h"
CMake Error at cmake_uninstall.cmake:20 (MESSAGE):
  Problem when removing "/usr/local/include/opencv2/cvconfig.h"

CMakeFiles/uninstall.dir/build.make:57: recipe for target
'CMakeFiles/uninstall' failed
make[3]: *** [CMakeFiles/uninstall] Error 1
CMakeFiles/Makefile2:296: recipe for target
'CMakeFiles/uninstall.dir/all' failed
make[2]: *** [CMakeFiles/uninstall.dir/all] Error 2
CMakeFiles/Makefile2:303: recipe for target
'CMakeFiles/uninstall.dir/rule' failed
make[1]: *** [CMakeFiles/uninstall.dir/rule] Error 2
Makefile:234: recipe for target 'uninstall' failed
make: *** [uninstall] Error 2
</code>```

答: You can't directly delete files from usr/local/...etc so you try giving sudo make uninstall it will work fine!

Body:
While installing opencv_contrib (during make -j5 step), my laptop went to sleep and gave errors on the install, failing with a fatal error.
Retrying make -j5 gave the same error again. trying to uninstall opencv completely using make uninstall also completely fails with a fatal error.

How do I do a fresh install of OpenCV from here?

Error on running make uninstall:

-- Uninstalling "/usr/local/include/opencv2/cvconfig.h"
CMake Error at cmake_uninstall.cmake:20 (MESSAGE):
  Problem when removing "/usr/local/include/opencv2/cvconfig.h"

CMakeFiles/uninstall.dir/build.make:57: recipe for target
'CMakeFiles/uninstall' failed
make[3]: *** [CMakeFiles/uninstall] Error 1
CMakeFiles/Makefile2:296: recipe for target
'CMakeFiles/uninstall.dir/all' failed
make[2]: *** [CMakeFiles/uninstall.dir/all] Error 2
CMakeFiles/Makefile2:303: recipe for target
'CMakeFiles/uninstall.dir/rule' failed
make[1]: *** [CMakeFiles/uninstall.dir/rule] Error 2
Makefile:234: recipe for target 'uninstall' failed
make: *** [uninstall] Error 2


问:
Disabled <input> that allows text selection?
Is it possible for a disabled <input> tag to support text selection?

答:
Based on the HTML spec, it looks like no:

Disabled controls do not receive focus.

Disabled controls are skipped in tabbing navigation.

Disabled controls cannot be successful.

Are you able to use the readonly attribute instead?

(Wow, "4 new answers have been posted"... I think the spec link is helpful, at least.)

ContentLicense: CC BY-SA 2.5


问:
git rebase --onto crashes only on long branches
I'm having problems to make a simple git rebase (no conflicts involved) when the rebased branch has too many commits. I couldn't find a similar error on stackoverflow neither on google.

I've found the problem trying to rebase a long branch (really?) with 71 commits:

```<code>$ git clone git@myrepo.com/project.git
$ cd project
$ git checkout develop
$ vim README.md # just a simple text update on tracked file
$ git add README.md
$ git commit -m "crash test"
$ git checkout feature/branch-to-be-rebased
$ git rebase --onto develop feature/big-branch-to-be-rebased~71

First, rewinding head to replay your work on top of it...
Applying: commit 01
Applying: commit 02
Applying: commit 03
...
Applying: commit 20
Assertion failed: (postlen ? fixed_preimage.nr == preimage->nr : fixed_preimage.nr <= preimage->nr), function update_pre_post_images, file apply.c, line 2322.
/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git-rebase--am: line 16: 44878 Abort trap: 6           git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" ${gpg_sign_opt:+"$gpg_sign_opt"} < "$GIT_DIR/rebased-patches"
</code>```

git rebase is working properly when the branch is short (it worked on 8 commits branch).

My OS is a Sierra 10.12.6

```<code>$ git --version
git version 2.13.6 (Apple Git-96)
</code>```

Same thing happened using up to date brew's git version:

```<code>$ /usr/local/Cellar/git/2.15.0/bin/git --version
git version 2.15.0
</code>```

I know some people will have different opinions about git workflow, but the point of this question is purely technical. So I'm not interested on workarounds like squash, cherry-pick, etc.

Is there a way to fix this crash? Does git rebase have some sort of upper limit on the number of commits it can handle? Is this a known bug?

答:
Is there a way to fix this crash?

Repair the bug in Git, of course.  (You said you are not interested in workarounds, but this appears to come from having --whitespace=fix as a command line argument, or setting apply.whitespace=fix in your configuration.  Eliminating that will probably sidestep the problem.)

Does git rebase have some sort of upper limit on the number of commits it can handle?

No.

Is this a known bug?

Well, it is now. :-)  Without a good reproducer, though, I'm not sure if anyone else can fix it.  (So perhaps this depends on what you mean by "known bug": your example shows that there is a bug in the whitespace-fixing code, but it's not clear what the bug is, yet.)

Body:
I'm having problems to make a simple git rebase (no conflicts involved) when the rebased branch has too many commits. I couldn't find a similar error on stackoverflow neither on google.

I've found the problem trying to rebase a long branch (really?) with 71 commits:

$ git clone git@myrepo.com/project.git
$ cd project
$ git checkout develop
$ vim README.md # just a simple text update on tracked file
$ git add README.md
$ git commit -m "crash test"
$ git checkout feature/branch-to-be-rebased
$ git rebase --onto develop feature/big-branch-to-be-rebased~71

First, rewinding head to replay your work on top of it...
Applying: commit 01
Applying: commit 02
Applying: commit 03
...
Applying: commit 20
Assertion failed: (postlen ? fixed_preimage.nr == preimage->nr : fixed_preimage.nr <= preimage->nr), function update_pre_post_images, file apply.c, line 2322.
/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git-rebase--am: line 16: 44878 Abort trap: 6           git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" ${gpg_sign_opt:+"$gpg_sign_opt"} < "$GIT_DIR/rebased-patches"

git rebase is working properly when the branch is short (it worked on 8 commits branch).

My OS is a Sierra 10.12.6

$ git --version
git version 2.13.6 (Apple Git-96)

Same thing happened using up to date brew's git version:

$ /usr/local/Cellar/git/2.15.0/bin/git --version
git version 2.15.0

I know some people will have different opinions about git workflow, but the point of this question is purely technical. So I'm not interested on workarounds like squash, cherry-pick, etc.

Is there a way to fix this crash? Does git rebase have some sort of upper limit on the number of commits it can handle? Is this a known bug?


问:
No shadows around window when I start program without desktop environment in Ubuntu
OS: Ubuntu 16.04

I wrote a Qt program and run it without desktop environment.

This is my question about how to run it without desktop environment.

How can I run my GUI application without desktop enviroment and make it fullscreen?

Shortly, I do this by two steps:

add a lightdm.conf in /etc/lightdm to start my xsession;

add a .desktop file in /usr/share/xsession to start my program:

2.1 start compiz as window manager;

2.2 start my program.

the last two lines in the script is like:

```<code>compiz&
/home/kevin/myapp
</code>```

Now I have another question.

When a window pops up in my program, there is no shadow around the window, just like a program in the desktop environment.

So, there is no clear border between the popped up window and its parent window.

But, when I run it in the desktop environment, there IS shadow around the popped up window.

How can I have shadow around the popped window?

答:
Boiling your question down to its essentials, what you're asking is why, when you run your X11 program without a window manager, you do not get the Window manager's decorations. The answer is, of course, "because there is no window manager".

https://en.wikipedia.org/wiki/X_window_manager

In a nutshell, X11 windows are just rectangles (usually) that allow an application to draw in exclusive areas, without interfering with other applications. It manages input like you're used to, but visually, it's just rectangles.

X11 does allow a special program to run, referred to as a Window Manager. This program gets to know whenever you want to display a window, and gets to do stuff to that window. In particular, the standard thing to do is to wrap your window inside the window manager's window, and display a bunch of controls for your window. These include maximize, minimize, close, an easy way to move the window around, resize etc.

You can see this extra window by using a program called xwininfo. You will see that, when you run your program without a manger, it's just your window. When you run it with a manager, your window is a child for one or more (depending on the WM) other windows.

The shadow you talk about is also something that your window manager does. If you run without it, you will not get it.

As for solutions, I can think of two:

Write your own mini-window manager. This can either be an official window manager, or just wrap your own application window with a bigger window that adds one pixel of black border.

or

Use a window manager, and ask it not to add its controls to your window. Precise details vary slightly between window managers, but the DOCK window type might do what you want.

ContentLicense: CC BY-SA 4.0

Body:
OS: Ubuntu 16.04

I wrote a Qt program and run it without desktop environment.

This is my question about how to run it without desktop environment.

How can I run my GUI application without desktop enviroment and make it fullscreen?

Shortly, I do this by two steps:

add a lightdm.conf in /etc/lightdm to start my xsession;

add a .desktop file in /usr/share/xsession to start my program:

2.1 start compiz as window manager;

2.2 start my program.

the last two lines in the script is like:

compiz&
/home/kevin/myapp

Now I have another question.

When a window pops up in my program, there is no shadow around the window, just like a program in the desktop environment.

So, there is no clear border between the popped up window and its parent window.

But, when I run it in the desktop environment, there IS shadow around the popped up window.

How can I have shadow around the popped window?


问:
XSLT append URL from relative to absolute
In my XML document, I am pulling the content of a <TextBlock> that contains images. The XML shows:

```<code><img src="/templates_soft/images/facebook.png" alt="twitter" />
</code>```

When I view the page, the image doesn't show up because it is not at the same path as the original page.

I need to add the rest of the URL for the images to display. Something like http://www.mypage.com/ so that the image displays from http://www.mypage.com/templates_soft/images/facebook.png

Is there a way to do this?

答:
Use:

```<code><img src="{$imageBase/}templates_soft/images/facebook.png" alt="twitter" />
</code>```

where the xsl:variable named $imageBase is defined to contain the necessary prefix (in your case "http://www.mypage.com").

Here is a complete XSLT solution:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pimageBase" select="'http://www.mypage.com'"/>

    <xsl:template match="img">
   <img src="{concat($pimageBase, @src)}" alt="{@alt}"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

when this transformation is applied on the following XML document:

```<code><img src="/templates_soft/images/facebook.png" alt="twitter" />
</code>```

the wanted, correct result is produced:

```<code><img src="http://www.mypage.com/templates_soft/images/facebook.png" alt="twitter"/>
</code>```

Body:
In my XML document, I am pulling the content of a <TextBlock> that contains images. The XML shows:

When I view the page, the image doesn't show up because it is not at the same path as the original page.

I need to add the rest of the URL for the images to display. Something like http://www.mypage.com/ so that the image displays from http://www.mypage.com/templates_soft/images/facebook.png

Is there a way to do this?

Body:
Use:

<img src="{$imageBase/}templates_soft/images/facebook.png" alt="twitter" />

where the xsl:variable named $imageBase is defined to contain the necessary prefix (in your case "http://www.mypage.com").

Here is a complete XSLT solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pimageBase" select="'http://www.mypage.com'"/>

    <xsl:template match="img">
   <img src="{concat($pimageBase, @src)}" alt="{@alt}"/>
  </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<img src="/templates_soft/images/facebook.png" alt="twitter" />

the wanted, correct result is produced:

<img src="http://www.mypage.com/templates_soft/images/facebook.png" alt="twitter"/>


问:
TypeLoadException on Attribute in shared assembly

UPDATE 10:29 MST on 11/7

Oddly enough if I move the attribute out of the ComponentModel folder back into the root of the Common project the code works fine. I can't imagine what's possibly referencing the old namespace after all of the references were refactored for the InflowHealth.Common.ComponentModel namespace.

It's almost like there is some reference hiding somewhere that's not code-based but rather runtime and dynamic, but I sure don't see it when looking through all find results of InflowHealthErrorContext.

UPDATE 19:33 MST on 11/6

Of new interest, when I commented out the line to use the custom attribute to inherit routes, and use the default one, it still blew up. Of further interest, the namespace it's looking for InflowHealth.Common.InflowHealthErrorContextAttribute is actually the old FQN before I refactored it and moved it to a folder (and namespace) ComponentModel.

UPDATE 07:42 MST on 11/6

I believe I've identified that the issue is related to another custom attribute I'm using to inherit actions. This attribute is added to the HttpConfiguration like this:

```<code>public static void MapInheritedAttributeRoutes(this HttpConfiguration config)
{
    config.MapHttpAttributeRoutes(new InheritanceDirectRouteProvider());
}
</code>```

The implementation of that attribute is pretty simple:

```<code>public class InheritanceDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
    {
        return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(true);
    }
}
</code>```

It appears that inheriting this InflowHealthErrorContext attribute is causing issues, but I'm not sure exactly what the issue is. I've tried:

Removing Inherited = false so that it is inheritable.

Removing AllowMultiple = true just because that was misconfigured.

Those did not change the error.

ORIGINAL POST

I have a very simple attribute in a Common assembly shared by a couple Web API applications. As simple as this is I just can't figure out what would cause this exception.

I have tried to collect Fusion logs on this, but it's not logging them.

This is the Attribute:

```<code>using System;

namespace InflowHealth.Common.ComponentModel
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public sealed class InflowHealthErrorContextAttribute : Attribute
    {
        // This is a positional argument
        public InflowHealthErrorContextAttribute(string errorContext)
        {
            ErrorContext = errorContext;
        }

        public string ErrorContext { get; }
    }
}
</code>```

This would be used on a route to later provide some extra context to the automated error logging done inside of a filter:

```<code>[Authorize(Roles = Roles.ALL_ADMINS)]
[Route("api/ControlPanelApi/PayerClassifications")]
[InflowHealthErrorContext("Error getting payer classifications.")]
public IHttpActionResult GetPayerClassifications(int clientId, bool showAllRows)
{
    return Ok(GetData(payerClassificationManager, clientId, showAllRows));
}
</code>```

Upon loading the application, when Web API Routes are registered, it fails. Here is the line it's breaking on:

```<code>GlobalConfiguration.Configure(WebApiConfig.Register);
</code>```

It's throwing this exception:

Could not load type 'InflowHealth.Common.InflowHealthErrorContextAttribute' from assembly 'InflowHealth.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

This is the stack trace:

```<code>   at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
   at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
   at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
   at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit)
   at System.Reflection.RuntimeMethodInfo.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Attribute.GetCustomAttribute(MemberInfo element, Type attributeType, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttribute[T](MemberInfo element)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.IsValidActionMethod(MethodInfo methodInfo)
   at System.Array.FindAll[T](T[] array, Predicate`1 match)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetActionMapping(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, HttpConfiguration configuration, IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<>c__DisplayClass4.<MapAttributeRoutes>b__1()
   at System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<MapAttributeRoutes>b__0(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration.EnsureInitialized()
   at System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback)
   at InflowHealthPortal.MvcApplication.Application_Start() in Global.asax.cs:line 22
</code>```

答:
I would suggest you delete the bin and obj folders and rebuild the project.

This issue sometimes happened when there was a stray dll hanging around that was not overwritten when the projects were compiled. Usually when renaming output files.

Performing the above actions have worked for me in the past when it came to references not reflecting the changes made to code and recompilation.

The same sometimes happened with Nuget packages and this would result in having to remove the package and re-installing it in order for the correct dlls to be referenced.

Body:
UPDATE 10:29 MST on 11/7

Oddly enough if I move the attribute out of the ComponentModel folder back into the root of the Common project the code works fine. I can't imagine what's possibly referencing the old namespace after all of the references were refactored for the InflowHealth.Common.ComponentModel namespace.

It's almost like there is some reference hiding somewhere that's not code-based but rather runtime and dynamic, but I sure don't see it when looking through all find results of InflowHealthErrorContext.

UPDATE 19:33 MST on 11/6

Of new interest, when I commented out the line to use the custom attribute to inherit routes, and use the default one, it still blew up. Of further interest, the namespace it's looking for InflowHealth.Common.InflowHealthErrorContextAttribute is actually the old FQN before I refactored it and moved it to a folder (and namespace) ComponentModel.

UPDATE 07:42 MST on 11/6

I believe I've identified that the issue is related to another custom attribute I'm using to inherit actions. This attribute is added to the HttpConfiguration like this:

public static void MapInheritedAttributeRoutes(this HttpConfiguration config)
{
    config.MapHttpAttributeRoutes(new InheritanceDirectRouteProvider());
}

The implementation of that attribute is pretty simple:

public class InheritanceDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
    {
        return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(true);
    }
}

It appears that inheriting this InflowHealthErrorContext attribute is causing issues, but I'm not sure exactly what the issue is. I've tried:

Removing Inherited = false so that it is inheritable.

Removing AllowMultiple = true just because that was misconfigured.

Those did not change the error.

ORIGINAL POST

I have a very simple attribute in a Common assembly shared by a couple Web API applications. As simple as this is I just can't figure out what would cause this exception.

I have tried to collect Fusion logs on this, but it's not logging them.

This is the Attribute:

using System;

namespace InflowHealth.Common.ComponentModel
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public sealed class InflowHealthErrorContextAttribute : Attribute
    {
        // This is a positional argument
        public InflowHealthErrorContextAttribute(string errorContext)
        {
            ErrorContext = errorContext;
        }

        public string ErrorContext { get; }
    }
}

This would be used on a route to later provide some extra context to the automated error logging done inside of a filter:

[Authorize(Roles = Roles.ALL_ADMINS)]
[Route("api/ControlPanelApi/PayerClassifications")]
[InflowHealthErrorContext("Error getting payer classifications.")]
public IHttpActionResult GetPayerClassifications(int clientId, bool showAllRows)
{
    return Ok(GetData(payerClassificationManager, clientId, showAllRows));
}

Upon loading the application, when Web API Routes are registered, it fails. Here is the line it's breaking on:

GlobalConfiguration.Configure(WebApiConfig.Register);

It's throwing this exception:

Could not load type 'InflowHealth.Common.InflowHealthErrorContextAttribute' from assembly 'InflowHealth.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

This is the stack trace:

   at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
   at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
   at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
   at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit)
   at System.Reflection.RuntimeMethodInfo.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Attribute.GetCustomAttribute(MemberInfo element, Type attributeType, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttribute[T](MemberInfo element)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.IsValidActionMethod(MethodInfo methodInfo)
   at System.Array.FindAll[T](T[] array, Predicate`1 match)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetActionMapping(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, HttpConfiguration configuration, IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<>c__DisplayClass4.<MapAttributeRoutes>b__1()
   at System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<MapAttributeRoutes>b__0(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration.EnsureInitialized()
   at System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback)
   at InflowHealthPortal.MvcApplication.Application_Start() in Global.asax.cs:line 22


问:
Configure logback.xml to split logs based on packages without overlapping information
I want to log everything of a package a into the logfile a.loq and all the rest (without any logs of a) into the standard.log file. So far I have got the a.log file but the standard log is still conaining everything of package a.

```<code><logger name="my.package.a" level="INFO" additivity="false">
    <appender-ref ref="FILE-A"/>
</logger>

<root level="INFO">
    <appender-ref ref="FILE-STD"/>
</root>
</code>```

答:
From documentation:

logger has its additivity flag set to false such that its logging output will be sent to the appender named FILE but not to any appender attached higher in the hierarchy

So, it's all about ordering of appenders and loggers in your logback.xml.

Appenders should be declared higher than this logger.

Body:
I want to log everything of a package a into the logfile a.loq and all the rest (without any logs of a) into the standard.log file. So far I have got the a.log file but the standard log is still conaining everything of package a.

<logger name="my.package.a" level="INFO" additivity="false">
    <appender-ref ref="FILE-A"/>
</logger>

<root level="INFO">
    <appender-ref ref="FILE-STD"/>
</root>


问:
Multi-Line Dictionary to Single-Line Dictionary
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

```<code>{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
</code>```

...and so on for over 100 hundred lines. How do you convert this to the following form:

```<code>{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}
</code>```

答:
Assuming you are asking for multiple dictionaries (not multiple line dictionary) to one dictionary.

```<code>a = {1: 1, 2:2}
b = {2:2, 3:3}
c = {2:3}
{**a, **b, **c}

Out: {1: 1, 2: 3, 3: 3}
</code>```

Body:
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}

...and so on for over 100 hundred lines. How do you convert this to the following form:

{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}

Body:
Assuming you are asking for multiple dictionaries (not multiple line dictionary) to one dictionary.

a = {1: 1, 2:2}
b = {2:2, 3:3}
c = {2:3}
{**a, **b, **c}

Out: {1: 1, 2: 3, 3: 3}


问:
Use EXISTS in SQL for multiple select
I have a table STATUSES which contain columns NAME and ACTIVE_FLAG.The column value of NAME may have new, pending, cancel. I want to generate a new output for the count of each NAME with ACTIVE_FLAG=Y

By thinking to use EXISTS to select records for single NAME,

```<code>SELECT COUNT(*) AS PENDING
FROM STATUSES
WHERE EXISTS (select NAME from STATUSES where NAME='Pending' and ACTIVE_FLAG = 'Y')
</code>```

Anyway if I can join other statuses count in a single SQL?

答:
You can use something like this as i don't see any need to use EXISTS :

```<code>SELECT sum(case when name='Pending' then 1 else 0 end) AS PENDING,
sum(case when name='new' then 1 else 0 end) AS NEW,
sum(case when name='cancel' then 1 else 0 end) AS CANCEL
FROM STATUSES
WHERE ACTIVE_FLAG = 'Y'
</code>```

SQL HERE

Title: Use EXISTS in SQL for multiple select

Body:
I have a table STATUSES which contain columns NAME and ACTIVE_FLAG.The column value of NAME may have new, pending, cancel. I want to generate a new output for the count of each NAME with ACTIVE_FLAG=Y

By thinking to use EXISTS to select records for single NAME,

SELECT COUNT(*) AS PENDING
FROM STATUSES
WHERE EXISTS (select NAME from STATUSES where NAME='Pending' and ACTIVE_FLAG = 'Y')

Anyway if I can join other statuses count in a single SQL?

Body:
You can use something like this as i don't see any need to use EXISTS :

SELECT sum(case when name='Pending' then 1 else 0 end) AS PENDING,
sum(case when name='new' then 1 else 0 end) AS NEW,
sum(case when name='cancel' then 1 else 0 end) AS CANCEL
FROM STATUSES
WHERE ACTIVE_FLAG = 'Y'

SQL HERE


问:
Pandas dataframe get index and header when in multiple columns
I have a dataframe which looks like this:

```<code>d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None
</code>```

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

答:
```<code>df[df.notnull().sum(1)>1].stack().reset_index().\
     groupby('id')['level_1'].apply(list).to_dict()
Out[382]: {'G': ['Person1', 'Person2'], 'Mc': ['Person1', 'Person2', 'Person3']}
</code>```

Body:
I have a dataframe which looks like this:

d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.


问:
Make an algorithm start again?
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

```<code>// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
</code>```

答:
Use hasNextInt() and a while loop to iterate over the data:

```<code>while (sc.hasNextInt()) {
    int aInt = sc.nextInt();
    //logic here
}
</code>```

Documentation for hasNextInt() method:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()

Title: Make an algorithm start again?

Body:
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant

Body:
Use hasNextInt() and a while loop to iterate over the data:

while (sc.hasNextInt()) {
    int aInt = sc.nextInt();
    //logic here
}

Documentation for hasNextInt() method:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()


问:
Getting Commit ID in CodePipeline
I am using CodePipeline with CodeCommit. Builds are triggered automatically with push to master branch. In CodePipeline console it is clearly visible that i am receiving commit id but i need to get it in the build environment so i can add them as a tag to the ECS image when i build it. Is there a way to get in in build environment.

答:
Is this what you're looking for?

http://docs.aws.amazon.com/codepipeline/latest/userguide/monitoring-source-revisions-view.html#monitoring-source-revisions-view-cli

Most (if not all) of the language SDKs have this API built in also.

Title: Getting Commit ID in CodePipeline


问:
Error request Alamofire + Basic Auth
I'm trying to make this request but only returns error 401, is the request correct? I have to use Basic Auth

```<code>    var user = ""
    var password = ""

    user = textField.text!
    password = textField2.text!

    print(user)
    print(password)

    let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
    print(credentialData)
    let base64Credentials = credentialData.base64EncodedString(options: [])
    print(base64Credentials)
    let headers: HTTPHeaders = ["Authorization":" Basic \(base64Credentials)"]

    print(headers)

    Alamofire.request("https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me", headers: headers)
        .validate().responseJSON { response in
            switch response.result {

            case .success:
                print("Validation Successful")
                let viewController: UIViewController = self.storyboard!.instantiateViewController(withIdentifier: "SideNavigationController")
                self.present(viewController, animated: true, completion: { _ in })

            case .failure(let error):
                print(error.localizedDescription)
                self.alertLabel.isHidden = false
            }
    }
</code>```

It only returns me error 401.

It's correct part of HTTPHeaders?

答:
Make small changes in your code and it will work.</p>

```<code>var user = ""
var password = ""

user = textField.text!
password = textField2.text!

print(user)
print(password)

let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
print(credentialData)

let base64Credentials = credentialData.base64EncodedString(options: [])
print(base64Credentials)

let url: String = "https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me"

var request = URLRequest(url:  NSURL(string: url)! as URL)
request.httpMethod = "GET"
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

Alamofire.request(request)
    .validate().responseJSON { response in
        switch response.result {

        case .success:
            print("Validation Successful")
            // Your desired functionality

        case .failure(let error):
            print(error.localizedDescription)
            // Your desired functionality

        }
}
</code>```

Title: Error request Alamofire + Basic Auth

Body:
I'm trying to make this request but only returns error 401, is the request correct? I have to use Basic Auth

    var user = ""
    var password = ""

    user = textField.text!
    password = textField2.text!

    print(user)
    print(password)

    let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
    print(credentialData)
    let base64Credentials = credentialData.base64EncodedString(options: [])
    print(base64Credentials)
    let headers: HTTPHeaders = ["Authorization":" Basic \(base64Credentials)"]

    print(headers)

    Alamofire.request("https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me", headers: headers)
        .validate().responseJSON { response in
            switch response.result {

            case .success:
                print("Validation Successful")
                let viewController: UIViewController = self.storyboard!.instantiateViewController(withIdentifier: "SideNavigationController")
                self.present(viewController, animated: true, completion: { _ in })

            case .failure(let error):
                print(error.localizedDescription)
                self.alertLabel.isHidden = false
            }
    }

It only returns me error 401.

It's correct part of HTTPHeaders?

Body:
Make small changes in your code and it will work.

var user = ""
var password = ""

user = textField.text!
password = textField2.text!

print(user)
print(password)

let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
print(credentialData)

let base64Credentials = credentialData.base64EncodedString(options: [])
print(base64Credentials)

let url: String = "https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me"

var request = URLRequest(url:  NSURL(string: url)! as URL)
request.httpMethod = "GET"
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

Alamofire.request(request)
    .validate().responseJSON { response in
        switch response.result {

        case .success:
            print("Validation Successful")
            // Your desired functionality

        case .failure(let error):
            print(error.localizedDescription)
            // Your desired functionality

        }
}


问:
How to make API calls using React, Redux in TypeScript
I'm using typescript-fsa and typescript-fsa-reducers packages to simply create actions and reducers in TypeScript React application.

```<code>const actionCreator = actionCreatorFactory();

export function signInHandler(state: UserState, action: Action): UserState {
    // ????

    return { ...state };
}

export const signIn = actionCreator.async<SignInRequest, RequestResponse<SignInResponse>>("USER_SIGNIN");

export const UserReducer = reducerWithInitialState({ signedIn: false } as UserState)
    .casesWithAction([signIn.started, signIn.done], signInHandler)
    .build();
</code>```

Usage in component:

```<code>export default connect<StateProps, DispatchProps>(
  (state: RootState) => ({} as StateProps),
  (dispatch: Dispatch<RootState>) => {
     return {
              signIn: (userName: string, password: string) => dispatch(signIn.started(new SignInRequest(userName, password)))
    };
  }
)(SignIn);
</code>```

And now I'm stuck. I don't know how to make HTTP calls to my API so I can send request when component dispatches action on dispatch next action when response from API arrives. I would like to use promises.
How to solve that?

答:
In React without the typescript-fsa abstraction, you'd make async API callsat the action creator level, since actions are just dispatched POJOs and reducers are supposed to not have any side effects.

There are two projects that make it easy to do this, redux-thunk and redux-saga.  I prefer redux-thunk because it is easier to wrap your head around.  Basically your action creators get passed the dispatch function, and then they can be responsible for dispatching more than one thing... like so:

```<code>function asyncActionCreator(dispatch) {
  dispatch(startAsyncAction());

  doSomethingAsync()
    .then(result => dispatch(completeAsyncAction(result))
    .catch(err => dispatch(errorAsyncAction(err));
}
</code>```

In your typescript-fsa world, there are some companion packages for both of these: typescript-fsa-redux-thunk and typescript-fsa-redux-saga.

It appears that typescript-fsa-redux-thunk takes a similar approach to the above example, using the concept of an "action worker", which coordinates the dispatching of actions via typescript-fsa.  There is a really good example of doing this on the typescript-fsa-redux-thunk repo.

Body:
I'm using typescript-fsa and typescript-fsa-reducers packages to simply create actions and reducers in TypeScript React application.

const actionCreator = actionCreatorFactory();

export function signInHandler(state: UserState, action: Action): UserState {
    // ????

    return { ...state };
}

export const signIn = actionCreator.async<SignInRequest, RequestResponse<SignInResponse>>("USER_SIGNIN");

export const UserReducer = reducerWithInitialState({ signedIn: false } as UserState)
    .casesWithAction([signIn.started, signIn.done], signInHandler)
    .build();

Usage in component:

export default connect<StateProps, DispatchProps>(
  (state: RootState) => ({} as StateProps),
  (dispatch: Dispatch<RootState>) => {
     return {
              signIn: (userName: string, password: string) => dispatch(signIn.started(new SignInRequest(userName, password)))
    };
  }
)(SignIn);

And now I'm stuck. I don't know how to make HTTP calls to my API so I can send request when component dispatches action on dispatch next action when response from API arrives. I would like to use promises.
How to solve that?

Body:
In React without the typescript-fsa abstraction, you'd make async API callsat the action creator level, since actions are just dispatched POJOs and reducers are supposed to not have any side effects.

There are two projects that make it easy to do this, redux-thunk and redux-saga.  I prefer redux-thunk because it is easier to wrap your head around.  Basically your action creators get passed the dispatch function, and then they can be responsible for dispatching more than one thing... like so:

function asyncActionCreator(dispatch) {
  dispatch(startAsyncAction());

  doSomethingAsync()
    .then(result => dispatch(completeAsyncAction(result))
    .catch(err => dispatch(errorAsyncAction(err));
}

In your typescript-fsa world, there are some companion packages for both of these: typescript-fsa-redux-thunk and typescript-fsa-redux-saga.

It appears that typescript-fsa-redux-thunk takes a similar approach to the above example, using the concept of an "action worker", which coordinates the dispatching of actions via typescript-fsa.  There is a really good example of doing this on the typescript-fsa-redux-thunk repo.


问:
How can I get an oauth2 access_token using Python
For a project someone gave me this data that I have used in Postman for testing purposes:

In Postman this works perfectly.

Auth URL: https://api.example.com/oauth/access_token

Access Token URL: https://api.example.com/access_token

client ID: abcde

client secret: 12345

Token name: access_token

Grant type: Client Credentials

All I need is to get back the access token.

Once, I got the access token I can continue.

I have already tried several Python packages and some custom code, but somehow this seemingly simple task starts to create a real headache.

One exemple I tried:

```<code>import httplib
import base64
import urllib
import json

def getAuthToken():
    CLIENT_ID = "abcde"
    CLIENT_SECRET = "12345"
    TOKEN_URL = "https://api.example.com/oauth/access_token"

    conn = httplib.HTTPSConnection("api.example.com")

    url = "/oauth/access_token"

    params = {
        "grant_type": "client_credentials"
    }

    client = CLIENT_ID
    client_secret = CLIENT_SECRET

    authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')

    requestUrl = url + "?" + urllib.urlencode(params)

    headersMap = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic " + authString
    }

    conn.request("POST", requestUrl, headers=headersMap)

    response = conn.getresponse()

    if response.status == 200:
        data = response.read()
        result = json.loads(data)

        return result["access_token"]
</code>```

Then I have got this one:

```<code>import requests
import requests.auth

CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"

def get_token(code):
    client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
    post_data = {"grant_type": "client_credentials",
                 "code": code,
                 "redirect_uri": REDIRECT_URI}
    response = requests.post(TOKEN_URL,
                             auth=client_auth,
                             data=post_data)
    token_json = response.json()
    return token_json["access_token"]
</code>```

If this would work, what should I put into the code parameter

I really hope someone can help me out here.

Thanks in advance.

答:
Simply (in case of Facebook Authentication):

```<code>import requests, json

access_token = requests.get("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret").json()["access_token"]
</code>```

Or you can use rauth library.

In the docs there is an interesting example with facebook oAuth2 authentication:

```<code>from rauth import OAuth2Service

facebook = OAuth2Service(
client_id='your_client_id',
client_secret='your_client_secret',
name='facebook',
authorize_url='https://graph.facebook.com/oauth/authorize',
access_token_url='https://graph.facebook.com/oauth/access_token',
base_url='https://graph.facebook.com/')
</code>```

and after open a session:

```<code>session = facebook.get_auth_session(data={'code': 'foo','redirect_uri': redirect_uri})
</code>```

in the session json there is your access token

Body:
For a project someone gave me this data that I have used in Postman for testing purposes:

In Postman this works perfectly.

Auth URL: https://api.example.com/oauth/access_token

Access Token URL: https://api.example.com/access_token

client ID: abcde

client secret: 12345

Token name: access_token

Grant type: Client Credentials

All I need is to get back the access token.

Once, I got the access token I can continue.

I have already tried several Python packages and some custom code, but somehow this seemingly simple task starts to create a real headache.

One exemple I tried:

import httplib
import base64
import urllib
import json

def getAuthToken():
    CLIENT_ID = "abcde"
    CLIENT_SECRET = "12345"
    TOKEN_URL = "https://api.example.com/oauth/access_token"

    conn = httplib.HTTPSConnection("api.example.com")

    url = "/oauth/access_token"

    params = {
        "grant_type": "client_credentials"
    }

    client = CLIENT_ID
    client_secret = CLIENT_SECRET

    authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')

    requestUrl = url + "?" + urllib.urlencode(params)

    headersMap = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic " + authString
    }

    conn.request("POST", requestUrl, headers=headersMap)

    response = conn.getresponse()

    if response.status == 200:
        data = response.read()
        result = json.loads(data)

        return result["access_token"]

Then I have got this one:

import requests
import requests.auth

CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"

def get_token(code):
    client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
    post_data = {"grant_type": "client_credentials",
                 "code": code,
                 "redirect_uri": REDIRECT_URI}
    response = requests.post(TOKEN_URL,
                             auth=client_auth,
                             data=post_data)
    token_json = response.json()
    return token_json["access_token"]

If this would work, what should I put into the code parameter

I really hope someone can help me out here.

Thanks in advance.

Body:
Simply (in case of Facebook Authentication):

import requests, json

access_token = requests.get("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret").json()["access_token"]

Or you can use rauth library.

In the docs there is an interesting example with facebook oAuth2 authentication:

from rauth import OAuth2Service

facebook = OAuth2Service(
client_id='your_client_id',
client_secret='your_client_secret',
name='facebook',
authorize_url='https://graph.facebook.com/oauth/authorize',
access_token_url='https://graph.facebook.com/oauth/access_token',
base_url='https://graph.facebook.com/')

and after open a session:

session = facebook.get_auth_session(data={'code': 'foo','redirect_uri': redirect_uri})

in the session json there is your access token


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
Wrong?  Partially.

"Your codebase grows incrementally, and never has a big planning/hierarchical design stage."

Correct.

"That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring..."

Not quite correct.

There's a huge gulf between Big Design Up Front (BDUF) and a more Agile design approach.

BDUF dictates that all design is completed before any coding.  This is still popular (just read an RFP yesterday which absolutely required all design be reviewed by the customer before any coding could begin.  Sigh.)

Agile suggests that perhaps all design isn't a helpful goal.  You need to do enough design that TDD will work.  You can't, for example, start TDD until you have a working infrastructure that allows someone to write tests and incrementally evolve a solution knowing that there won't be a weird production deployment problem to solve.

Design is still king.  Agile Design is better than monolithic design.

A consequence of Agile Design is YAGNI, DRY and Less-is-More.  These don't replace design, they're a consequence of how you prioritize and do design.

BDD and TDD are ways to structure your time so you have focus on what people need, what they do and what really matters.  TDD, in particular, focuses on testable behaviors of the software.  Not zero-value nuance, but actual behavior.

Premature optimization is interesting, but unrelated.  Even Agile teams can run down a low-value rat-hole pursuing a nuance or optimization that doesn't add any value.  Premature optimization is a habit of overthinking (== "hand wringing") a technology choice without facts about actual performance.

Agile is supposed to help you focus on the big picture: What actual people will actually do with the actual software and avoid technology rat-holes.

It doesn't replace engineering.  It refocuses it.

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H


问:
error while loadin applet in web application
I want to run my applet on web application, but i got some error which i mentioned below please help me to get out of this problem

```<code>Java Plug-in 1.7.0
Using JRE version 1.7.0-ea-b116 Java HotSpot(TM) Client VM
User home directory = C:\Users\HONEY
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------

java.lang.RuntimeException: java.lang.NoClassDefFoundError: mp3$1
 at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
 at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: mp3$1
 at mp3.<init>(mp3.java:93)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
 at java.lang.reflect.Constructor.newInstance(Unknown Source)
 at java.lang.Class.newInstance0(Unknown Source)
 at java.lang.Class.newInstance(Unknown Source)
 at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
 at java.awt.event.InvocationEvent.dispatch(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: mp3$1
 at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 ... 16 more
Caused by: java.io.IOException: open HTTP connection failed:http://viscous10.webng.com/mp3/mp3$1.class
 at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
 at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
 at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 ... 21 more
Exception: java.lang.RuntimeException: java.lang.NoClassDefFoundError: mp3$1
</code>```

but it happens only if i run applet with events
and in simple applet i never occurred

答:
to run the applet on web browser

write java code run the application on java

make the class file by using cmd prompt

give proper path and run your java file on cmd prompt to create class file

make html file add applet code in it <applet code=file.class archive =file.zip/jar></applet>

enabled java console from control panel

run the html file and refresh the window

NOTE: make sure class file, html file,zip or jar file having same name for avoiding any confusion

Body:
I want to run my applet on web application, but i got some error which i mentioned below please help me to get out of this problem

Java Plug-in 1.7.0
Using JRE version 1.7.0-ea-b116 Java HotSpot(TM) Client VM
User home directory = C:\Users\HONEY
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------

java.lang.RuntimeException: java.lang.NoClassDefFoundError: mp3$1
 at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
 at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: mp3$1
 at mp3.<init>(mp3.java:93)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
 at java.lang.reflect.Constructor.newInstance(Unknown Source)
 at java.lang.Class.newInstance0(Unknown Source)
 at java.lang.Class.newInstance(Unknown Source)
 at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
 at java.awt.event.InvocationEvent.dispatch(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: mp3$1
 at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
 at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 ... 16 more
Caused by: java.io.IOException: open HTTP connection failed:http://viscous10.webng.com/mp3/mp3$1.class
 at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
 at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
 at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 ... 21 more
Exception: java.lang.RuntimeException: java.lang.NoClassDefFoundError: mp3$1

but it happens only if i run applet with events
and in simple applet i never occurred


答:
So you want to ask for input again, i assume.

A simple way could be:

```<code>int c = sc.nextInt();

while (c > 1 || c < 0) {
    c = sc.nextInt();
}
//code continues
</code>```

Title: Make an algorithm start again?

Body:
So you want to ask for input again, i assume.

A simple way could be:

int c = sc.nextInt();

while (c > 1 || c < 0) {
    c = sc.nextInt();
}
//code continues


问:
MQL4 multi-timeframe indicator
I would like to write out an indicator that can take in input the int shift of an assigned timeframe, and turns out a value related to another timeframe.

As an example, I would like to write an MACD indicator over a 100 periods of M15, that can return out its value 1,2,3,4,5,6,7... minutes before the current candle.

Since in the current candle this indicator "changes" its value, tick by tick, I think that should be possible to write out such an indicator, but I can not figure out how to do it.

答:
Found a way to write it in a very simple way:

```<code>double M1  (int shift) {double val = iCustom(NULL,PERIOD_M1, "my_indicator",100,2.0,30.0,0,shift); return(val);}
double M15 (int shift) {double val = iCustom(NULL,PERIOD_M15,"my_indicator",100,2.0,30.0,0,shift); return(val);}

int s1_15;
double B_M1_M15(int i) {

                          if (i>=0  && i<15 ) s1_15=0;
                     else if (i>=15 && i<30 ) s1_15=1;
                     else if (i>=30 && i<45 ) s1_15=2;
                     else if (i>=45 && i<60 ) s1_15=3;
                     else if (i>=60 && i<75 ) s1_15=4;

                     return NormalizeDouble(MathAbs(M1(i) - M15(s1_15)),Digits);

                     }
</code>```

and so on for every others couples of timeframe.

Title: MQL4 multi-timeframe indicator

Body:
Found a way to write it in a very simple way:

double M1  (int shift) {double val = iCustom(NULL,PERIOD_M1, "my_indicator",100,2.0,30.0,0,shift); return(val);}
double M15 (int shift) {double val = iCustom(NULL,PERIOD_M15,"my_indicator",100,2.0,30.0,0,shift); return(val);}

int s1_15;
double B_M1_M15(int i) {

                          if (i>=0  && i<15 ) s1_15=0;
                     else if (i>=15 && i<30 ) s1_15=1;
                     else if (i>=30 && i<45 ) s1_15=2;
                     else if (i>=45 && i<60 ) s1_15=3;
                     else if (i>=60 && i<75 ) s1_15=4;

                     return NormalizeDouble(MathAbs(M1(i) - M15(s1_15)),Digits);

                     }

and so on for every others couples of timeframe.


答:
You need to use a loop so you have

```<code>while(true){
    int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
        break;
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
    ...
}
</code>```

Since you say you are new, I'll do a little explanation:
A While loop repeats what is in it's code block (i.e within the { }) for as long as a certain condition is true. In the case of my answer I did while(true) meaning it will keep repeating until something causes it to stop. In this case I used a break which forces the loop to end/stop.

Title: Make an algorithm start again?

Body:
You need to use a loop so you have

while(true){
    int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
        break;
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
    ...
}

Since you say you are new, I'll do a little explanation:
A While loop repeats what is in it's code block (i.e within the { }) for as long as a certain condition is true. In the case of my answer I did while(true) meaning it will keep repeating until something causes it to stop. In this case I used a break which forces the loop to end/stop.


问:
How do we cross reference to multiple items in Xtext?
I have a grammar which looks like below:

```<code>Module: MOD mid=ModId ;

Stmt: CALL nam=ModName ';';

ModName: (idn1=[ModId|ID] | ('"' idn2=[ModId|ID] '"') | (idn3=ID idn4=ID));
</code>```

Basically, I have a statement where module name is mentioned. So when I try to call the module later, it should prompt me the module names defined (with or without quotes) and also allow me to enter a new variable name (which is not a module name) also.

How do I achieve this? I am able to achieve either referencing to the module name or defining a name, not both.

Example program:

```<code>Module add

Module subtract

Module divide

call add;    //referencing module name

call "subtract";  // referencing module name in quotes

call operation;   // without reference
</code>```

Regards,

Anitha

答:
there are multiple issues with that.

first for referencing with string have a look at https://christiandietrich.wordpress.com/2015/03/19/xtext-and-strings-as-cross-references/

For having an optional reference you have to change the grammar to have either a ID only or a Reference only. In the IDOnly case you could do something like

```<code>ModNameManipulator returns ModName: ref=[XXXX]
</code>```

And then use IDerivedStateComputer and SyntheticLinkingSupport to create/populate the reference.

Or you adapt linking for no the throw errors.
Both of the solutions are not trivial and might need deeper Xtext knowledge

Body:
I have a grammar which looks like below:

Module: MOD mid=ModId ;

Stmt: CALL nam=ModName ';';

ModName: (idn1=[ModId|ID] | ('"' idn2=[ModId|ID] '"') | (idn3=ID idn4=ID));

Basically, I have a statement where module name is mentioned. So when I try to call the module later, it should prompt me the module names defined (with or without quotes) and also allow me to enter a new variable name (which is not a module name) also.

How do I achieve this? I am able to achieve either referencing to the module name or defining a name, not both.

Example program:

Module add

Module subtract

Module divide

call add;    //referencing module name

call "subtract";  // referencing module name in quotes

call operation;   // without reference

Regards,

Anitha

Body:
there are multiple issues with that.

first for referencing with string have a look at https://christiandietrich.wordpress.com/2015/03/19/xtext-and-strings-as-cross-references/

For having an optional reference you have to change the grammar to have either a ID only or a Reference only. In the IDOnly case you could do something like

ModNameManipulator returns ModName: ref=[XXXX]

And then use IDerivedStateComputer and SyntheticLinkingSupport to create/populate the reference.

Or you adapt linking for no the throw errors.
Both of the solutions are not trivial and might need deeper Xtext knowledge