问:
Secure Gateway cannot be bound to Bluemix app
When trying to binding any Bluemix apps to a pre-configured Secure Gateway service, the Secure Gateway is not in the list of services which can be bound to apps. Is there a different way to bind a nodejs app to a Secure Gateway instance?</p>

答:
Applications can no longer be bound to the Secure Gateway service.  Binding was possible in previous versions but provided no additional functionality to the application.

To have your application use the connectivity provided by Secure Gateway, your application simply needs to call the cloud host:port provided by your destination.


来源: stackexchange

问:
Http.request in node.js
This is my code in node js:

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

var options = {
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){
    console.log("Hello!");
}).end();

process.on('uncaughtException', function(err){
    console.log(err);
});
</code>```

When I compile it, the compiler shows me the following error:

enter image description here

edit: with the express works, but if I wanted to make it work without express how could I do?

答:
Test this:

```<code>const app = require('express')();
app.get('/', (req, res) => {
  res.json({ ok: true });
});
app.listen(8124);

var http = require('http');

var options = {
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){
    console.log("Hello!");
}).end();

process.on('uncaughtException', function(err){
    console.log(err);
});
</code>```

as you can see, it prints Hello! - when something is listening on port 8124. Your problem is on the server side, not on the client side. Specifically, the server that you are trying to connect to is not listening on port 8124 on localhost - at least not on this host.

ContentLicense: CC BY-SA 3.0

Title: Http.request in node.js

Body:
This is my code in node js:

var http = require('http');

var options = {
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){
    console.log("Hello!");
}).end();

process.on('uncaughtException', function(err){
    console.log(err);
});

When I compile it, the compiler shows me the following error:

enter image description here

edit: with the express works, but if I wanted to make it work without express how could I do?

Body:
Test this:

const app = require('express')();
app.get('/', (req, res) => {
  res.json({ ok: true });
});
app.listen(8124);

var http = require('http');

var options = {
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){
    console.log("Hello!");
}).end();

process.on('uncaughtException', function(err){
    console.log(err);
});

as you can see, it prints Hello! - when something is listening on port 8124. Your problem is on the server side, not on the client side. Specifically, the server that you are trying to connect to is not listening on port 8124 on localhost - at least not on this host.


问:
Find Duplicated Key in a complicated React component
I have a react component, which generate many keys for a time, I am not sure which one is not unique. The error is as below. Any easy way to help debugging? thanks!

react.js:19500 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of MyGrid. See https ://fb.me/ react-warning-keys for more information.

答:
This is a warning that you have NOT assigned a key, rather than it isn't actually unique, the next line of the message should tell you exactly what is the offending element - see an example below in div (created by CardsComponent)

warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `CardsComponent`. See fb.me/react-warning-keys for more information.
    in div (created by CardsComponent)

If you want to debug further the test is done in ReactElementValidator.validateExplicitKey which simply does a check for if the element key being non null, no checking of uniqueness amongst sibling keys...

```<code>function validateExplicitKey(element, parentType) {
  if (!element._store || element._store.validated || element.key != null) {
    return;
  }
  // if it gets here it has failed and you will be warned
</code>```

The interesting part here being element.key != null as the others pass as virtue of already having been validated

Body:
This is a warning that you have NOT assigned a key, rather than it isn't actually unique, the next line of the message should tell you exactly what is the offending element - see an example below in div (created by CardsComponent)

warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `CardsComponent`. See fb.me/react-warning-keys for more information.
    in div (created by CardsComponent)

If you want to debug further the test is done in ReactElementValidator.validateExplicitKey which simply does a check for if the element key being non null, no checking of uniqueness amongst sibling keys...

function validateExplicitKey(element, parentType) {
  if (!element._store || element._store.validated || element.key != null) {
    return;
  }
  // if it gets here it has failed and you will be warned

The interesting part here being element.key != null as the others pass as virtue of already having been validated


问:
compiling qt project give undefined reference to operator delete(void*, unsigned int)
I am trying to cross compile and create a deb file from a qt project with the command dpkg-buildpackage. I am using the yocto qt sdk :"poky-atmel-glibc-x86_64-atmel-qt5-demo-image-cortexa5hf-vfp-toolchain-2.1.1.sh"
I have installed it and runned the environment-setup-cortexa5hf-vfp-poky-linux-gnueabi file.
I haved updated the qtchooser to be as :

```<code>/opt/poky-atmel/2.1.1/sysroots/x86_64-pokysdk-linux/usr/bin/qt5
/opt/poky-atmel/2.1.1/sysroots/x86_64-pokysdk-linux/usr/lib
</code>```

I have set the qmake file in /usr/lib/x86_64-linux-

Im getting the folowing error:

```<code>/usr/lib/../lib/libQt5Widgets.so: undefined reference to operator delete(void*, unsigned int)@CXXABI_1.3.9'
/usr/lib/../lib/libQt5Widgets.so: undefined reference to operator delete[](void*, unsigned int)@CXXABI_1.3.9'
/usr/lib/../lib/libQt5Core.so: undefined reference to __cxa_throw_bad_array_new_length@CXXABI_1.3.8'
</code>```

using ubuntu 14.04 64 cross-compiling for armhf

any help would be appreciated

edit:
I think the problem is because I am using 64 bit system or g++ old version (4.8.4)

答: I have solved the problem. the problem was using libraries compiled with newer g++ 5.3 with older g++ 4.7. so I downloaded the poky 1.6 qt sdk, and installed it, then I managed to create deb file</p>

Body:
I am trying to cross compile and create a deb file from a qt project with the command dpkg-buildpackage. I am using the yocto qt sdk :"poky-atmel-glibc-x86_64-atmel-qt5-demo-image-cortexa5hf-vfp-toolchain-2.1.1.sh"
I have installed it and runned the environment-setup-cortexa5hf-vfp-poky-linux-gnueabi file.
I haved updated the qtchooser to be as :

/opt/poky-atmel/2.1.1/sysroots/x86_64-pokysdk-linux/usr/bin/qt5
/opt/poky-atmel/2.1.1/sysroots/x86_64-pokysdk-linux/usr/lib

I have set the qmake file in /usr/lib/x86_64-linux-

Im getting the folowing error:

/usr/lib/../lib/libQt5Widgets.so: undefined reference to operator delete(void*, unsigned int)@CXXABI_1.3.9'
/usr/lib/../lib/libQt5Widgets.so: undefined reference to operator delete[](void*, unsigned int)@CXXABI_1.3.9'
/usr/lib/../lib/libQt5Core.so: undefined reference to __cxa_throw_bad_array_new_length@CXXABI_1.3.8'

using ubuntu 14.04 64 cross-compiling for armhf

any help would be appreciated

edit:
I think the problem is because I am using 64 bit system or g++ old version (4.8.4)


问:
Debug symbols for asp.net core
Im trying to find debug symbols for the released version of Microsoft.AspNetCore.Authentication.Cookies. The latest stable version available on nuget is 1.1.2. As far as im aware, ive added all the appropriate symbol servers. The load info tells me its checking here:

```<code> - C:\Program Files\dotnet\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Users\*snip*\.nuget\packages\microsoft.aspnetcore.authentication.cookies\1.1.2\lib\netstandard1.3\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\b\w\d6337ac2abf63a4b\.repositories\Security\src\Microsoft.AspNetCore.Authentication.Cookies\bin\Release\netstandard1.3\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\symbols\dll\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\dll\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - D:\VSSymbolCache\Microsoft.AspNetCore.Authentication.Cookies.pdb\948e7690e7904496862761f01360a70b1\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - D:\VSSymbolCache\MicrosoftPublicSymbols\Microsoft.AspNetCore.Authentication.Cookies.pdb\948e7690e7904496862761f01360a70b1\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - https://nuget.smbsrc.net:
 - http://srv.symbolsource.org/pdb/Public:
 - https://referencesource.microsoft.com/symbols:
 - https://msdl.microsoft.com/download/symbols:
</code>```

What am i missing? Is there anywhere i can download the PDBs manually?

答: Get the source code on GitHub and compile it: https://github.com/aspnet/Security It's working like a charm. I don't know a way to get the PBD alone.</p>

Title: Debug symbols for asp.net core

Body:
Im trying to find debug symbols for the released version of Microsoft.AspNetCore.Authentication.Cookies. The latest stable version available on nuget is 1.1.2. As far as im aware, ive added all the appropriate symbol servers. The load info tells me its checking here:

 - C:\Program Files\dotnet\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Users\*snip*\.nuget\packages\microsoft.aspnetcore.authentication.cookies\1.1.2\lib\netstandard1.3\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\b\w\d6337ac2abf63a4b\.repositories\Security\src\Microsoft.AspNetCore.Authentication.Cookies\bin\Release\netstandard1.3\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\symbols\dll\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - C:\Windows\dll\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - D:\VSSymbolCache\Microsoft.AspNetCore.Authentication.Cookies.pdb\948e7690e7904496862761f01360a70b1\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - D:\VSSymbolCache\MicrosoftPublicSymbols\Microsoft.AspNetCore.Authentication.Cookies.pdb\948e7690e7904496862761f01360a70b1\Microsoft.AspNetCore.Authentication.Cookies.pdb:
 - https://nuget.smbsrc.net:
 - http://srv.symbolsource.org/pdb/Public:
 - https://referencesource.microsoft.com/symbols:
 - https://msdl.microsoft.com/download/symbols:

What am i missing? Is there anywhere i can download the PDBs manually?


问:
How to setup StyleCop for Asp.net Core 1.1 solution?
I'm working on asp.net core project which has a lot of projects (web, console & class library) and I want to setup stylecop for that.

I tried to install "StyleCopAnalyzers" nuget and it seems working (giving stylecop violation error).

some of stylecop rules I want to ignore (e.g. SA1652) for entire solution level.

Need help to setup stylecop for complete solution with best practics.

Thanks In Advance

答:
You may suppress undesired policies via suppression file. Create this file on solution root folder and link it (Add as Link) to each your project.

Sample file content:

```<code>using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:Prefix local calls with this")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1124:Do not use regions")]
</code>```

Body:
You may suppress undesired policies via suppression file. Create this file on solution root folder and link it (Add as Link) to each your project.

Sample file content:

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:Prefix local calls with this")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1124:Do not use regions")]


问:
How to make a dict of multiple lists in python?
I want to make a list of dicts that have the following structure,

```<code>[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]
</code>```

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

```<code>with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))
</code>```

I am well aware of the ugliness of the try as well...

答:
You can use defaultdict</p>

```<code>from collections import defaultdict
s = ["Business", "Attorney", "Website text"]
data = defaultdict(list)

