问:
Invoke a SOAP method with namespace prefixes
My C# web service client sends following soap message to Java-based web service:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getData>
<request>
<requestParameters xmlns="http://b...">
<equals>
...
</equals>
</requestParameters>
</request>
</getData>
</soap:Body>
</soap:Envelope>
</code>```

and Java-based web service returns error:

```<code>500 Internal Server Error
...
Cannot find dispatch method for {}getData
...
</code>```

Client written in Java, which works, sends the following message:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ns2:getData xmlns:ns2="http://a...">
<ns2:request>
<ns3:requestParameters xmlns:ns3="http://b...">
<ns3:equals>
...
</ns3:equals>
</ns3:requestParameters>
</ns2:request>
</ns2:getData>
</soap:Body>
</soap:Envelope>
</code>```

Is there an easy way in C# to send SOAP messages the same way Java client sends: with namespace prefixes?

Following is C# code that sends message:

```<code>// class MyService is auto-generated using wsdl.exe tool
MyService service = new MyService();

RequestMessage request = new RequestMessage();
...

ResponseMessage response = service.getData(request);
...
</code>```

UPDATE:

Here is RequestMessage class:

```<code>/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://uri.etsi.org/02657/v1.5.1#/RetainedData")]
public partial class RequestMessage
{

    private byte[] requestPriorityField;

    private RequestConstraints requestParametersField;

    private string deliveryPointHIBField;

    private string maxHitsField;

    private NationalRequestParameters nationalRequestParametersField;

    private System.Xml.XmlElement anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="hexBinary", Order=0)]
    public byte[] requestPriority
    {
        get
        {
            return this.requestPriorityField;
        }
        set
        {
            this.requestPriorityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=1)]
    public RequestConstraints requestParameters
    {
        get
        {
            return this.requestParametersField;
        }
        set
        {
            this.requestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=2)]
    public string deliveryPointHIB
    {
        get
        {
            return this.deliveryPointHIBField;
        }
        set
        {
            this.deliveryPointHIBField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=3)]
    public string maxHits
    {
        get
        {
            return this.maxHitsField;
        }
        set
        {
            this.maxHitsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=4)]
    public NationalRequestParameters nationalRequestParameters
    {
        get
        {
            return this.nationalRequestParametersField;
        }
        set
        {
            this.nationalRequestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute(Order=5)]
    public System.Xml.XmlElement Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}
</code>```

UPDATE #2:

The reason why Java-based web service didn't like my C# client produced SOAP message is not omission of namespace prefixes, but only because of omission of xmlns in getData element, so if my message looks like this:

```<code>...
<getData xmlns="http://a...">
...
</getData>
...
</code>```

it works!

I managed to put xmlns inside getData by manually editing SoapRpcMethodAttribute in wsdl.exe-produced source code. Here is excerpt:

```<code>/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(
    Name="AxxxPortTypeBinding", Namespace="http://a...")]
public partial class AxxxService
    : System.Web.Services.Protocols.SoapHttpClientProtocol {

    ...

    /// <remarks/>
    [System.Web.Services.Protocols.SoapRpcMethodAttribute(
        "http://a.../getData",
        RequestNamespace = "http://a...",
        ResponseNamespace = "http://a...",
        Use = System.Web.Services.Description.SoapBindingUse.Literal)]
    [return: System.Xml.Serialization.XmlElementAttribute("response")]
    public ResponseMessage getData(RequestMessage request) {
        object[] results = this.Invoke("getData", new object[] {
                    request});
        return ((ResponseMessage)(results[0]));
    }

    ...
}
</code>```

Before my change, SoapRpcMethodAttribute had following constructor:

```<code>[System.Web.Services.Protocols.SoapRpcMethodAttribute(
    "", RequestNamespace = "", ResponseNamespace = "",
    Use = System.Web.Services.Description.SoapBindingUse.Literal)]
</code>```

Now, the question is: what to put in WSDL file so that SoapRpcMethodAttribute have those strings in constructor (filled by the wsdl.exe tool) in the first place?

答:
I've seen this problem before where the WSDL.exe tool did not properly pull in the namespace when generating the service code. Check the request object definition in your generated code. My guess is that there is no XmlRootAttribute attribute defined on the class definition for the request object.

Adding the attribute [XmlRootAttribute(Namespace "http://a...")] to the class definition for the request object should fix this issue.

As a side note, I recommend adding this additional attribute in a separate code file using a partial class definition. Defining the attribute in a separate file will allow you to regenerate the web service code using WSDL.exe whenever neccessary without overwriting the fix to set the root element's namespace properly.

Body:
My C# web service client sends following soap message to Java-based web service:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getData>
<request>
<requestParameters xmlns="http://b...">
<equals>
...
</equals>
</requestParameters>
</request>
</getData>
</soap:Body>
</soap:Envelope>

and Java-based web service returns error:

500 Internal Server Error
...
Cannot find dispatch method for {}getData
...

Client written in Java, which works, sends the following message:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ns2:getData xmlns:ns2="http://a...">
<ns2:request>
<ns3:requestParameters xmlns:ns3="http://b...">
<ns3:equals>
...
</ns3:equals>
</ns3:requestParameters>
</ns2:request>
</ns2:getData>
</soap:Body>
</soap:Envelope>

Is there an easy way in C# to send SOAP messages the same way Java client sends: with namespace prefixes?

Following is C# code that sends message:

// class MyService is auto-generated using wsdl.exe tool
MyService service = new MyService();

RequestMessage request = new RequestMessage();
...

ResponseMessage response = service.getData(request);
...

UPDATE:

Here is RequestMessage class:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://uri.etsi.org/02657/v1.5.1#/RetainedData")]
public partial class RequestMessage
{

    private byte[] requestPriorityField;

    private RequestConstraints requestParametersField;

    private string deliveryPointHIBField;

    private string maxHitsField;

    private NationalRequestParameters nationalRequestParametersField;

    private System.Xml.XmlElement anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="hexBinary", Order=0)]
    public byte[] requestPriority
    {
        get
        {
            return this.requestPriorityField;
        }
        set
        {
            this.requestPriorityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=1)]
    public RequestConstraints requestParameters
    {
        get
        {
            return this.requestParametersField;
        }
        set
        {
            this.requestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=2)]
    public string deliveryPointHIB
    {
        get
        {
            return this.deliveryPointHIBField;
        }
        set
        {
            this.deliveryPointHIBField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=3)]
    public string maxHits
    {
        get
        {
            return this.maxHitsField;
        }
        set
        {
            this.maxHitsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=4)]
    public NationalRequestParameters nationalRequestParameters
    {
        get
        {
            return this.nationalRequestParametersField;
        }
        set
        {
            this.nationalRequestParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute(Order=5)]
    public System.Xml.XmlElement Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}

UPDATE #2:

The reason why Java-based web service didn't like my C# client produced SOAP message is not omission of namespace prefixes, but only because of omission of xmlns in getData element, so if my message looks like this:

...
<getData xmlns="http://a...">
...
</getData>
...

it works!

I managed to put xmlns inside getData by manually editing SoapRpcMethodAttribute in wsdl.exe-produced source code. Here is excerpt:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(
    Name="AxxxPortTypeBinding", Namespace="http://a...")]
public partial class AxxxService
    : System.Web.Services.Protocols.SoapHttpClientProtocol {

    ...

    /// <remarks/>
    [System.Web.Services.Protocols.SoapRpcMethodAttribute(
        "http://a.../getData",
        RequestNamespace = "http://a...",
        ResponseNamespace = "http://a...",
        Use = System.Web.Services.Description.SoapBindingUse.Literal)]
    [return: System.Xml.Serialization.XmlElementAttribute("response")]
    public ResponseMessage getData(RequestMessage request) {
        object[] results = this.Invoke("getData", new object[] {
                    request});
        return ((ResponseMessage)(results[0]));
    }

    ...
}

Before my change, SoapRpcMethodAttribute had following constructor:

[System.Web.Services.Protocols.SoapRpcMethodAttribute(
    "", RequestNamespace = "", ResponseNamespace = "",
    Use = System.Web.Services.Description.SoapBindingUse.Literal)]

Now, the question is: what to put in WSDL file so that SoapRpcMethodAttribute have those strings in constructor (filled by the wsdl.exe tool) in the first place?


来源: stackexchange