data[s[0]].append(business)
data[s[1]].append(classes)
data[s[2]].append(website)
</code>```

Body:
I want to make a list of dicts that have the following structure,

[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))

I am well aware of the ugliness of the try as well...

Body:
You can use defaultdict

from collections import defaultdict
s = ["Business", "Attorney", "Website text"]
data = defaultdict(list)

data[s[0]].append(business)
data[s[1]].append(classes)
data[s[2]].append(website)


问:
variable button vb.net
i declared a global variable button:

Dim button1 As New Button()

Now, i dont know how to add a click event in this button since it is a variable. Do you have any idea how do i do it?

答:
The Addhandler way is probably the way to go as mentioned. Your other option is to declare your button in the following way:

```<code>Dim withEvents button1 As New Button()

Private Sub button1_ClickHandler(ByVal sender As Object, ByVal e As EventArgs) Handles button1.click

'Handle stuff

End Sub
</code>```

This way simulates what VS does for you if you were to drag the button on the form in the designer.

The advantage to the AddHandler way is that you can remove handlers dynamically as well if you ever needed to.

OwnerDisplayName: sef

LastEditorDisplayName: lc

ContentLicense: CC BY-SA 2.5

Title: variable button vb.net

Body:
The Addhandler way is probably the way to go as mentioned. Your other option is to declare your button in the following way:

Dim withEvents button1 As New Button()

Private Sub button1_ClickHandler(ByVal sender As Object, ByVal e As EventArgs) Handles button1.click

'Handle stuff

End Sub

This way simulates what VS does for you if you were to drag the button on the form in the designer.

The advantage to the AddHandler way is that you can remove handlers dynamically as well if you ever needed to.

OwnerDisplayName: Jason Down


问:
How can I select a null value for no colour, from a kendo color picker?
I am trying to configure a colour picker for users to select from a set of colours using a palette of Hex strings from the database.  I have it all working fine except I can’t set the value to null for no colour selected.  Leaving the value property out, setting it to null, or an empty string all select the first option in the colour picker.  Does anyone know how I can set a value for no colour selected?

my view:

```<code>    @(Html.Kendo().ColorPicker()
        .Name("Colour")
        .TileSize(32)
        .Columns(16)
        .Palette(colours)
        .Deferred()
    )
</code>```

My Controller Method to get the array:

```<code>public string[] GetColours()
{
     var autoCadColours = _somerService.GetColours();
     int length = autoCadColours.Count();
     string[] colours = new string[length];
     foreach (var i in autoCadColours.Select((value, index) => new { Value = value, Index = index }))
     {
          colours[i.Index] = i.Value.HexString;
     }
     return colours;
}
</code>```

答:
To Solve this I used the Change event to set the value using Ajax.</p>

```<code>@(Html.Kendo().ColorPicker()
                            .Name("Color")
                            .Events(e => e.Change("colourChange"))
                            .Value("0")
                            .TileSize(32)
                            .Columns(16)
                            .Palette(colours)
                            .Deferred()
                    )
</code>```

Body:
I am trying to configure a colour picker for users to select from a set of colours using a palette of Hex strings from the database.  I have it all working fine except I can’t set the value to null for no colour selected.  Leaving the value property out, setting it to null, or an empty string all select the first option in the colour picker.  Does anyone know how I can set a value for no colour selected?

my view:

    @(Html.Kendo().ColorPicker()
        .Name("Colour")
        .TileSize(32)
        .Columns(16)
        .Palette(colours)
        .Deferred()
    )

My Controller Method to get the array:

public string[] GetColours()
{
     var autoCadColours = _somerService.GetColours();
     int length = autoCadColours.Count();
     string[] colours = new string[length];
     foreach (var i in autoCadColours.Select((value, index) => new { Value = value, Index = index }))
     {
          colours[i.Index] = i.Value.HexString;
     }
     return colours;
}

Body:
To Solve this I used the Change event to set the value using Ajax.

@(Html.Kendo().ColorPicker()
                            .Name("Color")
                            .Events(e => e.Change("colourChange"))
                            .Value("0")
                            .TileSize(32)
                            .Columns(16)
                            .Palette(colours)
                            .Deferred()
                    )


问:
Div show/hide is not working inside partial view
I have a partial view, based on the content of view bag I want to show the div and fade out after some second,for this I am using jQuery. everything is working fine if I put the code in main view. Unfortunately I want to have this pop up inside Partial view. code given below

        @if (!string.IsNullOrEmpty(ViewBag.Message))
        {

@ViewBag.Message

        }

        @if (!string.IsNullOrEmpty(ViewBag.Message))
        {

        }

```

here even the JavaScript alert is working fine. But the Show and Fade out is not working.

答: Move you script outside (and after) the div you are attempting to operate on. Open chrome developer tools and post any remaining error you find in the console.</p>

Body:
I have a partial view, based on the content of view bag I want to show the div and fade out after some second,for this I am using jQuery. everything is working fine if I put the code in main view. Unfortunately I want to have this pop up inside Partial view. code given below

        @if (!string.IsNullOrEmpty(ViewBag.Message))
        {

@ViewBag.Message

        }

        @if (!string.IsNullOrEmpty(ViewBag.Message))
        {

        }

here even the JavaScript alert is working fine. But the Show and Fade out is not working.


问:
How do I get the day month and year from a Windows cmd.exe script?
How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.</p>

答:
This variant works for all localizations:</p>

```<code>@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%
</code>```

Body:
This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%


问:
Absolute jump with a PC relative data source (AArch64)
How may one perform an absolute jump (64-bit dword) on AArch64 with as few instructions as possible, whilst using a data source relative to the program counter?

At first glance, one may assume a LDR followed by a  BR is possible, i.e:

```<code>LDR x9, [PC, #0x8];
BR x9
.dword 0xBADC0FFEE0DDF00D
</code>```

But since PC is no longer a general purpose register on AArch64, it is not.

So how can this be done with as few instructions as possible?

答:
You can rely on the compiler generated literal pools as usual:

```<code>LDR x9, =0xBADC0FFEE0DDF00D
BR x9
</code>```

This is readable and will essentially generate the same code.

If you want to have precise control, you can use the LDR literal version, the manual says:

Load Register (literal) calculates an address from the PC value and an immediate offset, loads a word from memory, and writes it to a register.

As such you can do:

```<code>LDR x9, foo
BR x9
foo: .dword 0xBADC0FFEE0DDF00D
</code>```

Or less readable but without a label:

```<code>LDR x9, .+8
BR x9
.dword 0xBADC0FFEE0DDF00D
</code>```

Body:
How may one perform an absolute jump (64-bit dword) on AArch64 with as few instructions as possible, whilst using a data source relative to the program counter?

At first glance, one may assume a LDR followed by a  BR is possible, i.e:

LDR x9, [PC, #0x8];
BR x9
.dword 0xBADC0FFEE0DDF00D

But since PC is no longer a general purpose register on AArch64, it is not.

So how can this be done with as few instructions as possible?

Body:
You can rely on the compiler generated literal pools as usual:

LDR x9, =0xBADC0FFEE0DDF00D
BR x9

This is readable and will essentially generate the same code.

If you want to have precise control, you can use the LDR literal version, the manual says:

Load Register (literal) calculates an address from the PC value and an immediate offset, loads a word from memory, and writes it to a register.

As such you can do:

LDR x9, foo
BR x9
foo: .dword 0xBADC0FFEE0DDF00D

Or less readable but without a label:

LDR x9, .+8
BR x9
.dword 0xBADC0FFEE0DDF00D


问:
App from Xcode works great, but App Store version freezes on load
Has anyone ever heard of this? I'm baffled, and so is Google.

When debugging on iPhone 4 with iOS 4.1, my app shows the splash screen, then shows an animation while it loads and gets the GPS location, and finally goes to the main menu. When I download it from the App Store, it never stops loading. More strange than that, if I hide the forever-loading-app and then restore it, the load animation freezes and the app no longer responds!

I've been trying to make all kinds of guesses about what's going wrong, but nothing is working. How can I get useful information about this failure?

EDIT: App has also been tested on iPhone 3 with iOS 4.0 and iOS 4.2.1, and iPhone 4 with iOS 4.0.2 and 4.2.1.

EDIT EDIT: The problem does not occur if I do not download it from the app store. This makes it extremely difficult to debug, but hopefully narrows it down for somebody out there with more experience than I have.

答:
First, it sounds like you've tested your app on one device.
Apps should be tested on few devices at least, so you can debug and understand inside flows on several cases.

But if you can't get another device, try elimination. means - try to put unnecessary code under remark, and load only the necessary code.
step-by-step you can understand the bug.

It sounds to me like server issue (are you sending any request to a server?), or maybe the gps can't stop searching..?


问:
Apply pseudo-element CSS selector inside shadow DOM
I have a Polymer 2 paper-input that holds a date:

```<code><paper-input type="date"></paper-input>
</code>```

When this renders the actual <input> is inside the shadow DOM for the control.

I want to use the pseudo-element selector ::-webkit-inner-spin-button to style the spinner buttons in Chrome.

In Polymer 1/Shadow DOM v0 I could use /deep/ or ::shadow to build a style rule for these, but those have been deprecated in Polymer 2/Shadow DOM v1.

How do I apply a style to a pseudo-element inside the <paper-input>'s shadow DOM?

答:
You can use the --paper-input-container-input-webkit-spinner custom css mixin have a look at this.

For instance, hide the spinner:

```<code>paper-input[type=date] {
    --paper-input-container-input-webkit-spinner: {
        -webkit-appearance: none;
    }
}
</code>```

Body:
I have a Polymer 2 paper-input that holds a date:

<paper-input type="date"></paper-input>

When this renders the actual <input> is inside the shadow DOM for the control.

I want to use the pseudo-element selector ::-webkit-inner-spin-button to style the spinner buttons in Chrome.

In Polymer 1/Shadow DOM v0 I could use /deep/ or ::shadow to build a style rule for these, but those have been deprecated in Polymer 2/Shadow DOM v1.

How do I apply a style to a pseudo-element inside the <paper-input>'s shadow DOM?

Body:
You can use the --paper-input-container-input-webkit-spinner custom css mixin have a look at this.

For instance, hide the spinner:

paper-input[type=date] {
    --paper-input-container-input-webkit-spinner: {
        -webkit-appearance: none;
    }
}


问:
Recursively calling an object method that returns an iterator of itself
I'm currently writing a project that requires third party code that uses a method that returns an iterator of itself, an example of how this would look in my code:

```<code>def generate():
    for x in obj.children():
        for y in x.children():
            for z in y.children():
                yield z.thing
</code>```

Currently this simply clutters my code, and becomes hard to read after 3 levels. Ideally I'd get it to do something like this:

```<code>x = recursive(obj, method="children", repeat=3).thing
</code>```

Is there a built in way to do this in Python?

答:
Starting from python3.3, you can use the yield from syntax to yield an entire generator expression.

So, you can modify your function a bit, to take a couple of parameters:

```<code>def generate(obj, n):
    if n == 1:
        for x in obj.children():
            yield x.thing
    else:
        for x in obj.children():
            yield from generate(x, n - 1)
</code>```

The yield from expression will yield the entire generator expression of the recursive call.

Call your function like this:

```<code>x = generate(obj, 3)
</code>```

Note that this returns you a generator of x.things.

Based on your particular requirement, here's a more generic version using getattr that works with arbitrary attributes.

```<code>def generate(obj, iterable_attr, attr_to_yield, n):
    if n == 1:
        for x in getattr(obj, iterable_attr):
            yield getattr(x, attr_to_yield)
    else:
        for x in getattr(obj, iterable_attr):
            yield from generate(x, iterable_attr, attr_to_yield, n - 1)
</code>```

And now, call your function as:

```<code>x = generate(obj, 'children', 'thing', 3)
</code>```

Body:
I'm currently writing a project that requires third party code that uses a method that returns an iterator of itself, an example of how this would look in my code:

def generate():
    for x in obj.children():
        for y in x.children():
            for z in y.children():
                yield z.thing

Currently this simply clutters my code, and becomes hard to read after 3 levels. Ideally I'd get it to do something like this:

x = recursive(obj, method="children", repeat=3).thing

Is there a built in way to do this in Python?

Body:
Starting from python3.3, you can use the yield from syntax to yield an entire generator expression.

So, you can modify your function a bit, to take a couple of parameters:

def generate(obj, n):
    if n == 1:
        for x in obj.children():
            yield x.thing
    else:
        for x in obj.children():
            yield from generate(x, n - 1)

The yield from expression will yield the entire generator expression of the recursive call.

Call your function like this:

x = generate(obj, 3)

Note that this returns you a generator of x.things.

Based on your particular requirement, here's a more generic version using getattr that works with arbitrary attributes.

def generate(obj, iterable_attr, attr_to_yield, n):
    if n == 1:
        for x in getattr(obj, iterable_attr):
            yield getattr(x, attr_to_yield)
    else:
        for x in getattr(obj, iterable_attr):
            yield from generate(x, iterable_attr, attr_to_yield, n - 1)

And now, call your function as:

x = generate(obj, 'children', 'thing', 3)


问:
calculate the area of shape created by custom lines on canvas in android
I am making an app for architecture planning. In that, i want to find the area covered by closed shape drawn by line on canvas by drawline() method. This is the Code.

```<code>public class CanvasBackground extends View {

public static boolean addPath;
public static flg flag;
public static boolean addLine = false;
public static boolean join = false;
public static boolean isDrawing;
public static int myLine;
public static ArrayList<Line> lines = new ArrayList<>();
public static ArrayList<Path> paths = new ArrayList<>();
public Paint paint;
public Context context;
public Canvas canvas;
public ScaleGestureDetector scaleGestureDetector;
public Bitmap addBtnBitmap;
public int passed_size;
float scalfactor = 1f;
Button addBtn;
public CanvasBackground(Context context) {
    super(context);
    this.context = context;
    paint = new Paint();
    scaleGestureDetector = new ScaleGestureDetector(context, new CanvasScale());
    DrawingActivity drawingActivity = new DrawingActivity();
    passed_size = drawingActivity.getCategory();

    setDrawingCacheEnabled(true);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    canvas.save();
    //add Button Select

    paint.setColor(Color.WHITE);
    canvas.drawPaint(paint);

    DrawingZoomingCanvas(canvas);
    DrawingLine(canvas);

    canvas.restore();
    Log.e("OnDraw >>>", "CALLING");
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (addLine) {
                if (lines.size() != 0) {
                    Line current = lines.get(lines.size() - 1);

                    lines.add(new Line(current.stopX, current.stopY, myLine));

                } else {

                    lines.add(new Line(event.getX(), event.getY(), myLine));
                }

                isDrawing = true;
                addLine = false;
            }

            if (addPath) {
                Path path = new Path();
                path.moveTo(event.getX(), event.getY());
                paths.add(path);
                isDrawing = true;
                addPath = false;
            }
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            if (isDrawing) {
                if (lines.size() > 0 && flg.ADDLINE == flag) {
                    Line current = lines.get(lines.size() - 1);
                    current.stopX = event.getX();
                    current.stopY = event.getY();
                } else if (paths.size() > 0 && flg.ADDPATH == flag) {
                    Path path = paths.get(paths.size() - 1);
                    path.lineTo(event.getX(), event.getY());
                }
                invalidate();
            }
            break;
        case MotionEvent.ACTION_UP:
            if (isDrawing) {
                if (lines.size() > 0 && flg.ADDLINE == flag) {
                    Line current = lines.get(lines.size() - 1);
                    current.stopX = event.getX();
                    current.stopY = event.getY();
                }
                invalidate();
            }
            break;
        default:
            break;
    }
    //scaleGestureDetector.onTouchEvent(event);

    Log.e("OnTouch >>>", "CALLING " + isDrawing + " >> " + event.getX() + " >> " + event.getY() + ">>" + event.getAction());
    return true;
}

//drawing a line
private void DrawingLine(Canvas canvas) {
    paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(2);
    paint.setAntiAlias(true);
    for (Line l : lines) {
        canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
        canvas.drawText(String.valueOf(l.getSize()), l.startX, l.startY, paint);
    }
    for (Path l : paths) {
        canvas.drawPath(l, paint);
    }
    if (flg.JOIN == flag) {
        Line first = lines.get(0);
        Line last = lines.get(lines.size() - 1);
        Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
        canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
        canvas.drawText(String.valueOf(myLine), last.stopX, last.stopY, paint);
        invalidate();
        isDrawing = true;

    }
    setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("CALL CLICK", "vv" + v.getId());
        }
    });

}

//drawing Matrix Canvas With Zoom
private void DrawingZoomingCanvas(Canvas canvas) {
    //drawing Matarix
    canvas.translate(scalfactor * 10, scalfactor * 10);
    canvas.scale(scalfactor, scalfactor);
    paint.setColor(Color.rgb(220, 220, 220));
    for (int i = 0; i <= canvas.getHeight() * scalfactor; i += 10) {
        canvas.drawLine(i, 0, i, canvas.getHeight(), paint);
        canvas.drawLine(0, i, canvas.getWidth(), i, paint);
    }
}

public void join_line() {

    Line first = lines.get(0);
    Line last = lines.get(lines.size() - 1);
    Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
    canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
    invalidate();
    isDrawing = true;

}

public enum flg {ADDLINE, ADDPATH, JOIN}

private class CanvasScale extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        scalfactor *= scaleGestureDetector.getScaleFactor();
        scalfactor = Math.max(0.1f, Math.min(scalfactor, 10.0f));
        invalidate();
        return true;
    }
}

}
</code>```

This is the Activity.

```<code>public class DrawingActivity extends AppCompatActivity {
public int line_size;
CanvasBackground canvasBackground;
LinearLayout linearLayoutV, linearLayoutH;
Button addBtn, confirmBtn, clearBtn, addPath, joinbtn;
Context context = DrawingActivity.this;
LinearLayout.LayoutParams wrap_content_layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    canvasBackground = new CanvasBackground(context);

    //Main Layout Liner
    linearLayoutV = new LinearLayout(context);
    linearLayoutV.setOrientation(LinearLayout.VERTICAL);

    linearLayoutH = new LinearLayout(context);
    linearLayoutH.setOrientation(LinearLayout.HORIZONTAL);
    linearLayoutH.setWeightSum(4);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.weight = 1;

    //add Line Button
    addBtn = new Button(context);
    addBtn.setLayoutParams(layoutParams);
    addBtn.setText("Line+");
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.addLine = true;
            CanvasBackground.flag = CanvasBackground.flg.ADDLINE;

            //**************** SET LENGTH
            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("Set the length of line");
            builder1.setCancelable(true);
            final EditText input = new EditText(DrawingActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            builder1.setView(input);

            builder1.setPositiveButton(
                    "Done",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            line_size = Integer.parseInt(input.getText().toString());
                            Log.e("size", String.valueOf(getCategory()));
                            CanvasBackground.myLine = line_size;
                            dialog.cancel();
                        }
                    });

            builder1.setNegativeButton(
                    "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert11 = builder1.create();
            alert11.show();
        }
    });
    linearLayoutH.addView(addBtn);
    // join last button
    joinbtn = new Button(context);
    joinbtn.setLayoutParams(layoutParams);
    joinbtn.setText("Join");
    joinbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.flag = CanvasBackground.flg.JOIN;

            v.invalidate();
            //**************** SET LENGTH
            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("Set the length of line");
            builder1.setCancelable(true);
            final EditText input = new EditText(DrawingActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            builder1.setView(input);

            builder1.setPositiveButton(
                    "Done",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            line_size = Integer.parseInt(input.getText().toString());
                            Log.e("size", String.valueOf(getCategory()));
                            CanvasBackground.myLine = line_size;
                            dialog.cancel();
                        }
                    });

            builder1.setNegativeButton(
                    "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert11 = builder1.create();
            alert11.show();

        }
    });
    linearLayoutH.addView(joinbtn);

    //add Line Button
    addPath = new Button(context);
    addPath.setLayoutParams(layoutParams);
    addPath.setText("Path+");
    addPath.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.addPath = true;
            CanvasBackground.flag = CanvasBackground.flg.ADDPATH;
        }
    });
    linearLayoutH.addView(addPath);

    //add Confirm Button
    confirmBtn = new Button(context);
    confirmBtn.setLayoutParams(layoutParams);
    confirmBtn.setText("Ok");
    confirmBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.isDrawing = false;
        }
    });
    linearLayoutH.addView(confirmBtn);
    linearLayoutV.addView(linearLayoutH);

    linearLayoutV.addView(canvasBackground);

    setContentView(linearLayoutV);
}

public int getCategory() {
    return line_size;
}

}
</code>```

This is the whole code. Please help me.

答:
Ya you can first validate the shape formed by the user on touch is close by observing the start and end coordinates. Once if the shape is closed. It forms a regular polygon.

For a regular polygon.

Find the perimeter of the polygon (permiter = summation of all side length)

Then find the apothem of the polygon ( apothem = length of sides / 2tan(180/no of sides))

Them find the area using the perimeter and the apothem.(Area = (area * perimeter)/2)

Also refer this link for more info on steps in detail.
http://www.wikihow.com/Find-the-Area-of-Regular-Polygons

Body:
I am making an app for architecture planning. In that, i want to find the area covered by closed shape drawn by line on canvas by drawline() method. This is the Code.

public class CanvasBackground extends View {

public static boolean addPath;
public static flg flag;
public static boolean addLine = false;
public static boolean join = false;
public static boolean isDrawing;
public static int myLine;
public static ArrayList<Line> lines = new ArrayList<>();
public static ArrayList<Path> paths = new ArrayList<>();
public Paint paint;
public Context context;
public Canvas canvas;
public ScaleGestureDetector scaleGestureDetector;
public Bitmap addBtnBitmap;
public int passed_size;
float scalfactor = 1f;
Button addBtn;
public CanvasBackground(Context context) {
    super(context);
    this.context = context;
    paint = new Paint();
    scaleGestureDetector = new ScaleGestureDetector(context, new CanvasScale());
    DrawingActivity drawingActivity = new DrawingActivity();
    passed_size = drawingActivity.getCategory();

    setDrawingCacheEnabled(true);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    canvas.save();
    //add Button Select

    paint.setColor(Color.WHITE);
    canvas.drawPaint(paint);

    DrawingZoomingCanvas(canvas);
    DrawingLine(canvas);

    canvas.restore();
    Log.e("OnDraw >>>", "CALLING");
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (addLine) {
                if (lines.size() != 0) {
                    Line current = lines.get(lines.size() - 1);

                    lines.add(new Line(current.stopX, current.stopY, myLine));

                } else {

                    lines.add(new Line(event.getX(), event.getY(), myLine));
                }

                isDrawing = true;
                addLine = false;
            }

            if (addPath) {
                Path path = new Path();
                path.moveTo(event.getX(), event.getY());
                paths.add(path);
                isDrawing = true;
                addPath = false;
            }
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            if (isDrawing) {
                if (lines.size() > 0 && flg.ADDLINE == flag) {
                    Line current = lines.get(lines.size() - 1);
                    current.stopX = event.getX();
                    current.stopY = event.getY();
                } else if (paths.size() > 0 && flg.ADDPATH == flag) {
                    Path path = paths.get(paths.size() - 1);
                    path.lineTo(event.getX(), event.getY());
                }
                invalidate();
            }
            break;
        case MotionEvent.ACTION_UP:
            if (isDrawing) {
                if (lines.size() > 0 && flg.ADDLINE == flag) {
                    Line current = lines.get(lines.size() - 1);
                    current.stopX = event.getX();
                    current.stopY = event.getY();
                }
                invalidate();
            }
            break;
        default:
            break;
    }
    //scaleGestureDetector.onTouchEvent(event);

    Log.e("OnTouch >>>", "CALLING " + isDrawing + " >> " + event.getX() + " >> " + event.getY() + ">>" + event.getAction());
    return true;
}

//drawing a line
private void DrawingLine(Canvas canvas) {
    paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(2);
    paint.setAntiAlias(true);
    for (Line l : lines) {
        canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
        canvas.drawText(String.valueOf(l.getSize()), l.startX, l.startY, paint);
    }
    for (Path l : paths) {
        canvas.drawPath(l, paint);
    }
    if (flg.JOIN == flag) {
        Line first = lines.get(0);
        Line last = lines.get(lines.size() - 1);
        Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
        canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
        canvas.drawText(String.valueOf(myLine), last.stopX, last.stopY, paint);
        invalidate();
        isDrawing = true;

    }
    setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("CALL CLICK", "vv" + v.getId());
        }
    });

}