问:
Object is identified only if it is visible with eye on browser window - UFT
We are automating a web application using UFT/QTP. The issue is that UFT works only on those web objects which are seen in browser window part. If any object/element is at the bottom of the page and require scroll down in window to be seen. UFT is not able to work on those objects. We have written code to  page down to work on those objects. It works fine. But sometimes when page is very lengthy and we don't know at what position that object will be like in middle of the page, or far bottom of the page etc. In that case, only page down does not work. Is there any way that we can make the object visible on the basis of object properties? That means we can bring object in front of the window.</p>

答:
If your scrolling pageup or pagedown code is already working, why don't you use a loop... </p>

```<code>Set obj = Browser(..).page(..).Link(..) ' use your object

While obj.getROProperty("visible") = False
    'Scroll code
Wend
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If your scrolling pageup or pagedown code is already working, why don't you use a loop...

Set obj = Browser(..).page(..).Link(..) ' use your object

While obj.getROProperty("visible") = False
    'Scroll code
Wend


问:
Catch output of keras layer
This is my neural network :

```<code>model = Sequential()
act = 'relu'
model.add(Dense(430, input_shape=(3,)))
model.add(Activation(act))

model.add(Dense(256))
model.add(Activation(act))
model.add(Dropout(0.42))

model.add(Dense(148))
model.add(Activation(act))
model.add(Dropout(0.3))

model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=[myAccuracy])
</code>```

myAccuracy is a custom metric here
I used this command to catch the output of the final layer (Dense(1))

```<code>output = model.layers[8].output
print(output)
</code>```

It gave me this output:

```<code>Tensor("dense_4/BiasAdd:0", shape=(?, 1), dtype=float32)
0
</code>```

I want the output for every training example I have how do I do this ?

答:
```<code>predictions = model.predict(allTrainingExamples)
</code>```

Title: Catch output of keras layer

Body:
This is my neural network :

model = Sequential()
act = 'relu'
model.add(Dense(430, input_shape=(3,)))
model.add(Activation(act))

model.add(Dense(256))
model.add(Activation(act))
model.add(Dropout(0.42))

model.add(Dense(148))
model.add(Activation(act))
model.add(Dropout(0.3))

model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=[myAccuracy])

myAccuracy is a custom metric here
I used this command to catch the output of the final layer (Dense(1))

output = model.layers[8].output
print(output)

It gave me this output:

Tensor("dense_4/BiasAdd:0", shape=(?, 1), dtype=float32)
0

I want the output for every training example I have how do I do this ?


问:
SMS via gms modem asp.net
I'm using a gsm modem itengo 3800. I'm currently doing a project that interface with a website to send/receive bulk sms, schedule sms and etc.

The problem is, i don't really know which should it be coded in. Should it be coded as a  asp.net web application? or should it coded as a windows programs that interface with the web application for send/receiving sms?

Also receiving/sending multiple sms is important, so i requires queue or anything for buffer? Would be glad if sample programme is provided.

答:
Because sending messages via gsm modem can be slow, what I'd do is have the ASP.NET app post the messages to a message queue, then have a windows service read the queue and send the messages.  This allows the website to avoid any degradation issues when sending out lots of messages.

Here is a decent article that discusses using MSMQ:  http://www.15seconds.com/issue/031202.htm

The ASP.NET app would:

```<code>MessageQueue queue = new MessageQueue(QUEUE_PATH);
Message msg = new Message("5555551212|message");
queue.Send(msg);
</code>```

And the service would listen:

```<code>MessageQueue queue = new MessageQueue(QUEUE_PATH);
Message msg = queue.Receive();
</code>```

Title: SMS via gms modem asp.net

Body:
Because sending messages via gsm modem can be slow, what I'd do is have the ASP.NET app post the messages to a message queue, then have a windows service read the queue and send the messages.  This allows the website to avoid any degradation issues when sending out lots of messages.

Here is a decent article that discusses using MSMQ:  http://www.15seconds.com/issue/031202.htm

The ASP.NET app would:

MessageQueue queue = new MessageQueue(QUEUE_PATH);
Message msg = new Message("5555551212|message");
queue.Send(msg);

And the service would listen:

MessageQueue queue = new MessageQueue(QUEUE_PATH);
Message msg = queue.Receive();

ContentLicense: CC BY-SA 2.5


问:
What's the difference between importScripts and ES6 modules/import?
I currently implement a front-end along with a service worker.
As I require several code pieces for my service worker, I opted to use the importScripts function from the standard.

I really don't get why importScripts was added to this standard as modules became part of the ES6 standard about 3 years ago (although still missing in most browsers, if not using a flag).

Can someone elaborate on this?
I assume it's related to the error handling and the like...

答: After some research the bottomline is, that the specification for importScripts was older than for the ES6 modules. In the long run ES6 modules likely will be supported in Service Workers. As of now it's not supported in Chrome Canary yet, although there is ES6 module support for the front-end since version 60.</p>


问:
Eclipse not respond when try to configure GIT
Windows 10 Pro 64 Bit

SSD Kingston

i5-4690

Eclipse version: ALL

Workspace: empty

Problem: everytime i try to configure TEAM > GIT > configuration or i try to import/create local/remote git, eclipse freeze until i force to close it with task.

I have already tryed a fresh install ( juno/mars/neon/oxygen ) 32/64 bit with and without installer with no good results

```<code>!SESSION 2017-06-27 00:39:29.113 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:39:50.111
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:41:04.510 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product -data file:/C:/Users/Enrico/workspace/ -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:41:13.439
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:42:32.097 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:42:42.119
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:45:05.785 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product -data file:/C:/Users/Enrico/workspace/ -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:45:13.542
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:47:39.707 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:47:49.374
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
</code>```

MY SOLUTION:
"Delete all folders from USER_FOLDER ( .p2 .eclipse ) and PROGRAMFILES. Remember to reboot!!!! Now all works fine with eclipse oxygen and git project"

答:
The GIT plugin of Eclipse tries to detect whether to use the GIT executable of the OS, or the build-in GIT. Therefor it uses a bash command.

Before the Windows Creators Update, the bash command did not exist (unless you've installed CygWin or a similar program). With the Windows Creators Update, a new feature Windows Subsystem for Linux is added. When the bash command is first called, it asks whether to install this feature or not.

So in order to fix GIT in Eclipse, you just have to manually run bash once and install it. You may have to activate Developer Mode in Windows.

Body:
Windows 10 Pro 64 Bit

SSD Kingston

i5-4690

Eclipse version: ALL

Workspace: empty

Problem: everytime i try to configure TEAM > GIT > configuration or i try to import/create local/remote git, eclipse freeze until i force to close it with task.

I have already tryed a fresh install ( juno/mars/neon/oxygen ) 32/64 bit with and without installer with no good results

!SESSION 2017-06-27 00:39:29.113 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:39:50.111
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:41:04.510 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product -data file:/C:/Users/Enrico/workspace/ -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:41:13.439
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:42:32.097 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:42:42.119
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:45:05.785 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product -data file:/C:/Users/Enrico/workspace/ -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:45:13.542
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.
!SESSION 2017-06-27 00:47:39.707 -----------------------------------------------
eclipse.buildId=4.7.0.I20170531-2000
java.version=1.8.0_91
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=it_IT
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product

!ENTRY org.eclipse.egit.ui 2 0 2017-06-27 00:47:49.374
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Enrico'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.

MY SOLUTION:
"Delete all folders from USER_FOLDER ( .p2 .eclipse ) and PROGRAMFILES. Remember to reboot!!!! Now all works fine with eclipse oxygen and git project"


问:
Sockets in Python giving error
I am serving a test file as follows:

```<code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
facebook = open("sources/facebook.htm","rb")
listen = ("localhost", 2000)
sock.bind(listen)
sock.listen(1)
while True:
    connection, client_address = sock.accept()
    print("Got a Connection from: " + client_address[0])
    sock.send(facebook.read(10000000))