//drawing Matrix Canvas With Zoom
private void DrawingZoomingCanvas(Canvas canvas) {
    //drawing Matarix
    canvas.translate(scalfactor * 10, scalfactor * 10);
    canvas.scale(scalfactor, scalfactor);
    paint.setColor(Color.rgb(220, 220, 220));
    for (int i = 0; i <= canvas.getHeight() * scalfactor; i += 10) {
        canvas.drawLine(i, 0, i, canvas.getHeight(), paint);
        canvas.drawLine(0, i, canvas.getWidth(), i, paint);
    }
}

public void join_line() {

    Line first = lines.get(0);
    Line last = lines.get(lines.size() - 1);
    Log.e("FL", "First:-" + first.startX + first.startY + "Last" + last.stopX + last.stopY);
    canvas.drawLine(first.startX, first.startY, last.stopX, last.stopY, paint);
    invalidate();
    isDrawing = true;

}

public enum flg {ADDLINE, ADDPATH, JOIN}

private class CanvasScale extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        scalfactor *= scaleGestureDetector.getScaleFactor();
        scalfactor = Math.max(0.1f, Math.min(scalfactor, 10.0f));
        invalidate();
        return true;
    }
}

}

This is the Activity.

public class DrawingActivity extends AppCompatActivity {
public int line_size;
CanvasBackground canvasBackground;
LinearLayout linearLayoutV, linearLayoutH;
Button addBtn, confirmBtn, clearBtn, addPath, joinbtn;
Context context = DrawingActivity.this;
LinearLayout.LayoutParams wrap_content_layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    canvasBackground = new CanvasBackground(context);