</code>```

I have downloaded facebook homepage to test connections but when I connect to this page, it gives the following error:

Got a Connection from: 127.0.0.1
  Traceback (most recent call last):
    File "C:\Users\Export.1\blocker.py", line 11, in
      sock.send(facebook.read(1000000))
  OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

How can I fix it?

答:
The error occurs because you are sending reply to the server socket instead of client, try changing

```<code>sock.send(facebook.read(10000000))
</code>```

to

```<code>connection.send (facebook.read(1000000))
</code>```

instead

Title: Sockets in Python giving error

Body:
I am serving a test file as follows:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
facebook = open("sources/facebook.htm","rb")
listen = ("localhost", 2000)
sock.bind(listen)
sock.listen(1)
while True:
    connection, client_address = sock.accept()
    print("Got a Connection from: " + client_address[0])
    sock.send(facebook.read(10000000))

I have downloaded facebook homepage to test connections but when I connect to this page, it gives the following error:

Got a Connection from: 127.0.0.1
  Traceback (most recent call last):
    File "C:\Users\Export.1\blocker.py", line 11, in
      sock.send(facebook.read(1000000))
  OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

How can I fix it?

Body:
The error occurs because you are sending reply to the server socket instead of client, try changing

sock.send(facebook.read(10000000))

to

connection.send (facebook.read(1000000))

instead


问:
How to convert string to byte arrays?
How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".

答: Python 2.6 and later have a bytearray type which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes "in place" rather than having to create a whole new string. It has a nice mix of the features of lists and strings. And it also makes your intent clear, that you are working with arbitrary bytes rather than text.</p>

Title: How to convert string to byte arrays?


问:
Process IDs are the same in User mode and Kernel mode
I was shocked that I got the same PID between User mode and Kernel mode in an IOCTL request from my application to my kernel driver(WDM) via DeviceIoControl() Win32 API.

As far as I know, drivers have its own PID in kernel mode; applications own its PID in user mode, they were separated, can be communicated through IOCTL. But today, I got the same PID between user/kernel mode in an IOCTL request. I got PID via GetCurrentProcessId() function in user mode; and got PID via PsGetCurrentProcessId() function in kernel mode, showing the result in user mode application, those two PID are the same.

Does anyone know why?

答:
What you saw is normal. In Windows, it is normal that a thread spent part of its time running user mode codes and part of its time running kernel mode codes. In your case, after a thread executed your application which made a call to execute IOCTL, Windows kernel used this same thread to execute your kernel mode driver codes to handle this IOCTL.

Hope this helps.


问:
sorting list items alphabetically
I have a simple unordered list i.e. a menu (with two levels of submenus). I want its submenus (and submenus of these submenus) to be displayed alphabetically from top to down. The HTML code for the menu is as follows:

```<code>    <div id="sidebar2" class="sidebar" >
         <ul class="goo-collapsible goo-coll-stacked">
           <li class="header">Information Systems</li>
         </ul>
      <div >

       <div id="nav">
         <ul id="navList">

            <li><a href="#">Other Databases and Portals</a>
    <!-- This is the sub nav -->
              <ul class="listTab">
                 <li ><a href='http://www.icar.org.in/rohudatabase/index.php' target="_blank">Rohu Database</a></li>
            <li ><a href='http://117.240.114.67/weedid/aiwsweedident.aspx' target="_blank">Weed Seed Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/cwsmainweeds.aspx' target="_blank">Weed Seedling Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/bwiweedident.aspx' target="_blank">Weed Identification</a></li>

            <li ><a href='http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href='http://www.cropweatheroutlook.in' target="_blank">Crop Weather Outlook: AICRPAM tools</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/formfish/index.html' target="_blank">Automated Species Identification System</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/ornamental/home.aspx' target="_blank">Marine ornamental finfishes and shell fishes</a></li>
            <li ><a href='http://210.212.93.85/agris/breed.aspx' target="_blank">Animal Genetic Resources of India</a></li>
            <li ><a href='http://www.ncipm.org.in/cropsap2014/login.aspx' target="_blank">Crop Pest Surveillance and Advisory</a></li>
            <li ><a href='http://www.ncipm.org.in/ICTMalawi/' target="_blank">ICT Based Pest Surveillance</a></li>
            <li ><a href='http://ctcri.in/statistics/FormsCEI.aspx' target="_blank">TUBER CROPS STATISTICS</a></li>

            <li ><a href='http://www.crijaf.org.in/SideLinks/QuickLinks/AgrometeorologicalData.html' target="_blank">Agrometeorological Data at ICAR-CRIJA</a></li>
            <li ><a href=' http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href=' http://nrcgrapes.nic.in/weather_forecast_based_grape_adv.htm' target="_blank">Weather forecast based grape advice</a></li>
            <li ><a href='http://research.ciphet.in/' target="_blank">Post-Harvest Machinery</a></li>
            <li ><a href='http://cift.res.in/innercontent.php?contentid=NjA=' target="_blank">CIFT Knowledge Base</a></li>
            <li ><a href='http://nrce.nic.in/breeds.php' target="_blank">Equine Breeds of India</a></li>
    </ul>
  </li>
  <li><a href="#">Genetic Resources Portals</a>
    <!-- This is the sub nav -->
    <ul class="listTab">
     <li ><a href='http://www.mgrportal.org.in/' target="_blank">Microbial Genetic Resources Portal</a></li>
            <li ><a href='http://www.nbpgr.ernet.in/PGR_Databases.aspx' target="_blank">PGR Database</a></li>
            <li ><a href='http://www.nbpgr.ernet.in:8080/PGRPortal/(S(fzkcby45lxboum2hufans255))/default.aspx' target="_blank">PGR Portal</a></li>
            <li ><a href='http://210.212.93.85/agrportal/index.htm' target="_blank">Animal Genetic Resources Portal</a></li>
            <li ><a href='http://www.sugarcane.res.in/index.php/en/resrch/genetic-resources' target="_blank">Sugarcane Genetic Resources</a></li>
    </ul>
  </li>
  </div>
  </div>
  <div style="margin-top: 65px;">
  <ul class="goo-collapsible goo-coll-stacked">
    <li class="header">Latest News</li>
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">
    <li><a href="PDF/Digitization AICRPs Information.pdf" target="_blank" >Digitization AICRPs Information</a></li>
    <li><a href="PDF/Draft Format for Technology Database.pdf" >Draft Format for Technology Database</a></li>
    <li><a href="PDF/ICAR Guidelines Research Papers 2014.pdf" >ICAR Guidelines Research Papers 2014</a></li>
    <li><a href="PDF/Letter for Nomination of Nodal officers.pdf" >Letter for Nomination of Nodal officers</a></li>
    <li><a href="PDF/Mapping of Natural Resources.pdf" >Mapping of Natural Resources</a></li>
    <li><a href="JavaScript:display('Circular');" >Circular</a></li>
    </marquee>
    </ul>
    </div>
</div>
</code>```

here the div whose menu I want to be sorted is the one with id=nav (rest are header and footer of the menu).
Please aid me over the matter.

答:
The answer can be simple and elegant with Angular JS, since u can apply native filters to "ng-repeat" directive.
In this case you need "orderBy".
See API reference https://docs.angularjs.org/api/ng/filter/orderBy

function ctrl($scope) {
  $scope.filter = 'name';
  $scope.alphabeticalReverse = false;
  $scope.menuItems = [{
      name: 'itemB',
      link: 'https://stackoverflow.com/',
      submenue: [{
          name: 'subItemZ',
          link: 'https://stackoverflow.com/'
        },
        {
          name: 'subItemA',
          link: 'https://stackoverflow.com/'
        }
      ]
    },
    {
      name: 'itemC',
      link: 'https://stackoverflow.com/'
    },
    {
      name: 'itemA',
      link: 'https://stackoverflow.com/'
    }
  ];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <meta charset=utf-8 />
  <title>Angular JS Demo</title>
</head>

<body ng-controller="ctrl">
  <ul class="main-menu">
    <li ng-repeat="item in menuItems | orderBy: filter:alphabeticalReverse">
      {{item.name}}
      <ul class="sub-menu">
        <li ng-repeat="subItem in item.submenue | orderBy:filter:!alphabeticalReverse">
          {{subItem.name}}
        </li>
      </ul>
    </li>
  </ul>
</body>

</html></code>```

Title: sorting list items alphabetically

Body:
I have a simple unordered list i.e. a menu (with two levels of submenus). I want its submenus (and submenus of these submenus) to be displayed alphabetically from top to down. The HTML code for the menu is as follows:

Information Systems

Other Databases and Portals

Rohu Database

Weed Seed Identification

Weed Seedling Identification

Weed Identification

Crop Pest DSS

Crop Weather Outlook: AICRPAM tools

Automated Species Identification System

Marine ornamental finfishes and shell fishes