    //Main Layout Liner
    linearLayoutV = new LinearLayout(context);
    linearLayoutV.setOrientation(LinearLayout.VERTICAL);

    linearLayoutH = new LinearLayout(context);
    linearLayoutH.setOrientation(LinearLayout.HORIZONTAL);
    linearLayoutH.setWeightSum(4);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.weight = 1;

    //add Line Button
    addBtn = new Button(context);
    addBtn.setLayoutParams(layoutParams);
    addBtn.setText("Line+");
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.addLine = true;
            CanvasBackground.flag = CanvasBackground.flg.ADDLINE;

            //**************** SET LENGTH
            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("Set the length of line");
            builder1.setCancelable(true);
            final EditText input = new EditText(DrawingActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            builder1.setView(input);

            builder1.setPositiveButton(
                    "Done",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            line_size = Integer.parseInt(input.getText().toString());
                            Log.e("size", String.valueOf(getCategory()));
                            CanvasBackground.myLine = line_size;
                            dialog.cancel();
                        }
                    });

            builder1.setNegativeButton(
                    "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert11 = builder1.create();
            alert11.show();
        }
    });
    linearLayoutH.addView(addBtn);
    // join last button
    joinbtn = new Button(context);
    joinbtn.setLayoutParams(layoutParams);
    joinbtn.setText("Join");
    joinbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.flag = CanvasBackground.flg.JOIN;

            v.invalidate();
            //**************** SET LENGTH
            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("Set the length of line");
            builder1.setCancelable(true);
            final EditText input = new EditText(DrawingActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            builder1.setView(input);

            builder1.setPositiveButton(
                    "Done",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            line_size = Integer.parseInt(input.getText().toString());
                            Log.e("size", String.valueOf(getCategory()));
                            CanvasBackground.myLine = line_size;
                            dialog.cancel();
                        }
                    });

            builder1.setNegativeButton(
                    "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert11 = builder1.create();
            alert11.show();

        }
    });
    linearLayoutH.addView(joinbtn);

    //add Line Button
    addPath = new Button(context);
    addPath.setLayoutParams(layoutParams);
    addPath.setText("Path+");
    addPath.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.addPath = true;
            CanvasBackground.flag = CanvasBackground.flg.ADDPATH;
        }
    });
    linearLayoutH.addView(addPath);

    //add Confirm Button
    confirmBtn = new Button(context);
    confirmBtn.setLayoutParams(layoutParams);
    confirmBtn.setText("Ok");
    confirmBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CanvasBackground.isDrawing = false;
        }
    });
    linearLayoutH.addView(confirmBtn);
    linearLayoutV.addView(linearLayoutH);

    linearLayoutV.addView(canvasBackground);

    setContentView(linearLayoutV);
}

public int getCategory() {
    return line_size;
}

}

This is the whole code. Please help me.


问:
How to find the max value in a Swift object array?
Let say I got an array with Usr objects. And the Usr object have the attribute age. Except from reading the Usrobject one by one, and compare the age value one by one, is there any shortcuts to do so? Thx.

答:
Swift 3:

```<code>let users = [Usr(15), Usr(25), Usr(20)]
let max = users.map { $0.age }.max()
</code>```

// max = 25

Body:
Swift 3:

let users = [Usr(15), Usr(25), Usr(20)]
let max = users.map { $0.age }.max()

// max = 25


问:
Assigning objects to an array C#
Struggling to assign objects to an array in C#.

The output of the code is unexpected because I get the nameOfProject.ClassName(?) x3 rather than name and life points of 3 monsters i added using my for loop.
Debug suggests monsters aren't being assigned.  Is there a logical flaw that people like me should be looking out for?

```<code>class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Monsters[] monster = new Monsters[3];

        for (int i = 0; i < monster.Length; i++)
        {
            Console.WriteLine("Please enter a name");
            string name = Console.ReadLine();
            Console.WriteLine("Please enter life points");
            int points = Convert.ToInt32(Console.ReadLine());
            monster[i] = new Monsters(name,points);
            Console.Clear();
        }
        foreach (var element in monster)
        {
            Console.WriteLine(element);
        }
        Console.ReadKey();

    }
</code>```

答:
How should WriteLine know that you want to print those two properties and not e.g. the type-name (which it does per default) or any other wierd string? You have to tell your program how to do this. This is done by overriding ToString

```<code>class Monster
{
    public override string ToString() {
        return this.name + " " + this.lifePoints;
    }
}
</code>```

Furthermore your variables need to be fields:

```<code>class Monster
{
    private readonly string name;
    private readonly int lifePoints;

    Monster(string name, int points)
    {
        this.name = name;
        this.lifePoints = points;
    }
}
</code>```

Title: Assigning objects to an array C#

Body:
Struggling to assign objects to an array in C#.

The output of the code is unexpected because I get the nameOfProject.ClassName(?) x3 rather than name and life points of 3 monsters i added using my for loop.
Debug suggests monsters aren't being assigned.  Is there a logical flaw that people like me should be looking out for?

class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Monsters[] monster = new Monsters[3];

        for (int i = 0; i < monster.Length; i++)
        {
            Console.WriteLine("Please enter a name");
            string name = Console.ReadLine();
            Console.WriteLine("Please enter life points");
            int points = Convert.ToInt32(Console.ReadLine());
            monster[i] = new Monsters(name,points);
            Console.Clear();
        }
        foreach (var element in monster)
        {
            Console.WriteLine(element);
        }
        Console.ReadKey();

    }

Body:
How should WriteLine know that you want to print those two properties and not e.g. the type-name (which it does per default) or any other wierd string? You have to tell your program how to do this. This is done by overriding ToString

class Monster
{
    public override string ToString() {
        return this.name + " " + this.lifePoints;
    }
}

Furthermore your variables need to be fields:

class Monster
{
    private readonly string name;
    private readonly int lifePoints;

    Monster(string name, int points)
    {
        this.name = name;
        this.lifePoints = points;
    }
}


问:
How to change already added string column to a Reference in Rails
I've already created a model in Rails to collect some user information

I created the columns as :string initially but I've since changed the way this data is looked up and entered by using separate populated models.

Now instead of entering into these fields as string - i want these columns to be "references" instead.

Is there an easy way to change from the string to reference without having to create a new model entirely?

*do not need to save the existing data

答:
Is there any data in the strings you would like to save?

Or is it just because it has the same name?

You don't have to create a new model.

You could create a simple migration

```<code>remove_column :table, :your_column_name, :string
add_column :table, :your_column_name, :integer, references: :your_parent_model
</code>```

Body:
Is there any data in the strings you would like to save?

Or is it just because it has the same name?

You don't have to create a new model.

You could create a simple migration

remove_column :table, :your_column_name, :string
add_column :table, :your_column_name, :integer, references: :your_parent_model


问:
Linker command failed with exit code 1 error in Xcode project
I was working on my project and suddenly after editing the code and compiling gave this error:

ld: warning: directory not found for option '-

  L/Users/mani/Documents/Classes/Twitter+OAuth/Libraries & Headers' ld:
  duplicate symbol _OBJC_CLASS_$_playSiew in
  /Users/mani/Library/Developer/Xcode/DerivedData/learn-aktrtiwswclovoatyweyquoxmypa/Build/Intermediates/learn.build/Debug-iphonesimulator/learn.build/Objects-normal/i386/playSiew.o
  and
  /Users/mani/Library/Developer/Xcode/DerivedData/learn-aktrtiwswclovoatyweyquoxmypa/Build/Intermediates/learn.build/Debug-iphonesimulator/learn.build/Objects-normal/i386/Thumb.o
  for architecture i386 clang: error: linker command failed with exit
  code 1 (use -v to see invocation)

I never touched the project settings, just edited the code.

What's more strange is that I took out last revised code from svn but still I got the the same error.

答: Go to general and linked frameworks and libraries in xcode and remove all the files there.


问:
Overflow hidden is not working with absolute element in safari

.services {
     margin: 0 0 40px 0;
    }
    .services ul {
     list-style: none;
    }
    .services ul > li {
     float: left;
     width: 168px;
     text-align: center;
    }
    .services ul > li + li {
     margin-left: 24px;
    }
    .services ul > li .thumb {
     border: 2px solid #b9b9b9;
     border-radius: 50%;
     -moz-border-radius: 50%
     -webkit-border-radius: 50%;
     overflow: hidden;
     position: relative;
     margin: 0 0 14px 0;
    }
    .services ul > li .thumb img {
     display: block;
     border-radius: 50%;
     -moz-border-radius: 50%;
     -webkit-border-radius: 50%;
     max-width: 100%;
     height: auto;
    }
    .services ul > li .thumb span {
     position: absolute;
     background: #95bd0d;
     font-size: 14px;
     line-height: 20px;
     width: 100%;
     padding: 8px 10px;
     bottom: 0px;
     left: 0px;
     color: #fff;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="services">
    <div class="container">
        <ul>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-3.jpg" height="168" width="168" alt="" > <span>FAKTEN</span> </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                lesen Sie mehr
            </li>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-4.jpg" height="168" width="168" alt="" > </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                lesen Sie mehr
            </li>
        </ul>
    </div>
</div></code>```

Thumb div overflow:hidden is not working with absolute element in safari.
As well as it won't work with thumb image also, i have also rounded the image tag with border-radius.

Word FAKTEN should be hidden as left image. Below is the code. Please suggest.

答:
This is a documented bug

The best workaround is to add to the .thumb rule the following

```<code>-webkit-transform: translateZ(0);
-webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%);
</code>```

.services {
     margin: 0 0 40px 0;
    }
    .services ul {
     list-style: none;
    }
    .services ul > li {
     float: left;
     width: 168px;
     text-align: center;
    }
    .services ul > li + li {
     margin-left: 24px;
    }
    .services ul > li .thumb {
     border: 2px solid #b9b9b9;
     border-radius: 50%;
     -moz-border-radius: 50%
     -webkit-border-radius: 50%;
     overflow: hidden;
     position: relative;
     margin: 0 0 14px 0;
      /*fix safari border-radius and overflow hidden problem*/
      -webkit-transform: translateZ(0);
      -webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%);
    }
    .services ul > li .thumb img {
     display: block;
     border-radius: 50%;
     -moz-border-radius: 50%;
     -webkit-border-radius: 50%;
     max-width: 100%;
     height: auto;
    }
    .services ul > li .thumb span {
     position: absolute;
     background: #95bd0d;
     font-size: 14px;
     line-height: 20px;
     width: 100%;
     padding: 8px 10px;
     bottom: 0px;
     left: 0px;
     color: #fff;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="services">
    <div class="container">
        <ul>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-3.jpg" height="168" width="168" alt="" > <span>FAKTEN</span> </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                lesen Sie mehr
            </li>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-4.jpg" height="168" width="168" alt="" > </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                lesen Sie mehr
            </li>
        </ul>
    </div>
</div></code>```

Body:
.services {
     margin: 0 0 40px 0;
    }
    .services ul {
     list-style: none;
    }
    .services ul > li {
     float: left;
     width: 168px;
     text-align: center;
    }
    .services ul > li + li {
     margin-left: 24px;
    }
    .services ul > li .thumb {
     border: 2px solid #b9b9b9;
     border-radius: 50%;
     -moz-border-radius: 50%
     -webkit-border-radius: 50%;
     overflow: hidden;
     position: relative;
     margin: 0 0 14px 0;
    }
    .services ul > li .thumb img {
     display: block;
     border-radius: 50%;
     -moz-border-radius: 50%;
     -webkit-border-radius: 50%;
     max-width: 100%;
     height: auto;
    }
    .services ul > li .thumb span {
     position: absolute;
     background: #95bd0d;
     font-size: 14px;
     line-height: 20px;
     width: 100%;
     padding: 8px 10px;
     bottom: 0px;
     left: 0px;
     color: #fff;
    }

  FAKTEN

Spirovent Superior - Vakuumentgaser

                lesen Sie mehr

Spirovent Superior - Vakuumentgaser

                lesen Sie mehr

Thumb div overflow:hidden is not working with absolute element in safari.
As well as it won't work with thumb image also, i have also rounded the image tag with border-radius.

Word FAKTEN should be hidden as left image. Below is the code. Please suggest.

Body:
This is a documented bug

The best workaround is to add to the .thumb rule the following

-webkit-transform: translateZ(0);
-webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%);

.services {
     margin: 0 0 40px 0;
    }
    .services ul {
     list-style: none;
    }
    .services ul > li {
     float: left;
     width: 168px;
     text-align: center;
    }
    .services ul > li + li {
     margin-left: 24px;
    }
    .services ul > li .thumb {
     border: 2px solid #b9b9b9;
     border-radius: 50%;
     -moz-border-radius: 50%
     -webkit-border-radius: 50%;
     overflow: hidden;
     position: relative;
     margin: 0 0 14px 0;
      /*fix safari border-radius and overflow hidden problem*/
      -webkit-transform: translateZ(0);
      -webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%);
    }
    .services ul > li .thumb img {
     display: block;
     border-radius: 50%;
     -moz-border-radius: 50%;
     -webkit-border-radius: 50%;
     max-width: 100%;
     height: auto;
    }
    .services ul > li .thumb span {
     position: absolute;
     background: #95bd0d;
     font-size: 14px;
     line-height: 20px;
     width: 100%;
     padding: 8px 10px;
     bottom: 0px;
     left: 0px;
     color: #fff;
    }

<div class="services">
    <div class="container">
        <ul>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-3.jpg" height="168" width="168" alt="" > <span>FAKTEN</span> </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                <a href="#">lesen Sie mehr</a>
            </li>
            <li>
                <div class="thumb"> <img src="http://182.73.133.220/ateet/image-4.jpg" height="168" width="168" alt="" > </div>
                <h4>Spirovent Superior - Vakuumentgaser</h4>
                <a href="#">lesen Sie mehr</a>
            </li>
        </ul>
    </div>
</div>


答:
Please find answer as below

```<code><div id="error_Msg_div" class=" " data-label="canccelled" data-left="0" data-top="0" data-width="0" data-height="0" style="display:block;position: absolute !important; left: 600px !important ;">

    @if (!string.IsNullOrEmpty(ViewBag.Message))
    {
    <!-- Unnamed (Rectangle) -->
        <div id="error_text" class="ax_default label">

            <!-- Unnamed () -->
            <div id="error_msg" class="text">
                <p><span>@ViewBag.Message</span></p>
            </div>
        </div>
    }
</div>
    <script type="text/javascript">
        $(document).ready(function () {
            if ('@ViewBag.Message' == '') {

                alert("error");

                $("#error_Msg_div").show();
                $("#error_Msg_div").fadeOut(5000);
            }
        });

    </script>
</code>```

you need call javascript function when view load

Title: Div show/hide is not working inside partial view

Body:
Please find answer as below

<div id="error_Msg_div" class=" " data-label="canccelled" data-left="0" data-top="0" data-width="0" data-height="0" style="display:block;position: absolute !important; left: 600px !important ;">

    @if (!string.IsNullOrEmpty(ViewBag.Message))
    {
    <!-- Unnamed (Rectangle) -->
        <div id="error_text" class="ax_default label">

            <!-- Unnamed () -->
            <div id="error_msg" class="text">
                <p><span>@ViewBag.Message</span></p>
            </div>
        </div>
    }
</div>
    <script type="text/javascript">
        $(document).ready(function () {
            if ('@ViewBag.Message' == '') {

                alert("error");

                $("#error_Msg_div").show();
                $("#error_Msg_div").fadeOut(5000);
            }
        });

    </script>

you need call javascript function when view load


问:
Removing characters in a java string
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

```<code>String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");
</code>```

This won't work!

答:
```<code>SQL = SQL.replace("AND Gender = 'Female'","");
</code>```

strings are immutable in java

Title: Removing characters in a java string

Body:
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");

This won't work!

Body:
SQL = SQL.replace("AND Gender = 'Female'","");

strings are immutable in java


问:
VS 2015 syntax highlighting red lines in vue files
I have a .Vue file but VS 2015 keeps complaining about syntax: Here is how it shows red lines everywhere

I am on VS 2015 Update 3 Enterprise edition

How can I fix this issue? Is there any plugins required to be installed for this purpose?

答:
Visual Studio does not have specific tooling (currently) for VueJS single file components (.vue files), I encountered the same Intellisense issues.

What I ended up doing is using Visual Studio Code to develop .vue files, specifically this plugin for VSCode https://marketplace.visualstudio.com/items?itemName=octref.vetur (Vetur)


答:
You can add a temporary string column to save the string column first:

```<code>rails g migration add_temporary_string_column_to_model temporary_string_column:string
</code>```

And run rails console:

```<code>SomeModel.all.each do |some_model|
    some_mode.temporary_string_column = some_mode.string_column
    some_mode.save
end
</code>```

And now you can change your original string column's type to references which is an int(4) column in MySQL, migration like this:

```<code>class ChangeFormatInSomeTable < ActiveRecord::Migration
    def change
        change_column :some_table, :string_column, :references
    end
end
</code>```

Finally, you can run rails console again to convert the string data to integer like this:

```<code>SomeModel.all.each do |some_model|
    some_mode.string_column = some_mode.temporary_string_column.to_i
    some_mode.save
end
</code>```

And at last, remove the temporary string column:

```<code>rails g migration remove_temporary_string_column_from_model temporary_string_column
</code>```