Animal Genetic Resources of India

Crop Pest Surveillance and Advisory

ICT Based Pest Surveillance

TUBER CROPS STATISTICS

Agrometeorological Data at ICAR-CRIJA

Crop Pest DSS

Weather forecast based grape advice

Post-Harvest Machinery

CIFT Knowledge Base

Equine Breeds of India

Genetic Resources Portals

Microbial Genetic Resources Portal

PGR Database

PGR Portal

Animal Genetic Resources Portal

Sugarcane Genetic Resources

Latest News

    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">

Digitization AICRPs Information

Draft Format for Technology Database

ICAR Guidelines Research Papers 2014

Letter for Nomination of Nodal officers

Mapping of Natural Resources

Circular

    </marquee>

here the div whose menu I want to be sorted is the one with id=nav (rest are header and footer of the menu).
Please aid me over the matter.

Body:
The answer can be simple and elegant with Angular JS, since u can apply native filters to "ng-repeat" directive.
In this case you need "orderBy".
See API reference https://docs.angularjs.org/api/ng/filter/orderBy

function ctrl($scope) {
  $scope.filter = 'name';
  $scope.alphabeticalReverse = false;
  $scope.menuItems = [{
      name: 'itemB',
      link: 'https://stackoverflow.com/',
      submenue: [{
          name: 'subItemZ',
          link: 'https://stackoverflow.com/'
        },
        {
          name: 'subItemA',
          link: 'https://stackoverflow.com/'
        }
      ]
    },
    {
      name: 'itemC',
      link: 'https://stackoverflow.com/'
    },
    {
      name: 'itemA',
      link: 'https://stackoverflow.com/'
    }
  ];
}

<!DOCTYPE html>
<html ng-app>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <meta charset=utf-8 />
  <title>Angular JS Demo</title>
</head>

<body ng-controller="ctrl">
  <ul class="main-menu">
    <li ng-repeat="item in menuItems | orderBy: filter:alphabeticalReverse">
      <a ng-href="{{item.link}}">{{item.name}}</a>
      <ul class="sub-menu">
        <li ng-repeat="subItem in item.submenue | orderBy:filter:!alphabeticalReverse">
          <a ng-href="{{subItem.link}}">{{subItem.name}}</a>
        </li>
      </ul>
    </li>
  </ul>
</body>

</html>


问:
'at' command won't open the program
I have a Python script that opens a VLC player; when I run it from the command line, it works perfectly.

I have a bash function that calls this program with the input of a time, like so:

```<code>alarm (){
    echo "python /Users/thumbtackthief/Documents/code/steven_alarm/alarm.py" | at ${1:-0800}
}
</code>```

When I call this function, it runs at the appropriate time, but does not actually open the program.  I know it is running because in /var/mail I get a message with any print statements from the functions (not sure why it's outputting to /var/mail; I didn't set that up).  Is there something different I'm supposed to do to actually open the VLC player?  Permissions on player and video are set to 755.

Here is a message in /var/mail:

```<code>From thumbtackthief@My-iMac.local  Tue Jul  4 09:51:16 2017
Return-Path: <thumbtackthief@My-iMac.local>
X-Original-To: thumbtackthief
Delivered-To: thumbtackthief@My-iMac.local
Received: by My-iMac.local (Postfix, from userid 501)
    id 51B758F818FC; Tue,  4 Jul 2017 09:51:15 -0400 (EDT)
Subject: Output from your job a00017017d429f
Message-Id: <20170704135116.51B758F818FC@My-iMac.local>
Date: Tue,  4 Jul 2017 09:51:15 -0400 (EDT)
From: thumbtackthief@My-iMac.local (Atrun Service)

python /Users/thumbtackthief/Documents/code/steven_alarm/alarm.py
</code>```

答:
At does not execute under your login-shell.  As for why you are receiving the output via mail: that is normal, see man at:

The user will be mailed standard error and standard output from his
  commands, if any. Mail will be sent using the command
  /usr/sbin/sendmail. If at is executed from a su(1) shell, the owner of >the login shell will receive the mail.

So, because you're in a different context, the script doesn't know where to display your VLC. Handing out a DISPLAY variable would help, but then the VLC also needs the authority to display there.

And yes, it's probably more a unix/linux thing.

Something to try, if you're in a sufficiently closed environment (this is a cut-and-paste from my environment):

```<code>[ljm@verlaine ~]$ xhost +
access control disabled, clients can connect from any host
[ljm@verlaine ~]$ echo $DISPLAY
:0.0
</code>```

The :0.0 is used in your at:

```<code>[ljm@verlaine ~]$ at 19:30
warning: commands will be executed using /bin/sh
at> DISPLAY=:0.0 xclock  #
at> <EOT>
job 6 at Tue Jul  4 19:30:00 2017
</code>```

That displays an xclock at that specific time.

Title: 'at' command won't open the program

Body:
I have a Python script that opens a VLC player; when I run it from the command line, it works perfectly.

I have a bash function that calls this program with the input of a time, like so:

alarm (){
    echo "python /Users/thumbtackthief/Documents/code/steven_alarm/alarm.py" | at ${1:-0800}
}

When I call this function, it runs at the appropriate time, but does not actually open the program.  I know it is running because in /var/mail I get a message with any print statements from the functions (not sure why it's outputting to /var/mail; I didn't set that up).  Is there something different I'm supposed to do to actually open the VLC player?  Permissions on player and video are set to 755.

Here is a message in /var/mail:

From thumbtackthief@My-iMac.local  Tue Jul  4 09:51:16 2017
Return-Path: <thumbtackthief@My-iMac.local>
X-Original-To: thumbtackthief
Delivered-To: thumbtackthief@My-iMac.local
Received: by My-iMac.local (Postfix, from userid 501)
    id 51B758F818FC; Tue,  4 Jul 2017 09:51:15 -0400 (EDT)
Subject: Output from your job a00017017d429f
Message-Id: <20170704135116.51B758F818FC@My-iMac.local>
Date: Tue,  4 Jul 2017 09:51:15 -0400 (EDT)
From: thumbtackthief@My-iMac.local (Atrun Service)

python /Users/thumbtackthief/Documents/code/steven_alarm/alarm.py

Body:
At does not execute under your login-shell.  As for why you are receiving the output via mail: that is normal, see man at:

The user will be mailed standard error and standard output from his
  commands, if any. Mail will be sent using the command
  /usr/sbin/sendmail. If at is executed from a su(1) shell, the owner of >the login shell will receive the mail.

So, because you're in a different context, the script doesn't know where to display your VLC. Handing out a DISPLAY variable would help, but then the VLC also needs the authority to display there.

And yes, it's probably more a unix/linux thing.

Something to try, if you're in a sufficiently closed environment (this is a cut-and-paste from my environment):

[ljm@verlaine ~]$ xhost +
access control disabled, clients can connect from any host
[ljm@verlaine ~]$ echo $DISPLAY
:0.0

The :0.0 is used in your at:

[ljm@verlaine ~]$ at 19:30
warning: commands will be executed using /bin/sh
at> DISPLAY=:0.0 xclock  #
at> <EOT>
job 6 at Tue Jul  4 19:30:00 2017

That displays an xclock at that specific time.


问:
Download commit using git clone
With the git clone command and arguments --depth/--branch, you can download the last commit of a specific repository branch, but how to download a specific commit using its hash?

P.S. The use of git clone and git checkout hash is not suitable, because in that case necessary to make a clone of the entire repository.

Thanks!

答:
If the repo is in github, you can navigate to the tree view of the repo at https://github.com/<repo_name>/tree/<commit_sha>

Then clicking on the Download ZIP button on the right-hand navigation bar will download the repo up to the specified commit.

Title: Download commit using git clone


问:
Using lapply with more than one item that differs between function calls
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

```<code>#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))
</code>```

答:
I guess you could adapt your lapply function to take column names and use them for indexing:

```<code>res <- lapply(names(data)[-1], function(x){

  mod_cntrl <- samplemode[samplemode$samples == as.character(settings[settings$samples == x,2]),2]

  B <- sum(data[,x][data$CAG >= mod_cntrl]) #Sum heights > mode
  A <- sum(data[,x][data$CAG <= mod_cntrl]) #Sum heights < mode

  mod_smpl <- data$CAG[which.max(data[,x])]

  C <- sum(data[,x][data$CAG >= mod_smpl])
  D <- sum(data[,x][data$CAG <= mod_smpl])

  data.frame(sample=x,prop = C/(C+D),ctrlprop = B/(A+B))

})

> do.call(rbind,res)
  sample      prop  ctrlprop
1    A01 0.5068066 0.5068066
2    A02 0.3797468 1.0000000
3    A03 0.5896748 0.5896748
4    A04 0.4146568 0.7332421
</code>```

I guess this will do just fine, but there might be a more elegant solution.

Body:
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))

Body:
I guess you could adapt your lapply function to take column names and use them for indexing:

res <- lapply(names(data)[-1], function(x){

  mod_cntrl <- samplemode[samplemode$samples == as.character(settings[settings$samples == x,2]),2]

  B <- sum(data[,x][data$CAG >= mod_cntrl]) #Sum heights > mode
  A <- sum(data[,x][data$CAG <= mod_cntrl]) #Sum heights < mode

  mod_smpl <- data$CAG[which.max(data[,x])]

  C <- sum(data[,x][data$CAG >= mod_smpl])
  D <- sum(data[,x][data$CAG <= mod_smpl])

  data.frame(sample=x,prop = C/(C+D),ctrlprop = B/(A+B))

})

> do.call(rbind,res)
  sample      prop  ctrlprop
1    A01 0.5068066 0.5068066
2    A02 0.3797468 1.0000000
3    A03 0.5896748 0.5896748
4    A04 0.4146568 0.7332421

I guess this will do just fine, but there might be a more elegant solution.


问:
Calling another ruby file that is not a gem
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

```<code>class TestClass

  def say_hello
    puts "say hello"
  end
end
</code>```

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

```<code>require 'TestClass.rb'

puts "start"
say_hello
</code>```

But it fails with :

```<code>C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `<main>'
</code>```

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?

答:
Is the TestClass file in the same dir?
Make the TestClass.rb file lowercase and load it with

```<code>require './testclass'
</code>```

no need for the .rb

I'd suggest putting any classes in a lib folder.
Then you require file as follows:

```<code>require './lib/testclass'
</code>```

Body:
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

class TestClass

  def say_hello
    puts "say hello"
  end
end

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

require 'TestClass.rb'

puts "start"
say_hello

But it fails with :

C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `'

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?

Body:
Is the TestClass file in the same dir?
Make the TestClass.rb file lowercase and load it with

require './testclass'

no need for the .rb

I'd suggest putting any classes in a lib folder.
Then you require file as follows:

require './lib/testclass'


问:
i18n translations in rspec
I want to isolate my test from internalization. I use rails 3.2.8 and rspec 2.11.1

I put this code to spec/support/translations.rb

```<code>module I18nHelpers
  def with_translations(locale, translations)
    I18n.backend.store_translations locale, translations
    yield
  ensure
    I18n.reload!
  end
</code>```

end

```<code>RSpec.configure do |config|
  config.include I18nHelpers
end
</code>```

Then I test application helper:

```<code>describe ApplicationHelper do
  context "messages" do
    it "show body" do
       with_translations :en, navigation: {messages: 'foo'} do
           concat messages_navigation
           assert_test 'span', 'foo'
       end
    end
  end
end
</code>```

But this test falls with message

```<code>Failure/Error: assert_select 'span', text: /foo/
     MiniTest::Assertion:
        </foo/> expected but was
        <"Messages">.
</code>```

'Messages' is from my real config/locales/en.yml
I test #store_translations from console and it works. but when i put line p I18n.t(translations.key.first) before ensure word in helper module, it shows me old translations.

Thanks for any help!

答:
After being stuck with a similar issue, I ended up writing a helper like this:

Helper

```<code>module TranslationSupport
  def with_translation(replacement_translation)
    I18n.t(".").deep_merge!(replacement_translation)
    begin
      yield
    ensure
      I18n.reload!
    end
  end
end
</code>```

The shortcut here is initialising the backend first with I18n.t(".") and then merge in the desired values.

As other answers suggest, alternatively one could initialise the i18n backend then use I18n.backend.store_translations to update the values. The downside of this approach is one needs to pass the locale as an argument.

Usage

This helper can then used it like so:

```<code>require "rails_helper"
require "support/translation"

RSpec.describe "testing a view with overridden translations" do
  include TranslationSupport

  it "works" do
    translations = {
      homepage: {
        index: {
          label: "Overridden"
        }
      }
    }

    with_translation(translations) do
      # Your action
    end

    # Expectations
  end
end
</code>```

And if you don't want to include the helper each time:

```<code>RSpec.configure do |config|
  config.include TranslationSupport
end
</code>```

Title: i18n translations in rspec

Body:
I want to isolate my test from internalization. I use rails 3.2.8 and rspec 2.11.1

I put this code to spec/support/translations.rb

module I18nHelpers
  def with_translations(locale, translations)
    I18n.backend.store_translations locale, translations
    yield
  ensure
    I18n.reload!
  end

end

RSpec.configure do |config|
  config.include I18nHelpers
end

Then I test application helper:

describe ApplicationHelper do
  context "messages" do
    it "show body" do
       with_translations :en, navigation: {messages: 'foo'} do
           concat messages_navigation
           assert_test 'span', 'foo'
       end
    end
  end
end

But this test falls with message

Failure/Error: assert_select 'span', text: /foo/
     MiniTest::Assertion:
        </foo/> expected but was
        <"Messages">.

'Messages' is from my real config/locales/en.yml
I test #store_translations from console and it works. but when i put line p I18n.t(translations.key.first) before ensure word in helper module, it shows me old translations.

Thanks for any help!

Body:
After being stuck with a similar issue, I ended up writing a helper like this:

Helper

module TranslationSupport
  def with_translation(replacement_translation)
    I18n.t(".").deep_merge!(replacement_translation)
    begin
      yield
    ensure
      I18n.reload!
    end
  end
end

The shortcut here is initialising the backend first with I18n.t(".") and then merge in the desired values.

As other answers suggest, alternatively one could initialise the i18n backend then use I18n.backend.store_translations to update the values. The downside of this approach is one needs to pass the locale as an argument.

Usage

This helper can then used it like so:

require "rails_helper"
require "support/translation"

RSpec.describe "testing a view with overridden translations" do
  include TranslationSupport

  it "works" do
    translations = {
      homepage: {
        index: {
          label: "Overridden"
        }
      }
    }

    with_translation(translations) do
      # Your action
    end

    # Expectations
  end
end

And if you don't want to include the helper each time:

RSpec.configure do |config|
  config.include TranslationSupport
end


问:
R: Extract unique values in one column grouped by values in another column
I had thought I could solve this with data.table but looks like it is a bit more difficult. My dataframe looks like this:

```<code>userID1   A
userID1   A
userID1   B
userID2   A
userID2   A
</code>```

The output is supposed to look like this:

```<code>userID1   A
userID1   B
userID2   A
</code>```

Basically create a row for each unique user and item occurence. Most of the examples are about counting unique elements but not about actually extracting these. Any suggestions?

答:
This is a dplyr solution that should get those results</p>

```<code>library(dplyr)

df <- data.frame(user = c(rep("userID1",3), rep("userID2",2)),
                 group = c("A","A","B","A","A"),
                 stringsAsFactors = FALSE)

df <- df %>%
      group_by(user, group) %>%
      filter(row_number() == 1)
</code>```

Body:
I had thought I could solve this with data.table but looks like it is a bit more difficult. My dataframe looks like this:

userID1   A
userID1   A
userID1   B
userID2   A
userID2   A

The output is supposed to look like this:

userID1   A
userID1   B
userID2   A

Basically create a row for each unique user and item occurence. Most of the examples are about counting unique elements but not about actually extracting these. Any suggestions?

Body:
This is a dplyr solution that should get those results

library(dplyr)

df <- data.frame(user = c(rep("userID1",3), rep("userID2",2)),
                 group = c("A","A","B","A","A"),
                 stringsAsFactors = FALSE)

df <- df %>%
      group_by(user, group) %>%
      filter(row_number() == 1)


问:
recursively delete all JSON keys with null values and delete parent key if all child keys are deleted
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

```<code>x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}
</code>```

should turn into this:

```<code>x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }
</code>```

Here is the function that I wrote to delete all keys with null values:

```<code>function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }
</code>```

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

```<code>x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }
</code>```

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.