Title: How to change already added string column to a Reference in Rails

Body:
I've already created a model in Rails to collect some user information

I created the columns as :string initially but I've since changed the way this data is looked up and entered by using separate populated models.

Now instead of entering into these fields as string - i want these columns to be "references" instead.

Is there an easy way to change from the string to reference without having to create a new model entirely?

*do not need to save the existing data

Body:
You can add a temporary string column to save the string column first:

rails g migration add_temporary_string_column_to_model temporary_string_column:string

And run rails console:

SomeModel.all.each do |some_model|
    some_mode.temporary_string_column = some_mode.string_column
    some_mode.save
end

And now you can change your original string column's type to references which is an int(4) column in MySQL, migration like this:

class ChangeFormatInSomeTable < ActiveRecord::Migration
    def change
        change_column :some_table, :string_column, :references
    end
end

Finally, you can run rails console again to convert the string data to integer like this:

SomeModel.all.each do |some_model|
    some_mode.string_column = some_mode.temporary_string_column.to_i
    some_mode.save
end

And at last, remove the temporary string column:

rails g migration remove_temporary_string_column_from_model temporary_string_column


问:
Using Pandas, adding a timedelta to a new row in master dataframe?
Goal: For a cell in a specific column that has a date within the next 9 months, add a new column to Master with either "Yes", for the date is coming up, or "No", for the date is not coming up.

I'm new to Pandas, so any help would be great. I have one dataframe I'm calling "Master", as the dataframe I am adding everything to to then export to an Excel spreadsheet. With the code below, I created a new dataframe for the date and am trying to say "If the cell is in date, put "Yes" in a new column".

I suspect my issue is that I'm trying to treat Pandas like arrays, but what it's actually doing is creating entirely new indexing when I make a new dataframe and doesn't hold onto how it used to be mapped to master. Is my understanding correct? And if so, how can I accomplish my goal in a more elegant way?

```<code>def mess_with_time(Master):
    now = datetime.datetime.now()
    nine_months_in_the_future = str(datetime.datetime.today() + relativedelta(months=+8))
    just_future_month=int(nine_months_in_the_future[5:7])
    just_future_year=int(nine_months_in_the_future[0:4])

    dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))]
Master['Contract End date coming up?'] = np.where(dates, 'Yes', 'No') #this breaks with
the error 'Length of values does not match length of index'

def Create_Master(file):
    df = pd.ExcelFile('{}.xlsx'.format(file))

    Master = df.parse('Main').fillna(0)
</code>```

答:
I try rewrite your solution to pandas:

First is possible use DateOffset and then create boolean mask by between:

```<code>now = pd.datetime.now()
months9 = now + pd.offsets.DateOffset(months=8)
print (months9)
2018-03-06 15:07:52.850238

rng = pd.date_range('2017-04-03', periods=10, freq='3M')
Master = pd.DataFrame({'Contract End Date': rng, 'a': range(10)})

dates_mask = Master['Contract End Date'].between(now, months9)
Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No')
print (Master)
  Contract End Date  a Contract End date coming up?
0        2017-04-30  0                           No
1        2017-07-31  1                          Yes
2        2017-10-31  2                          Yes
3        2018-01-31  3                          Yes
4        2018-04-30  4                           No
5        2018-07-31  5                           No
6        2018-10-31  6                           No
7        2019-01-31  7                           No
8        2019-04-30  8                           No
9        2019-07-31  9                           No
</code>```

It seems you need change boolean indexing Master[boolean_condition] to boolean condition only:

```<code>dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))]
</code>```

to:

```<code>dates_mask = (Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))

Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No')
</code>```

Body:
Goal: For a cell in a specific column that has a date within the next 9 months, add a new column to Master with either "Yes", for the date is coming up, or "No", for the date is not coming up.

I'm new to Pandas, so any help would be great. I have one dataframe I'm calling "Master", as the dataframe I am adding everything to to then export to an Excel spreadsheet. With the code below, I created a new dataframe for the date and am trying to say "If the cell is in date, put "Yes" in a new column".

I suspect my issue is that I'm trying to treat Pandas like arrays, but what it's actually doing is creating entirely new indexing when I make a new dataframe and doesn't hold onto how it used to be mapped to master. Is my understanding correct? And if so, how can I accomplish my goal in a more elegant way?

def mess_with_time(Master):
    now = datetime.datetime.now()
    nine_months_in_the_future = str(datetime.datetime.today() + relativedelta(months=+8))
    just_future_month=int(nine_months_in_the_future[5:7])
    just_future_year=int(nine_months_in_the_future[0:4])

    dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))]
Master['Contract End date coming up?'] = np.where(dates, 'Yes', 'No') #this breaks with
the error 'Length of values does not match length of index'

def Create_Master(file):
    df = pd.ExcelFile('{}.xlsx'.format(file))

    Master = df.parse('Main').fillna(0)

Body:
I try rewrite your solution to pandas:

First is possible use DateOffset and then create boolean mask by between:

now = pd.datetime.now()
months9 = now + pd.offsets.DateOffset(months=8)
print (months9)
2018-03-06 15:07:52.850238

rng = pd.date_range('2017-04-03', periods=10, freq='3M')
Master = pd.DataFrame({'Contract End Date': rng, 'a': range(10)})

dates_mask = Master['Contract End Date'].between(now, months9)
Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No')
print (Master)
  Contract End Date  a Contract End date coming up?
0        2017-04-30  0                           No
1        2017-07-31  1                          Yes
2        2017-10-31  2                          Yes
3        2018-01-31  3                          Yes
4        2018-04-30  4                           No
5        2018-07-31  5                           No
6        2018-10-31  6                           No
7        2019-01-31  7                           No
8        2019-04-30  8                           No
9        2019-07-31  9                           No

It seems you need change boolean indexing Master[boolean_condition] to boolean condition only:

dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))]

to:

dates_mask = (Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))

Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No')


问:
Generic Methods, how to call a parent method without specifying a type
I have this parent class

```<code>public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}
</code>```

and this child

```<code>public class Child : Parent
{
    public string Name { get; set; }
}
</code>```

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

答:
I would do something like this:</p>

```<code>public abstract class Parent<T> where T : class, new()
{
    public T Find(string id)
    {
        return new T();
    }
}
public class Child  : Parent<Child>
{
    public void Test()
    {
        var child = base.Find ("");
    }
}
</code>```

Body:
I have this parent class

public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}

and this child

public class Child : Parent
{
    public string Name { get; set; }
}

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

Body:
I would do something like this:

public abstract class Parent<T> where T : class, new()
{
    public T Find(string id)
    {
        return new T();
    }
}
public class Child  : Parent<Child>
{
    public void Test()
    {
        var child = base.Find ("");
    }
}


问:
How to implement WatchKit sliding button?
Is there a way to implement a sliding button on the watch, similar to the power button linked below?

power off screen from watch

答: I ended up using SpriteKit to add an SKSpriteNode to the scene with my image. It doesn't have the smoothness of the power off slider, but that could probably be tweaked. Using an SKAction to move the icon instead of setting the coordinates directly helped but it's not perfect.</p>


问:
Azure functions with complex c# code
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

```<code>public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}
</code>```

Many thanks

答: First of all, Azure Functions are not designed for complex processing. Instead you can consider worker roles for this or a microservice if your solution is already on Service Fabric. </p>

Title: Azure functions with complex c# code

Body:
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}

Many thanks


问:
How do I configure Service Fabric Cluster on Windows Server 2016 to be able to run Linux Containers?
In one of our project, we have a technical constraint to use Service Fabric as platform to run applications built with Service Fabric SDK. The Service Fabric Cluster will use Windows Server 2016 for the Operating System.

However, the software also are depending on a 3rd party product that run as Docker Container running on Linux Container OS.

The Product Owner would like to have the Container to be deployed on the same Service Fabric cluster for easier management and monitoring.

It is known that Windows Server 2016 are able to run Linux Docker Container using Hyper-V Isolation Technology. How do I configure Service Fabric running on Windows Server 2016 to be able to utilize that technology and run Linux Containers?

Thank you.

答:
Support for running Linux containers directly on WinSrv2016 is on the way. It's not here yet. Therefore you can't run them on SF yet either.

You can't have a hybrid cluster either. So at this time your options is: run two SF clusters.


问:
How to delete duplicates in line of text?
I can't find anything on how to do this. I read the documentation on uniq but it only deals with duplicate lines, I need to remove duplicate strings in the same line.

Let's say I have

```<code>TodayToday is an an array
</code>```

I need it to ouput

```<code>Today is an array
</code>```

Thanks!

答:
uniq works on entire lines, the proper tool for processing the line contents is sed (you could use also awk or Perl for other ways of doing these one-liners).

Since you say in your comments that you already use sed and you tagged your question "linux", here is how you would obtain the repetition removal, with identical sequences of upper or lowercase, based on your provided test case using GNU sed:

```<code>$ echo 'TodayToday is an an array' | sed -e 's/\b\([a-zA-Z ]\+\)\1/\1/g'
Today is an array
</code>```

if you want to treat "TodayTODay" as a repetition, then you could to this (add i case-insentitive flag):