答:
Use Object.keys().length to check if the object is empty or not</p>

```<code>function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
       //extra check for an empty object.
       if(Object.keys(app[key]).length === 0){
         delete app[key]
       }
       else{
          delKeys(app[key])
       }
    }
    if(app[key] === null){
      delete app[key]
    }
}
</code>```

Body:
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}

should turn into this:

x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }

Here is the function that I wrote to delete all keys with null values:

function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.

Body:
Use Object.keys().length to check if the object is empty or not

function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
       //extra check for an empty object.
       if(Object.keys(app[key]).length === 0){
         delete app[key]
       }
       else{
          delKeys(app[key])
       }
    }
    if(app[key] === null){
      delete app[key]
    }
}


问:
TypeError: 'Response' object has no attribute '__getitem__'
I am trying to get a value from a response object in a dictionary, but I keep running into this error, am I wrong in thinking you __getitem__ is more commonly used for indexing in classes?

Here is the code:

```<code>import json
import requests
from requests.auth import HTTPBasicAuth

url = "http://public.coindaddy.io:4000/api/"
headers = {'content-type': 'application/json'}
auth = HTTPBasicAuth('rpc', '1234')

payload = {
  "method": "get_running_info",
  "params": {},
  "jsonrpc": "2.0",
  "id": 0,
}

response = requests.post(url, data=json.dumps(payload), headers=headers,   auth=auth)

print("respone is: ", response['result'])
</code>```

答:
Just change your source code a bit like this :

```<code> response = requests.post(url, json=json.dumps(payload), headers=headers,   auth=auth).json()

 print("respone is: ", response['result'].encode('utf-8'))
</code>```

It's true that response object alone can't be indexed instead for that purpose you need to return info in json format (in order parse response information ) which you can do so using json() and
Here in order to get proper string you must encode it with utf-8 (other wise your output will be something like this -u'LikeThis)

Body:
I am trying to get a value from a response object in a dictionary, but I keep running into this error, am I wrong in thinking you __getitem__ is more commonly used for indexing in classes?

Here is the code:

import json
import requests
from requests.auth import HTTPBasicAuth

url = "http://public.coindaddy.io:4000/api/"
headers = {'content-type': 'application/json'}
auth = HTTPBasicAuth('rpc', '1234')

payload = {
  "method": "get_running_info",
  "params": {},
  "jsonrpc": "2.0",
  "id": 0,
}

response = requests.post(url, data=json.dumps(payload), headers=headers,   auth=auth)

print("respone is: ", response['result'])

Body:
Just change your source code a bit like this :

 response = requests.post(url, json=json.dumps(payload), headers=headers,   auth=auth).json()

 print("respone is: ", response['result'].encode('utf-8'))

It's true that response object alone can't be indexed instead for that purpose you need to return info in json format (in order parse response information ) which you can do so using json() and
Here in order to get proper string you must encode it with utf-8 (other wise your output will be something like this -u'LikeThis)

ContentLicense: CC BY-SA 4.0


问:
Setting tab order with javascript
I have a page which has multiple forms. I'm using Mootools sliding tabs so each of the buttons on the menu slide along to the next form. There are 3 forms which are technically on the same HTML page. See an example of the technique at http://creativepony.com/archive/demos/sliding-tabs/

My problem is when a user presses the tab key and tabs through to the last field I want the tab order so it goes back to the first field. This is so the user does not accidentally tab to the next form. The user would end up looping back around the same form fields. For the user to reach the next form they use the menu so I don't want them to be able to tab to the next form.

I am aware of setting tab order with 'tabindex' but this doesn't help me make the user return to the first field of that form.

Any ideas how to achieve this with javascript?

答:
You can do this via event listeners:</p>

```<code>$$(".foo").addEvent("click", function(e) {
  if (e.keyCode == 9) new Event(e).stop();
  $("#myfield").focus();
});
</code>```

Title: Setting tab order with javascript

Body:
You can do this via event listeners:

$$(".foo").addEvent("click", function(e) {
  if (e.keyCode == 9) new Event(e).stop();
  $("#myfield").focus();
});


问:
Beginner questions about Frtos compiler(s)
I want to learn FreeRtos I just started reading some pdf books online. I'm a total beginner in this area and I have a question:

I have googled and found out that "Visual Studio 2010 Express" compiler supports FreeRtos. Does that mean that If I write some C FreeRTOS code in this compiler just like I would do a normal .c program will it work fine? Also please explain what is a "port" when talking about RTOS.

Please help me clear this up as I'm planning to start compiling the examples that I read in my pdf books. Thank you.

答: Yes you can run FreeRTOS in a Windows environment, but don't expect real time behaviour when you do.  The FreeRTOS scheduler will be scheduling the tasks like normal, but ultimately it will be running in a Windows process, which Windows itself has control over.  If you are reading the latest book (available for free download) then it tells you about this and the examples are already pre-configured to run in the windows (simulator) environment.  You can also find out more about running FreeRTOS in a Windows process here: http://www.freertos.org/FreeRTOS-Windows-Simulator-Emulator-for-Visual-Studio-and-Eclipse-MingW.html</p>


问:
How to make an android apk file in android studio that runs in all mobiles for testing purpose only
I'm new to android, When i'm installing android app via USB cable manually it's running but i want to share it and run in another mobile phones for testing purpose for that what i've to do?</p>

答:
What's the real issue..? Take the APK and simply sideload it in another phone. Or, connect the phone with your machine.

Firebase offers a limited test for any real and virtual devices on your choice. Use the free services everyday to test it on all available devices.


问:
How to get rid of V677: custom declaration of a standard type warning
We are using a PVS Studio (free variant for opensource projects) in conjunction with travis-ci and it for some reason spawns errors for files located in /usr/local/clang-3.5.0/lib/clang/3.5.0/include:

```
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:58:1: warning: V677 Custom declaration of a standard 'size_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:86:1: warning: V677 Custom declaration of a standard 'wchar_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stdarg.h:30:1: warning: V677 Custom declaration of a standard 'va_list' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:47:1: warning: V677 Custom declaration of a standard 'ptrdiff_t' type. The declaration from system header files should be used instead.
```

This location looks like an example of “system” headers for non-standard compiler and is far away from the project root (which AFAIR is somewhere in /home: standard travis location). Script run uses latest version from https://www.viva64.com/en/pvs-studio-download-linux/, latest run at “Mon Jul 3 20:13:42 UTC 2017” (unfortunately, used version is not saved).

答: It appears that PVS does not detect the error if clang is updated to clang-4.0.</p>

Body:
We are using a PVS Studio (free variant for opensource projects) in conjunction with travis-ci and it for some reason spawns errors for files located in /usr/local/clang-3.5.0/lib/clang/3.5.0/include:

/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:58:1: warning: V677 Custom declaration of a standard 'size_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:86:1: warning: V677 Custom declaration of a standard 'wchar_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stdarg.h:30:1: warning: V677 Custom declaration of a standard 'va_list' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:47:1: warning: V677 Custom declaration of a standard 'ptrdiff_t' type. The declaration from system header files should be used instead.

This location looks like an example of “system” headers for non-standard compiler and is far away from the project root (which AFAIR is somewhere in /home: standard travis location). Script run uses latest version from https://www.viva64.com/en/pvs-studio-download-linux/, latest run at “Mon Jul 3 20:13:42 UTC 2017” (unfortunately, used version is not saved).


问:
Select one column header same name and display data horizontal
I have 2 tables :

1-contracts

```<code>    contracts_id  |  subject_contract
    001           |  name
    002           |  name
</code>```

2-contracts_files

```<code>    contracts_id  |  file_data
    001           |  1image <varbinary(MAX)>
    002           |  1image <varbinary(MAX)>
    001           |  2image <varbinary(MAX)>
    002           |  2image <varbinary(MAX)>
</code>```

Need SQL output like this result :

```<code>contracts_id  |  subject_contract  |  file_data   |  file_data
001           |  name              |  1image      |  2image
002           |  name              |  1image      |  2image
</code>```

I try this

```<code>SELECT Contracts.[contracts_id]
      ,Contracts.[subject_contract]
      ,contracts_files.[filedata]

  FROM Contracts , contracts_files

  where contracts_files.contracts_id = Contracts.contracts_id

  AND Contracts.contracts_id=' 001 '
</code>```

but the result was :

```<code>contracts_id  |  subject_contract  |  file_data
    001       |  name              |  1image
    001       |  name              |  2image
</code>```

So how can i create it with 'FOR LOOP' or with 'CASE' ?

答:
If you don't like pivot, do the old way of case (when some variable = 1) then (some value). If the when doesn't work out, null is used, the MAX() will not return a null. Highlight the inner query and run just that to see how the data looks half way thru the transform if you're curious</p>

```<code>SELECT
  contracts_id,
  subject_contract,
  MAX(CASE WHEN rown = 1 then file_data end) as file1,
  MAX(CASE WHEN rown = 2 then file_data end) as file2

FROM
  (SELECT c.contracts_id, subject_contract, file_data, row_number() over (partition by c.[Contracts_id] order by c.[contracts_id]) as rown FROM contracts c INNER JOIN contracts_files cf ON cf.contracts_id = c.contracts_id) a
GROUP BY
  contracts_id,
  subject_contract
</code>```

Body:
I have 2 tables :

1-contracts

    contracts_id  |  subject_contract
    001           |  name
    002           |  name

2-contracts_files

    contracts_id  |  file_data
    001           |  1image <varbinary(MAX)>
    002           |  1image <varbinary(MAX)>
    001           |  2image <varbinary(MAX)>
    002           |  2image <varbinary(MAX)>

Need SQL output like this result :

contracts_id  |  subject_contract  |  file_data   |  file_data
001           |  name              |  1image      |  2image
002           |  name              |  1image      |  2image

I try this

SELECT Contracts.[contracts_id]
      ,Contracts.[subject_contract]
      ,contracts_files.[filedata]

  FROM Contracts , contracts_files

  where contracts_files.contracts_id = Contracts.contracts_id

  AND Contracts.contracts_id=' 001 '

but the result was :

contracts_id  |  subject_contract  |  file_data
    001       |  name              |  1image
    001       |  name              |  2image

So how can i create it with 'FOR LOOP' or with 'CASE' ?

Body:
If you don't like pivot, do the old way of case (when some variable = 1) then (some value). If the when doesn't work out, null is used, the MAX() will not return a null. Highlight the inner query and run just that to see how the data looks half way thru the transform if you're curious

SELECT
  contracts_id,
  subject_contract,
  MAX(CASE WHEN rown = 1 then file_data end) as file1,
  MAX(CASE WHEN rown = 2 then file_data end) as file2

FROM
  (SELECT c.contracts_id, subject_contract, file_data, row_number() over (partition by c.[Contracts_id] order by c.[contracts_id]) as rown FROM contracts c INNER JOIN contracts_files cf ON cf.contracts_id = c.contracts_id) a
GROUP BY
  contracts_id,
  subject_contract


答:
You need to check if app[key] has keys after you delete null keys.

const x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}

function isEmpty(obj) {
  for(var key in obj) return false;

  return true
}

function delKeys(app){
  for(var key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])

      if(isEmpty(app[key])) {
        delete app[key]
      }
    }
    if(app[key] === null){
      delete app[key]
    }
  }
}

delKeys(x)

console.log(x)```

Title: recursively delete all JSON keys with null values and delete parent key if all child keys are deleted


问:
create function sql server 2005 disable errors

I'm trying to write a *.bat file which runs all sql-scripts in given folder (every file in this folder has a create function script):

```<code>for /r "%~dp0\Production\Functions" %%X in (*.sql) do (
   sqlcmd -S%1 -d%2 -b -i "%%X"
)
</code>```

But some functions in the folder are depended on others. So I get Invalid object name error. Is there a way to disable this error?

答:
It is not possible to disable errors generated by SQL when you run (what I think of as) code-based object: stored procedures, functions, views, triggers, and anything else that has to be the sole object of a batch submitted to SQL.

It is also awkward at best to work around this problem. Some options:

One way, as Joe Stefanelli recommends, is to name your files such that they get executed in proper order (by name, or perhaps by date created or something more esoteric).

Another way is to group related functions in single scripts, such that referenced objects must be created before referencing objects.

Or combine the above two, putting all your dependent objects in one script you can guarantee will always run first. Not so useful if your have nested references.

A last (and more kludgy) way is to iterate over your scripts several times (assuming your "create" script will properly deal with an object that already exists), until a given pass raises no errors.

For development purposes, we store code-based objects in individual files, but when it comes time to wrap the code up for push to Production systems, I glom the files together, test it, and shuffle the contents around and retest until no more errors are generated.

Body:
I'm trying to write a *.bat file which runs all sql-scripts in given folder (every file in this folder has a create function script):

for /r "%~dp0\Production\Functions" %%X in (*.sql) do (
   sqlcmd -S%1 -d%2 -b -i "%%X"
)

But some functions in the folder are depended on others. So I get Invalid object name error. Is there a way to disable this error?


问:
Insert in batch mode on PostgreSQL 9.6 with Apache Spark 1.6
Please, there is a configuration or params to do this:

```<code>dataFrame.write.mode(saveMode).jdbc(url, "tablename", new java.util.Properties())
</code>```

Command is written in Scala, Apache Spark 1.6

That takes a DataFrame and inserts data in PostgreSQL row by row, one by one. We need to do this in batch mode.

Anyone knows if exists any configuration or another way to accomplish that?

Thanks in advance

答:
According to documentation - link - you can use batchsize parameter to perform inserts in batches

```<code>dataFrame
    .write
    .mode(saveMode)
    .option("batchsize", 1000)
    .jdbc(url, "tablename", new java.util.Properties())
</code>```

Now insert will be perfomed in batches of 1000 rows

Body:
Please, there is a configuration or params to do this:

dataFrame.write.mode(saveMode).jdbc(url, "tablename", new java.util.Properties())

Command is written in Scala, Apache Spark 1.6

That takes a DataFrame and inserts data in PostgreSQL row by row, one by one. We need to do this in batch mode.

Anyone knows if exists any configuration or another way to accomplish that?

Thanks in advance

Body:
According to documentation - link - you can use batchsize parameter to perform inserts in batches

dataFrame
    .write
    .mode(saveMode)
    .option("batchsize", 1000)
    .jdbc(url, "tablename", new java.util.Properties())

Now insert will be perfomed in batches of 1000 rows


问:
Eclipse (STS) reverts to being a fresh instal every time I open it on my Mac
I have started using mac recently. I downloaded STS and started coding in it. I installed few plugins I needed to work. After a days work I shut down and started it the next day and all off a sudden it again asked for workspace location even if I checked the default location do not ask again checkbox the last time and again I selected the workspace location and checked the checkbox again and now the plugins I installed the previous day are not there I had to install them all over again and it's the same everyday. Can anyone help we with this?</p>

答:
This is a known issue on Mac Os Sierra. I'm not a Mac user myself and not too familiar with the details, but it has something to do with a security feature of Mac OS which is trying to 'sandbox' apps by randomizing thier startup location. This makes STS / Eclipse think its a fresh install and unable to locate any settings / state saved from before.

You can find more info in the STS New and Noteworthy under "Known Issues".

Perhaps these are the most important snippets of information:

If you unpackage the STS archive on macOS Sierra and use it without moving it to a different location on your drive, macOS Sierra Gatekeeper activates a security feature called "Path Randomization" for the app

...

As a workaround, please move the STS.app bundle to a different location on your drive before starting it.


问:
Angular Curly braces not rendering in html
In my browser, the value of the angular curly braces is not displayed. There are no errors in the console and the console logs the value, but in my browser its a blank page. However it should say 'hello World' in the top left.

my app.js:

```<code>    (function() {
      'use strict';
      angular.module('testModule', []);
    }());
</code>```

my controller:

```<code>    (function () {
        'use strict';
        angular
            .module('testModule')
            .controller('testController', Controller);
        Controller.$inject = [];

        function Controller() {
            var vm = this;
            vm.test = "hello World";
            activate();
            function activate() {
                console.log(vm.test);
            }
        }
    })();
</code>```

my html:

```<code><body ng-controller="testController">
    <div>
        {{vm.test}}
    </div>