```<code>$ echo 'TodayTODay is an an array' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Today is an array
</code>```

if you want to treat groups of words separated by spaces such as "Today is an arrayToday is an array" as a repetition, you can do this (add space in the matching set):

```<code>$ echo 'Today is an arrayTODay is an array' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Today is an array
</code>```

doing this, does not, nevertheless allow the regexp to decide not to alter a word such as "nana"

```<code>$ echo 'Her name was Nana' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Her name was Na
</code>```

but we can safely say we eat "banana", given the \b word boundary introduced before the regexp to address the case drawn to our attention by @purplepsycho:

```<code>$ echo 'We eat banana' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
We eat banana
</code>```

Body:
I can't find anything on how to do this. I read the documentation on uniq but it only deals with duplicate lines, I need to remove duplicate strings in the same line.

Let's say I have

TodayToday is an an array

I need it to ouput

Today is an array

Thanks!

Body:
uniq works on entire lines, the proper tool for processing the line contents is sed (you could use also awk or Perl for other ways of doing these one-liners).

Since you say in your comments that you already use sed and you tagged your question "linux", here is how you would obtain the repetition removal, with identical sequences of upper or lowercase, based on your provided test case using GNU sed:

$ echo 'TodayToday is an an array' | sed -e 's/\b\([a-zA-Z ]\+\)\1/\1/g'
Today is an array

if you want to treat "TodayTODay" as a repetition, then you could to this (add i case-insentitive flag):

$ echo 'TodayTODay is an an array' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Today is an array

if you want to treat groups of words separated by spaces such as "Today is an arrayToday is an array" as a repetition, you can do this (add space in the matching set):

$ echo 'Today is an arrayTODay is an array' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Today is an array

doing this, does not, nevertheless allow the regexp to decide not to alter a word such as "nana"

$ echo 'Her name was Nana' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
Her name was Na

but we can safely say we eat "banana", given the \b word boundary introduced before the regexp to address the case drawn to our attention by @purplepsycho:

$ echo 'We eat banana' | sed -e 's/\b\([a-z ]\+\)\1/\1/gi'
We eat banana


问:
KNN in Tensorflow - Using Graph to predict unseen data
Based on the following example of KNN in Tensorflow - what would be the best way to use the graph to "predict" the label of some unseen data?</p>

```<code>from __future__ import print_function

import numpy as np
import tensorflow as tf

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing

# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])

# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)

accuracy = 0.

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # loop over test data
    for i in range(len(Xte)):
        # Get nearest neighbor
        nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
        # Get nearest neighbor class label and compare it to its true label
        print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
            "True Class:", np.argmax(Yte[i]))
        # Calculate accuracy
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print("Done!")
    print("Accuracy:", accuracy)
</code>```

答:
You can do this by appending these lines to the end, inside the "with tf.Session() as sess:".</p>

```<code># Generate new (unseen) data
X, y = mnist.test.next_batch(1)

# Compute index of new data
nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: X[0, :]})

# Print the computed prediction
print("Test", i,
      "Prediction:", np.argmax(Ytr[nn_index]),
      "True Class:", np.argmax(y[0]))
</code>```

Body:
Based on the following example of KNN in Tensorflow - what would be the best way to use the graph to "predict" the label of some unseen data?

from __future__ import print_function

import numpy as np
import tensorflow as tf

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing

# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])

# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)

accuracy = 0.

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # loop over test data
    for i in range(len(Xte)):
        # Get nearest neighbor
        nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
        # Get nearest neighbor class label and compare it to its true label
        print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
            "True Class:", np.argmax(Yte[i]))
        # Calculate accuracy
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print("Done!")
    print("Accuracy:", accuracy)

Body:
You can do this by appending these lines to the end, inside the "with tf.Session() as sess:".

# Generate new (unseen) data
X, y = mnist.test.next_batch(1)

# Compute index of new data
nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: X[0, :]})

# Print the computed prediction
print("Test", i,
      "Prediction:", np.argmax(Ytr[nn_index]),
      "True Class:", np.argmax(y[0]))


问:
FallBackValue in IMultiValueConverter is UnsetValue
I am trying to use a single IMultiValueConverter for more than one controls in XAML.

I am using a simple string Literal to tell what value the IMultiValueConverter is supposed to return.

But I am getting DependencyProperty.UnsetValue in values[2],ie value of parametter named Command when it comes to convert function of ModifierCategoryEnableDisable.

Similar arrangment is working on similar controls on this XAML form within other IMultiValueConverters but not here.
 Please guide what am i missing?

NOTE:

CurrentRec is the currently selected object from the ViewModel

DM_CategoryData is a Class and Current_Selected_Category is a List<DM_CategoryData> in the ViewModel's current object,ie CurrenRec.

XAML:

```<code><GroupBox Width="226" Height="117"  Margin="0" Canvas.Top="252" Header="Modifiers" Canvas.Left="55" >
         <GroupBox.IsEnabled>
             <MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}">
                     <Binding Path="SearchFound" />
                     <Binding Path="CurrentRec.Current_Selected_Category"/>
                     <Binding Path="Command" FallbackValue="1" />
              </MultiBinding>
        </GroupBox.IsEnabled>
 </GroupBox>
</code>```

C#:

```<code>public class ModifierCategoryEnableDisable : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string Command = values[2].ToString();
        bool Retval1 = false;
        string Retval2 = "";
        switch(Command)
        {
            case "1":
                bool SearchFound = (bool)values[0];
                DM_CategoryData CurrentSelectedItemCategory = (DM_CategoryData)(values[1]);
                Retval1 = SearchFound && (CurrentSelectedItemCategory == null ? true : CurrentSelectedItemCategory.IsModifier.Equals("1") ? false : true);
                break;
            case "2":
                Retval2 = "0";
                break;
        }

        if(Command.Equals("1"))
        {
            return Retval1;
        }
        else
        {
            return Retval2;
        }
   }
}
</code>```

答:
In order to provide additional static data to a multibinding converter, use a ConverterParameter:

```<code><MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}" ConverterParameter="1">
    <Binding Path="SearchFound" />
    <Binding Path="CurrentRec.Current_Selected_Category"/>
</MultiBinding>
</code>```

And check the parameter in the Convert method:

```<code>public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    string Command = parameter as string;

    // ...
}
</code>```

Body:
I am trying to use a single IMultiValueConverter for more than one controls in XAML.

I am using a simple string Literal to tell what value the IMultiValueConverter is supposed to return.

But I am getting DependencyProperty.UnsetValue in values[2],ie value of parametter named Command when it comes to convert function of ModifierCategoryEnableDisable.

Similar arrangment is working on similar controls on this XAML form within other IMultiValueConverters but not here.
 Please guide what am i missing?

NOTE:

CurrentRec is the currently selected object from the ViewModel

DM_CategoryData is a Class and Current_Selected_Category is a List<DM_CategoryData> in the ViewModel's current object,ie CurrenRec.

XAML:

<GroupBox Width="226" Height="117"  Margin="0" Canvas.Top="252" Header="Modifiers" Canvas.Left="55" >
         <GroupBox.IsEnabled>
             <MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}">
                     <Binding Path="SearchFound" />
                     <Binding Path="CurrentRec.Current_Selected_Category"/>
                     <Binding Path="Command" FallbackValue="1" />
              </MultiBinding>
        </GroupBox.IsEnabled>
 </GroupBox>

C#:

public class ModifierCategoryEnableDisable : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string Command = values[2].ToString();
        bool Retval1 = false;
        string Retval2 = "";
        switch(Command)
        {
            case "1":
                bool SearchFound = (bool)values[0];
                DM_CategoryData CurrentSelectedItemCategory = (DM_CategoryData)(values[1]);
                Retval1 = SearchFound && (CurrentSelectedItemCategory == null ? true : CurrentSelectedItemCategory.IsModifier.Equals("1") ? false : true);
                break;
            case "2":
                Retval2 = "0";
                break;
        }

        if(Command.Equals("1"))
        {
            return Retval1;
        }
        else
        {
            return Retval2;
        }
   }
}

Body:
In order to provide additional static data to a multibinding converter, use a ConverterParameter:

<MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}" ConverterParameter="1">
    <Binding Path="SearchFound" />
    <Binding Path="CurrentRec.Current_Selected_Category"/>
</MultiBinding>

And check the parameter in the Convert method:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    string Command = parameter as string;

    // ...
}


问:
Posting different versions of your Android App in React-Native
I have a React-Native app in the Google Market. What I need to do is to create a separate version for our internal use (it will have some different functionality). Pretty much I need to have two apps in the market so I can have both of them on my phone. The closest answer that I found was this. I forked my app and from my understanding, I need to change all the package names to a new one. However, the problem is in my app I use Google Services like FCM, I use some extra packagaes like sharing and importing posts. And those are also tied to a package name.

Are there any tutorials to doing this, or do I need to create a blank project and start building it up from scratch, adding packages?

Sorry, if I am unclear about the explanations. I thought this was a common practice, but did not find much information about it.

答: You just need to change your apps name by cloning your repo and made some changes explained here.</p>