</body>
</code>```

答:
in template update it like; (As you're using controller as syntax)

```<code>ng-controller="testController as vm"
</code>```

Here's a working plunker

http://plnkr.co/edit/tbENuThIIszfe2D2e4qx?p=preview

Body:
In my browser, the value of the angular curly braces is not displayed. There are no errors in the console and the console logs the value, but in my browser its a blank page. However it should say 'hello World' in the top left.

my app.js:

    (function() {
      'use strict';
      angular.module('testModule', []);
    }());

my controller:

    (function () {
        'use strict';
        angular
            .module('testModule')
            .controller('testController', Controller);
        Controller.$inject = [];

        function Controller() {
            var vm = this;
            vm.test = "hello World";
            activate();
            function activate() {
                console.log(vm.test);
            }
        }
    })();

my html:

        {{vm.test}}

Body:
in template update it like; (As you're using controller as syntax)

ng-controller="testController as vm"

Here's a working plunker

http://plnkr.co/edit/tbENuThIIszfe2D2e4qx?p=preview


问:
How I search a string in core data with swift 3?
I want to search a string in my DB and it keeps returning all records from core data. The other questions I saw here didn't work. Suggestions? </p>

```<code>var users:[Users] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let myrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

        let predicate = NSPredicate(format: "name = '%@'", "alex")
        myrequest.predicate = predicate

        do{
            users = try context.fetch(myrequest) as! [Users]

        }catch{
            print("error")
        }

    }
</code>```

答:
try to do this in do case

```<code>users = try context.fetch(Users.fetchRequest())
</code>```

Body:
I want to search a string in my DB and it keeps returning all records from core data. The other questions I saw here didn't work. Suggestions?

var users:[Users] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let myrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

        let predicate = NSPredicate(format: "name = '%@'", "alex")
        myrequest.predicate = predicate

        do{
            users = try context.fetch(myrequest) as! [Users]

        }catch{
            print("error")
        }

    }

Body:
try to do this in do case

users = try context.fetch(Users.fetchRequest())


问:
Using javascript to alter span text dynamically and keeping the original text
I have a  html page, inside which i have following code snippet, depending on which case we're following:

```<code>CASE 1)    <p> <span id ="xyz">  some code here  </span> </p>
CASE 2)    <p> <span id ="xyz">   </span> some code here </p>
</code>```

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

答:
```<code>document.getElementById('xyz').innerHTML = 'some code here' + 'dynamically code';
</code>```

or

```<code>document.getElementById('xyz').innerHTML = 'dynamically code' + 'some code here' ;
</code>```

Body:
I have a  html page, inside which i have following code snippet, depending on which case we're following:

CASE 1)
   some code here

CASE 2)
     some code here

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

Body:
document.getElementById('xyz').innerHTML = 'some code here' + 'dynamically code';

or

document.getElementById('xyz').innerHTML = 'dynamically code' + 'some code here' ;


答:
You need to rewrite this line

```<code><body ng-controller="testController">
</code>```

as

```<code><body ng-controller="testController as vm">
</code>```

This is because you are using this inside your controller and referencing the scope variable with this cannot be accessed directly by the Angular expression so you need to create a alias of the controller using as you can give it any alias. Then use this alias to access the scope variable. If you use

```<code> `<body ng-controller="testController as ctrl">`
</code>```

then you need to access by {{ctrl.test}}

Title: Angular Curly braces not rendering in html

Body:
You need to rewrite this line

<body ng-controller="testController">

as

<body ng-controller="testController as vm">

This is because you are using this inside your controller and referencing the scope variable with this cannot be accessed directly by the Angular expression so you need to create a alias of the controller using as you can give it any alias. Then use this alias to access the scope variable. If you use

 `<body ng-controller="testController as ctrl">`

then you need to access by {{ctrl.test}}


问:
Delete all rows from datagridview and database
Hi guys as the title says i want to delete all rows from a datagridview and in the process deleting them from the database. Heres my code but its only deleting one row and not all. Thank you</p>

```<code>     private void clear_Click(object sender, EventArgs e)
    {

        if (this.dgvProducts.SelectedRows.Count > 0)
        {
            foreach (DataGridViewRow row in dgvProducts.SelectedRows)
            {
                int selectedIndex = dgvProducts.SelectedRows[0].Index;
                int rowID = int.Parse(dgvProducts[0, selectedIndex].Value.ToString());
                 crud.AddRecord("Delete from Supplier_productlist where ProductID = '" + rowID + "' and SupplierID = '"+supplierid.Text+"' ");

            }
        }

        //dgvProducts.Refresh();

    }
</code>```

答:
In your code, you're looping over only SelectedRows, not all Rows.

```<code>foreach (DataGridViewRow row in dgvProducts.SelectedRows)
</code>```

To loop over the whole datagrid's rows you should use

```<code>foreach (DataGridViewRow row in dgvProducts.**Rows**)
</code>```

Hope, this link helps:
https://msdn.microsoft.com/ru-ru/library/system.windows.forms.datagridview.rows(v=vs.110).aspx

Body:
Hi guys as the title says i want to delete all rows from a datagridview and in the process deleting them from the database. Heres my code but its only deleting one row and not all. Thank you

     private void clear_Click(object sender, EventArgs e)
    {

        if (this.dgvProducts.SelectedRows.Count > 0)
        {
            foreach (DataGridViewRow row in dgvProducts.SelectedRows)
            {
                int selectedIndex = dgvProducts.SelectedRows[0].Index;
                int rowID = int.Parse(dgvProducts[0, selectedIndex].Value.ToString());
                 crud.AddRecord("Delete from Supplier_productlist where ProductID = '" + rowID + "' and SupplierID = '"+supplierid.Text+"' ");

            }
        }

        //dgvProducts.Refresh();

    }

Body:
In your code, you're looping over only SelectedRows, not all Rows.

foreach (DataGridViewRow row in dgvProducts.SelectedRows)

To loop over the whole datagrid's rows you should use

foreach (DataGridViewRow row in dgvProducts.**Rows**)

Hope, this link helps:
https://msdn.microsoft.com/ru-ru/library/system.windows.forms.datagridview.rows(v=vs.110).aspx


问:
Convert this Excel formula into VBA code
```<code>=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400
</code>```

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

```<code>If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function
</code>```

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

答:
```<code> DateAdd ( interval, number, date )
</code>```

You should investigate this and apply it towards what youre trying to do :)

https://www.techonthenet.com/excel/formulas/dateadd.php

Body:
=IF((effDate)-curDate>0,0,IF(curDate-(effDate)+1>nDays,0,nSpend/4))+IF((effDate+365/4*1)-curDate>0,0,IF(curDate-(effDate+365/$4*1)+1>nDays,0,nSpend/4))+IF((effDate+365/4*2)-curDate>0,0,IF(curDate-(effDate+365/4*2)+1>nDays,0,nSpend/4))+IF((effDate+365/4*3)-curDate>0,0,IF(curDate-(effDate+365/4*3)+1>nDays,0,nSpend/4))

effDate: 1/1/2017 (as value)
curDate: 1/31/2017 (as value)
nSpend: 1600
nDays: 60
Correct answer: 400

Above is a long formula I'm trying to covert to VBA code. The way I've been trying to do it is long and I tried breaking it up into smaller functions, but it's not giving me the right answer. My VBA skills are very beginner so I'm not sure what else to try. I keep getting the wrong answer or no answer at all.

This is what I've been trying:

If effdate - curdate > 0 Then
val1 = 0
Exit Function
End If

If curdate - effDate + 1 > nDays Then
val1 = 0
Else
val1 = nSpend / 4

End If

If (effDate + (365 / 4)) - curdate > 0 Then
val2 = 0
Exit Function
End If

If curdate - (effDate + (365 / 4)) + 1 > nDays Then
val2 = 0
Else
val2 = nSpend / 4
End If

If effDate + (365 / (4 * 2)) - curdate > 0 Then
val3 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 2))) + 1 > nDays Then
val3 = 0
Else
val3 = nSpend / 4
End If

If effDate + (365 / (4 * 3)) - curdate > 0 Then
val4 = 0
Exit Function
End If

If curdate - (effDate + (365 / (4 * 3))) + 1 > nDays Then
val4 = 0
Else
val4 = nSpend / 4
End If
End If

APFcst = val1 + val2 + val3 + val4

End Function

I dimmed everything correctly, it's the actual conversion that I have problems with.
I would appreciate the help! This is also a huge learning stretch for me since I just started learning VBA coding.
Thank you!

Body:
 DateAdd ( interval, number, date )

You should investigate this and apply it towards what youre trying to do :)

https://www.techonthenet.com/excel/formulas/dateadd.php