问:
Why can't my Java/SalesForce app create JAXBContext due to a security restriction?
I was on one Java/Salesforce tutorial but I couldn't get it to work as is because SoapBindingStub seems to be obsolete code based upon depreciated libraries.  So I tried to mesh the code with code from JAX-WS Quick Start, but this didn't quite work either.  No matter what I did, ultimately the sample console application would suffer exceptions, complaining "Web Service Exception creating salesface port.: Unable to create JAXBContext due to the security restriction on class javax.xml.ws.WebServiceException".

I gave up (for the moment) trying to mash the two codes, and instead am now just working on abstracting the JAX-WS Quickstart.java so I can understand wow it works and reuse its methods in other applications.

No matter how I slice and dice the code, it always gets stuck at the same location with essentially that same error.

Here is the current code for method which is persistantly failing:

```<code>private void initPort()
{
    try
    {
        URL wsdlLocation = this.getClass().getClassLoader().getResource("META-INF/enterprise.wsdl");
        if (wsdlLocation == null)
        {
            WebServiceException webServiceException = new WebServiceException("enterprise.wsdl not found!");
            ExceptionToolkit.display("Web Service Exception can't find enterprise.wsdl", webServiceException);
            throw webServiceException;
        }
        else {System.out.println("\nFOUND enterprise.wsdl!!!\n\n");}

        QName qName = new QName("urn:enterprise.soap.sforce.com", "SforceService");
        SforceService sforceService = new SforceService( wsdlLocation, qName );
        System.out.println("\nsforceService INITIALIZED. About to get Soap.\n\n");
        Soap soap = (sforceService).getSoap();
        System.out.println("\nWe have soap.\n\n");
        setPort (soap);
    }
    catch (WebServiceException webServiceException)
    {
        ExceptionToolkit.display("Web Service Exception creating salesface port", webServiceException);
        return;
    }
}
</code>```

Here is the error, including output immediately before and after:

```<code>Running main loop

FOUND enterprise.wsdl!!!

sforceService INITIALIZED. About to get Soap.

Web Service Exception creating salesface port: Unable to create JAXBContext due to the security restriction
on class javax.xml.ws.WebServiceException
javax.xml.ws.WebServiceException: Unable to create JAXBContext due to the security restriction
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:131)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:63)
    at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:224)
    at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:588)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:291)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:274)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:267)
    at javax.xml.ws.Service.getPort(Unknown Source)
    at com.sforce.soap.enterprise.SforceService.getSoap(SforceService.java:53)
    at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
    at hu.flux.salesforce.LoginToolkit.doLogin(LoginToolkit.java:122)
    at hu.flux.salesforce.LoginToolkit.<init>(LoginToolkit.java:49)
    at hu.flux.salesforce.samples.Quickstart.mainLoop(Quickstart.java:55)
    at hu.flux.salesforce.samples.Quickstart.<init>(Quickstart.java:28)
    at hu.flux.salesforce.samples.Quickstart.main(Quickstart.java:21)
Caused by: java.security.PrivilegedActionException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:124)
    ... 14 more
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:422)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:270)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:103)
    at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:89)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:126)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:125)
    ... 16 more

1. Login
2. Get Accounts
3. Update Accounts
4. Get Server Timestamp
5. Exit
Enter a menu option:
</code>```

The last line (chronologically) on the stack which refers to my own code is:

```<code>at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
</code>```

System.out.println statements in the source confirms that this is what the execution terminates.  This line specifically states:

```<code>Soap soap = (sforceService).getSoap();
</code>```

Does anyone know how or why this could transcend a security restriction ultimately leaving java unable to create the JAXBContext?

答: If you want to use Jax-WS, see the Jax-WS/salesforce quickstart, there's a long list of java samples for salesfoce on the wiki</p>

Body:
I was on one Java/Salesforce tutorial but I couldn't get it to work as is because SoapBindingStub seems to be obsolete code based upon depreciated libraries.  So I tried to mesh the code with code from JAX-WS Quick Start, but this didn't quite work either.  No matter what I did, ultimately the sample console application would suffer exceptions, complaining "Web Service Exception creating salesface port.: Unable to create JAXBContext due to the security restriction on class javax.xml.ws.WebServiceException".

I gave up (for the moment) trying to mash the two codes, and instead am now just working on abstracting the JAX-WS Quickstart.java so I can understand wow it works and reuse its methods in other applications.

No matter how I slice and dice the code, it always gets stuck at the same location with essentially that same error.

Here is the current code for method which is persistantly failing:

private void initPort()
{
    try
    {
        URL wsdlLocation = this.getClass().getClassLoader().getResource("META-INF/enterprise.wsdl");
        if (wsdlLocation == null)
        {
            WebServiceException webServiceException = new WebServiceException("enterprise.wsdl not found!");
            ExceptionToolkit.display("Web Service Exception can't find enterprise.wsdl", webServiceException);
            throw webServiceException;
        }
        else {System.out.println("\nFOUND enterprise.wsdl!!!\n\n");}

        QName qName = new QName("urn:enterprise.soap.sforce.com", "SforceService");
        SforceService sforceService = new SforceService( wsdlLocation, qName );
        System.out.println("\nsforceService INITIALIZED. About to get Soap.\n\n");
        Soap soap = (sforceService).getSoap();
        System.out.println("\nWe have soap.\n\n");
        setPort (soap);
    }
    catch (WebServiceException webServiceException)
    {
        ExceptionToolkit.display("Web Service Exception creating salesface port", webServiceException);
        return;
    }
}

Here is the error, including output immediately before and after:

Running main loop

FOUND enterprise.wsdl!!!

sforceService INITIALIZED. About to get Soap.

Web Service Exception creating salesface port: Unable to create JAXBContext due to the security restriction
on class javax.xml.ws.WebServiceException
javax.xml.ws.WebServiceException: Unable to create JAXBContext due to the security restriction
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:131)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.postProcess(AbstractSEIModelImpl.java:63)
    at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:224)
    at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:588)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:291)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:274)
    at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:267)
    at javax.xml.ws.Service.getPort(Unknown Source)
    at com.sforce.soap.enterprise.SforceService.getSoap(SforceService.java:53)
    at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)
    at hu.flux.salesforce.LoginToolkit.doLogin(LoginToolkit.java:122)
    at hu.flux.salesforce.LoginToolkit.<init>(LoginToolkit.java:49)
    at hu.flux.salesforce.samples.Quickstart.mainLoop(Quickstart.java:55)
    at hu.flux.salesforce.samples.Quickstart.<init>(Quickstart.java:28)
    at hu.flux.salesforce.samples.Quickstart.main(Quickstart.java:21)
Caused by: java.security.PrivilegedActionException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:124)
    ... 14 more
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.lang.StackTraceElement does not have a no-arg default constructor.
    this problem is related to the following location:
        at java.lang.StackTraceElement
        at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()
        at java.lang.Throwable
        at java.lang.Exception
        at com.sforce.ws.ConnectionException
        at com.sforce.ws.SoapFaultException
        at com.sforce.soap.enterprise.fault.ApiFault
        at public javax.xml.bind.JAXBElement com.sforce.soap.enterprise.fault.ObjectFactory.createFault(com.sforce.soap.enterprise.fault.ApiFault)
        at com.sforce.soap.enterprise.fault.ObjectFactory
com.sforce.ws.types.Time does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.sforce.ws.types.Time
        at public com.sforce.ws.types.Time com.sforce.soap.enterprise.sobject.BusinessHours.getFridayEndTime()
        at com.sforce.soap.enterprise.sobject.BusinessHours
        at public com.sforce.soap.enterprise.sobject.BusinessHours com.sforce.soap.enterprise.sobject.ObjectFactory.createBusinessHours()
        at com.sforce.soap.enterprise.sobject.ObjectFactory

    at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:422)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:270)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:103)
    at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:89)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:126)
    at com.sun.xml.ws.model.AbstractSEIModelImpl$1.run(AbstractSEIModelImpl.java:125)
    ... 16 more

1. Login
2. Get Accounts
3. Update Accounts
4. Get Server Timestamp
5. Exit
Enter a menu option:

The last line (chronologically) on the stack which refers to my own code is:

at hu.flux.salesforce.LoginToolkit.initPort(LoginToolkit.java:78)

System.out.println statements in the source confirms that this is what the execution terminates.  This line specifically states:

Soap soap = (sforceService).getSoap();

Does anyone know how or why this could transcend a security restriction ultimately leaving java unable to create the JAXBContext?


来源: stackexchange

问:
is it possible to draw a two layer Pie Chart?
Hi i am trying to implement a chart like the following. Please see the image and help me find a suitable solution for this. Here i am using  MPAndroidChart Library.

Right now my pie chart is look like below image.

I am using below xml

```<code><com.github.mikephil.charting.charts.PieChart
    android:id="@+id/chart1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

And in java, i have manage angle like that.

```<code>mChart.setMaxAngle(270f); // HALF CHART
mChart.setRotationAngle(135f);
</code>```

I still have not been able to create the inner line of the pie chart. I want the graph that I already mention on top. How can I draw that line?

答:
First you need to add MPAndroidChart library in you project. Here is the basic code I have written, you need to make changes according to your use.

MainActivity.java

```<code>package com.devdwl.stackdemo;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    PieChart mChartOuter, mChartInner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mChartOuter = (PieChart) findViewById(R.id.mChartOuter);
        mChartInner = (PieChart) findViewById(R.id.mChartInner);

        mChartOuter.getDescription().setEnabled(false);
        mChartInner.getDescription().setEnabled(false);

        mChartOuter.setCenterTextSize(10f);
        mChartInner.setCenterTextSize(10f);

        mChartOuter.setHoleRadius(75f);
        mChartInner.setHoleRadius(75f);

        mChartOuter.setTransparentCircleRadius(50f);
        mChartInner.setTransparentCircleRadius(50f);

        mChartOuter.getLegend().setEnabled(false);
        mChartInner.getLegend().setEnabled(false);

        setData();

    }

    private void setData() {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        for (int i = 0; i < 5; i++) {
            entries.add(new PieEntry((float) ((Math.random() * (float) 5) + (float) 5 / 5), i));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mChartOuter.setData(data);
        mChartInner.setData(data);

        mChartOuter.highlightValues(null);
        mChartInner.highlightValues(null);

        mChartOuter.invalidate();
        mChartInner.invalidate();
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/constraint_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartOuter"
        android:layout_width="600dp"
        android:layout_height="600dp"
        android:layout_centerInParent="true" />

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartInner"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true" />

</RelativeLayout>
</code>```

Result

Good Luck.

ContentLicense: CC BY-SA 3.0

Body:
Hi i am trying to implement a chart like the following. Please see the image and help me find a suitable solution for this. Here i am using  MPAndroidChart Library.

Right now my pie chart is look like below image.

I am using below xml

<com.github.mikephil.charting.charts.PieChart
    android:id="@+id/chart1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

And in java, i have manage angle like that.

mChart.setMaxAngle(270f); // HALF CHART
mChart.setRotationAngle(135f);

I still have not been able to create the inner line of the pie chart. I want the graph that I already mention on top. How can I draw that line?

Body:
First you need to add MPAndroidChart library in you project. Here is the basic code I have written, you need to make changes according to your use.

MainActivity.java

package com.devdwl.stackdemo;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    PieChart mChartOuter, mChartInner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mChartOuter = (PieChart) findViewById(R.id.mChartOuter);
        mChartInner = (PieChart) findViewById(R.id.mChartInner);

        mChartOuter.getDescription().setEnabled(false);
        mChartInner.getDescription().setEnabled(false);

        mChartOuter.setCenterTextSize(10f);
        mChartInner.setCenterTextSize(10f);

        mChartOuter.setHoleRadius(75f);
        mChartInner.setHoleRadius(75f);

        mChartOuter.setTransparentCircleRadius(50f);
        mChartInner.setTransparentCircleRadius(50f);

        mChartOuter.getLegend().setEnabled(false);
        mChartInner.getLegend().setEnabled(false);

        setData();

    }

    private void setData() {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        for (int i = 0; i < 5; i++) {
            entries.add(new PieEntry((float) ((Math.random() * (float) 5) + (float) 5 / 5), i));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mChartOuter.setData(data);
        mChartInner.setData(data);

        mChartOuter.highlightValues(null);
        mChartInner.highlightValues(null);

        mChartOuter.invalidate();
        mChartInner.invalidate();
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/constraint_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartOuter"
        android:layout_width="600dp"
        android:layout_height="600dp"
        android:layout_centerInParent="true" />

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartInner"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true" />

</RelativeLayout>

Result

Good Luck.


问:
XSLT conditional include of external file
I want to perform a conditional include in XSLT, but xsl:include is a top level element. You can only use xsl:if or xsl:choose inside of a template. Is there any kind of hack or work around which allows a conditional include of an external file? I tried to use the document() function, but it fails to load my external file ( probably because it doesn't conform to some set of rules which would make it "valid" ).

My external xml file is a bunch of xslt code fragments. depending on the value of a variable in the main XSLT file, the corisponding code from the external file should be "copy/pasted" in place ( like conditional include in C or PHP ).

The flow of my main XSLT file should proceed in the following manner:

```<code>$configurationMode
if ( $configurationMode = Standard ) { xsl:include="standard.xml" } else { xsl:include="alt.xml" }
</code>```

Obviously I cannot do it as simply as the above, hence why I am asking if there is a hack or workaround.

答:
There is one approach I have found to conditionally include files using use-when feature in XSLT 2.0.

You have to create one system property which is passed through the Application at runtime, like in my case I am using Java so I have created "Debug" property using command to run my application:

```<code>java -DDebug=yes myAppPath
</code>```

then in XSLT use this property to include conditional files. For example

```<code><xsl:include href="file1.xslt" use-when="system-property('DEBUG') = 'yes'"/>
<xsl:include href="file2.xslt" use-when="system-property('DEBUG') != 'yes'"/>
</code>```

like that.

Don't know if it fits for asked scenario but YES there is way to do it in XSLT 2.0.
In XSLT 3.0, support for local variable is also added. So this can be easily done there using local variables.

Thanks,
Happy Coding

Body:
I want to perform a conditional include in XSLT, but xsl:include is a top level element. You can only use xsl:if or xsl:choose inside of a template. Is there any kind of hack or work around which allows a conditional include of an external file? I tried to use the document() function, but it fails to load my external file ( probably because it doesn't conform to some set of rules which would make it "valid" ).

My external xml file is a bunch of xslt code fragments. depending on the value of a variable in the main XSLT file, the corisponding code from the external file should be "copy/pasted" in place ( like conditional include in C or PHP ).

The flow of my main XSLT file should proceed in the following manner:

$configurationMode
if ( $configurationMode = Standard ) { xsl:include="standard.xml" } else { xsl:include="alt.xml" }

Obviously I cannot do it as simply as the above, hence why I am asking if there is a hack or workaround.

Body:
There is one approach I have found to conditionally include files using use-when feature in XSLT 2.0.

You have to create one system property which is passed through the Application at runtime, like in my case I am using Java so I have created "Debug" property using command to run my application:

java -DDebug=yes myAppPath

then in XSLT use this property to include conditional files. For example

<xsl:include href="file1.xslt" use-when="system-property('DEBUG') = 'yes'"/>
<xsl:include href="file2.xslt" use-when="system-property('DEBUG') != 'yes'"/>

like that.

Don't know if it fits for asked scenario but YES there is way to do it in XSLT 2.0.
In XSLT 3.0, support for local variable is also added. So this can be easily done there using local variables.

Thanks,
Happy Coding


问:
STM: how to keep metadata when converting from tm to stm document-term matrix?
I'm trying to run structural topic models (using stm package) on the document-term matrix that was prepared using tm package.

I built a corpus in tm package that contains the following metadata:

```<code>library(tm)

myReader2 <- readTabular(mapping=list(content="text", id="id", sentiment = "sentiment"))
text_corpus2 <- VCorpus(DataframeSource(bin_stm_df), readerControl = list(reader = myReader2))

meta(text_corpus2[[1]])
  id       : 11
  sentiment: negative
  language : en
</code>```

After doing some text-cleaning and saving the results as clean_corpus2(metadata still present), I change it to document-term matrix and then read it as stm-compatible matrix:

```<code>library(stm)

chat_DTM2 <- DocumentTermMatrix(clean_corpus2, control = list(wordLengths = c(3, Inf)))
DTM2 <- removeSparseTerms(chat_DTM2 , 0.990)
DTM_st <-readCorpus(DTM2, type = "slam")
</code>```

So far, so good. However, when I try to specify the metadata using stm-compatible data, the metadata is gone:

```<code>docsTM <- DTM_st$documents # works fine
vocabTM <- DTM_st$vocab # works fine
metaTM <- DTM_st$meta # returns NULL

> metaTM
NULL
</code>```

How do I keep the metadata from tm-generated Corpus in stm-compatible document-term matrix? Any suggestions welcome, thanks.

答:
How about trying the quanteda package?

Without the ability to access your object, I cannot guarantee this works verbatim, but it should:

```<code>library("quanteda")

# creates the corpus with document variables except for the "text"
text_corpus3 <- corpus(bin_stm_df, text_field = "text")

# convert to document-feature matrix - cleaning options can be added
# see ?tokens
chat_DTM3 <- dfm(text_corpus3)

# similar to tm::removeSparseTerms()
DTM3 <- dfm_trim(chat_DTM3, sparsity = 0.990)

# convert to STM format
DTM_st <- convert(DTM3, to = "stm")

# then it's all there
docsTM <- DTM_st$documents
vocabTM <- DTM_st$vocab
metaTM <- DTM_st$meta      # should return the data.frame of document variables
</code>```

Body:
I'm trying to run structural topic models (using stm package) on the document-term matrix that was prepared using tm package.

I built a corpus in tm package that contains the following metadata:

library(tm)

myReader2 <- readTabular(mapping=list(content="text", id="id", sentiment = "sentiment"))
text_corpus2 <- VCorpus(DataframeSource(bin_stm_df), readerControl = list(reader = myReader2))

meta(text_corpus2[[1]])
  id       : 11
  sentiment: negative
  language : en

After doing some text-cleaning and saving the results as clean_corpus2(metadata still present), I change it to document-term matrix and then read it as stm-compatible matrix:

library(stm)

chat_DTM2 <- DocumentTermMatrix(clean_corpus2, control = list(wordLengths = c(3, Inf)))
DTM2 <- removeSparseTerms(chat_DTM2 , 0.990)
DTM_st <-readCorpus(DTM2, type = "slam")

So far, so good. However, when I try to specify the metadata using stm-compatible data, the metadata is gone:

docsTM <- DTM_st$documents # works fine
vocabTM <- DTM_st$vocab # works fine
metaTM <- DTM_st$meta # returns NULL

> metaTM
NULL

How do I keep the metadata from tm-generated Corpus in stm-compatible document-term matrix? Any suggestions welcome, thanks.

Body:
How about trying the quanteda package?

Without the ability to access your object, I cannot guarantee this works verbatim, but it should:

library("quanteda")

# creates the corpus with document variables except for the "text"
text_corpus3 <- corpus(bin_stm_df, text_field = "text")

# convert to document-feature matrix - cleaning options can be added
# see ?tokens
chat_DTM3 <- dfm(text_corpus3)

# similar to tm::removeSparseTerms()
DTM3 <- dfm_trim(chat_DTM3, sparsity = 0.990)

# convert to STM format
DTM_st <- convert(DTM3, to = "stm")

# then it's all there
docsTM <- DTM_st$documents
vocabTM <- DTM_st$vocab
metaTM <- DTM_st$meta      # should return the data.frame of document variables


问:
SSIS - Input String was not in a correct format SQL
I'm working on a workflow in SSIS and I keep having an error about the result set of one sql task. Here are the info:

From a first table I sum up a field that contain value as such:

```<code> 3.4;534.3;4.5;12.4;
</code>```

with the following stored proc :

```<code>create FUNCTION [dbo].[GetTotalOfSemiColomnSeperatedVal]
(
  @semiColomnSeperatedVal varchar(1000)
)
RETURNS decimal(18,2)
AS
BEGIN

declare @sum decimal(18,2)
DECLARE @x XML
SELECT @x = CAST('<A>'+ REPLACE(@semiColomnSeperatedVal,';','</A><A>')+ '</A>' AS XML)

SELECT @sum=sum(t.value('.', 'decimal(18,2)'))
  FROM @x.nodes('/A') AS x(t)

return @sum END GO
</code>```

The result is added in a table alongside with other information.
The column (Total) is defined as decimal(18,2).

After that, I'm doing a sum of the Total field for a single combination:

```<code>select sum(total)
from mytable
where
column1= ?
and column2= ?
and column3= ?
and column4= ?
and column5= ?
and column5= ?
and column6= ?
and column7= ?
</code>```

So that query returns a single value and in the SQL task:

In the Result set page:

The variable VolTotal here is defined as decimal in the Variable screen.

The error I keep getting is 'input string was not in a correct format '

Do you have any ideas of what I am doing wrong?

Thanks!

答: According to this SO article, you have to store your result into a Double variable. </p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a workflow in SSIS and I keep having an error about the result set of one sql task. Here are the info:

From a first table I sum up a field that contain value as such:

 3.4;534.3;4.5;12.4;

with the following stored proc :

create FUNCTION [dbo].[GetTotalOfSemiColomnSeperatedVal]
(
  @semiColomnSeperatedVal varchar(1000)
)
RETURNS decimal(18,2)
AS
BEGIN

declare @sum decimal(18,2)
DECLARE @x XML
SELECT @x = CAST(''+ REPLACE(@semiColomnSeperatedVal,';','')+ '' AS XML)

SELECT @sum=sum(t.value('.', 'decimal(18,2)'))
  FROM @x.nodes('/A') AS x(t)

return @sum END GO

The result is added in a table alongside with other information.
The column (Total) is defined as decimal(18,2).

After that, I'm doing a sum of the Total field for a single combination:

select sum(total)
from mytable
where
column1= ?
and column2= ?
and column3= ?
and column4= ?
and column5= ?
and column5= ?
and column6= ?
and column7= ?

So that query returns a single value and in the SQL task:

In the Result set page:

The variable VolTotal here is defined as decimal in the Variable screen.

The error I keep getting is 'input string was not in a correct format '

Do you have any ideas of what I am doing wrong?

Thanks!


问:
Excel VBA - Weekday and/or datediff function not working properly
I have the code below which is supposed to parse a column with dates/times and advise (by highlighting) if the value is older than 24 hours ago as of 6:30am on the current day.  If the day is Monday, it is supposed to look back 72 hours (since Saturday and Sunday are not work days) and advise if the value is older than 72 hours as of 6:30am.

Something is amiss as it is not highlighting values that are breaching the 24 hours threshold, but I don't know what it is.

```<code>'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Set updateRange = Range("D2:D" & lastRow)
If Weekday(Date, vbMonday) Then
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 72 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
Else
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 24 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
End If
</code>```

答:
As mentioned by Kostas K. in the comments, Weekday() returns an Integer number from 1 to 7, which is always evaluated to a True boolean - MSDN Weekday!

However, if you use If Weekday(Date, vbMonday) = vbMonday most probably you will get a False if the today is Monday.

That is because the default day of the beginning of the Weekday is Sunday. And you are changing it to Monday. And from the contrary, vbMonday is always evaluated to 2 (write ?vbMonday at the immediate window)

Anyhow, it is probably a bit easier to see it than to explain it. Today it is Friday (TGIF). Thus, simply run the following code:

```<code>Public Sub TestMe()
    Debug.Print Weekday(Date) = vbFriday            'True
    Debug.Print Weekday(Date, vbMonday) = vbFriday  'False
End Sub
</code>```

Body:
I have the code below which is supposed to parse a column with dates/times and advise (by highlighting) if the value is older than 24 hours ago as of 6:30am on the current day.  If the day is Monday, it is supposed to look back 72 hours (since Saturday and Sunday are not work days) and advise if the value is older than 72 hours as of 6:30am.

Something is amiss as it is not highlighting values that are breaching the 24 hours threshold, but I don't know what it is.

'Highlight breached tickets
Dim updateRange As Range, updateCell As Range
Set updateRange = Range("D2:D" & lastRow)
If Weekday(Date, vbMonday) Then
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 72 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
Else
    For Each updateCell In updateRange
        If DateDiff("h", CDate(updateCell.Value), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(6, 30, 0)) > 24 Then
            updateCell.Interior.Color = 13311
            updateCell.Offset(0, -3).Interior.Color = 13311
        End If
    Next updateCell
End If

Body:
As mentioned by Kostas K. in the comments, Weekday() returns an Integer number from 1 to 7, which is always evaluated to a True boolean - MSDN Weekday!

However, if you use If Weekday(Date, vbMonday) = vbMonday most probably you will get a False if the today is Monday.

That is because the default day of the beginning of the Weekday is Sunday. And you are changing it to Monday. And from the contrary, vbMonday is always evaluated to 2 (write ?vbMonday at the immediate window)

Anyhow, it is probably a bit easier to see it than to explain it. Today it is Friday (TGIF). Thus, simply run the following code:

Public Sub TestMe()
    Debug.Print Weekday(Date) = vbFriday            'True
    Debug.Print Weekday(Date, vbMonday) = vbFriday  'False
End Sub


问:
build perl one-liners from short perl script and combines in to other line
Continue my previous question (but other queastion),

According to the following perl script (rename.pl)

how to build perl one-liners  line from the rename.pl script
in order to replace the: /var/tmp/rename.pl (from find command ...)
with the one-liners perl syntax?

(I dont want to use the rename.pl script ,)

```<code>   find  /  -name "$OLD_HOST"  -print0 | xargs -0 /var/tmp/rename.pl 'print "changing $_\n"; s/$OLD_HOST/host_10/g'
</code>```

rename.pl script:

```<code>  #!/usr/bin/perl

   $op = shift;
     for (@ARGV) {
      $was = $_;
      eval $op;
      die $@ if $@;
      rename($was,$_) unless $was eq $_;
    }
</code>```

答:
This one-liner will find zip files with numbers inside the filename, and print some "mv" shell commands rather than executing them immediately. You can paste this into the command line for more control later.
Maybe this will get you started.

find . -name "*.zip"  | perl -nE
  'chomp; my $f = qq($_); $f =~ /(\d+)/;
  say "mv $f " . sprintf("%03d", $1) . ".zip";'

ContentLicense: CC BY-SA 2.5

Body:
Continue my previous question (but other queastion),

According to the following perl script (rename.pl)

how to build perl one-liners  line from the rename.pl script
in order to replace the: /var/tmp/rename.pl (from find command ...)
with the one-liners perl syntax?

(I dont want to use the rename.pl script ,)

   find  /  -name "$OLD_HOST"  -print0 | xargs -0 /var/tmp/rename.pl 'print "changing $_\n"; s/$OLD_HOST/host_10/g'

rename.pl script:

  #!/usr/bin/perl

   $op = shift;
     for (@ARGV) {
      $was = $_;
      eval $op;
      die $@ if $@;
      rename($was,$_) unless $was eq $_;
    }


问:
Firebase : php push notification to multiple devics
i am using following code to send push notifications to one Android device </p>

```<code>function send_notification($message, $token){
    define( 'API_ACCESS_KEY', 'mykey');
     $msg = array
          (
            'body'  =>$message,
            'title' => 'You have a new message ',

          );
    $fields = array
            (
                'to'        => $token,
                'notification'  => $msg
            );

    $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        echo $result;
        curl_close( $ch );
}
</code>```

<p>i am successfully sending it to one device what if i want to send it to multiple device id's where do i have to loop and what format data would be . Please help </p>

答: Docs here show how to specify registration_ids for recipients of multicast messages. Replace your $fields['to'] with a $fields['registration_ids'] which will be an array of strings containing your recipients' tokens.

Body:
i am using following code to send push notifications to one Android device

function send_notification($message, $token){
    define( 'API_ACCESS_KEY', 'mykey');
     $msg = array
          (
            'body'  =>$message,
            'title' => 'You have a new message ',

          );
    $fields = array
            (
                'to'        => $token,
                'notification'  => $msg
            );

    $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        echo $result;
        curl_close( $ch );
}

i am successfully sending it to one device what if i want to send it to multiple device id's where do i have to loop and what format data would be . Please help


问:
How to run my created java program to my pc
I'm using Dialog Boxes in java. How do i apply this to my computer? just asking
I'm not very good enough. please help me.</p>

```<code>import javax.swing.*;

public class dialogs{
    public static void main(String [] args){
        JOptionPane.showMessageDialog(null,"Hello World");
    }
}
</code>```

答: You have several options depending on your IDE. I would suggest you try to either run your code directly from the IDE, which is usually possible. Or you export your code to a runnable .jar file. To run this file, navigate to the directory where you exported it to via the command promt and enter java -jar dialogs.jar (if you named the exported file differently, use a different file name).

Body:
I'm using Dialog Boxes in java. How do i apply this to my computer? just asking
I'm not very good enough. please help me.

import javax.swing.*;

public class dialogs{
    public static void main(String [] args){
        JOptionPane.showMessageDialog(null,"Hello World");
    }
}


问:
xcode: class is not key value coding-compliant
I'm currently working myself through this tutorial:
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ConnectTheUIToCode.html#//apple_ref/doc/uid/TP40015214-CH22-SW1
After creating the function for the button(at ~2/3 on the page) I tried running the code and got the Exception:

```<code>2017-12-08 11:24:31.343183+0100 FoodTracker[2159:154603] ***

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FoodTracker.ViewController 0x7fea6f406820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key setDefaultLabelText.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109d7512b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001060fcf41 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109d75079 -[NSException raise] + 9
    3   Foundation                          0x0000000105b1ba63 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x0000000106b39117 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x0000000106e2ac2d -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x0000000109d183cd -[NSArray makeObjectsPerformSelector:] + 317
    7   UIKit                               0x0000000106e295e3 -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x0000000106b403ff -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    9   UIKit                               0x0000000106b40d2b -[UIViewController loadView] + 177
    10  UIKit                               0x0000000106b4105c -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x0000000106b418b9 -[UIViewController view] + 27
    12  UIKit                               0x0000000106a0c7cf -[UIWindow addRootViewControllerViewIfPossible] + 122
    13  UIKit                               0x0000000106a0ced7 -[UIWindow _setHidden:forced:] + 294
    14  UIKit                               0x0000000106a1fe54 -[UIWindow makeKeyAndVisible] + 42
    15  UIKit                               0x00000001069928b8 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4737
    16  UIKit                               0x0000000106997aeb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1720
    17  UIKit                               0x0000000106d616f8 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 924
    18  UIKit                               0x00000001071374c8 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    19  UIKit                               0x0000000106d612f1 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 249
    20  UIKit                               0x0000000106d61b6b -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 696
    21  UIKit                               0x00000001076dfa69 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 262
    22  UIKit                               0x00000001076df922 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 444
    23  UIKit                               0x00000001073bc9c8 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 221
    24  UIKit                               0x00000001075bbb06 _performActionsWithDelayForTransitionContext + 100
    25  UIKit                               0x00000001073bc88b -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 231
    26  UIKit                               0x0000000107136b25 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    27  UIKit                               0x000000010699636a -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 523
    28  UIKit                               0x0000000106f71605 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 369
    29  FrontBoardServices                  0x000000010bc38cc0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 338
    30  FrontBoardServices                  0x000000010bc417b5 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 235
    31  libdispatch.dylib                   0x000000010ae9733d _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x000000010ae9c9f3 _dispatch_block_invoke_direct + 592
    33  FrontBoardServices                  0x000000010bc6d498 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    34  FrontBoardServices                  0x000000010bc6d14e -[FBSSerialQueue _performNext] + 464
    35  FrontBoardServices                  0x000000010bc6d6bd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    36  CoreFoundation                      0x0000000109d18101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    37  CoreFoundation                      0x0000000109db7f71 __CFRunLoopDoSource0 + 81
    38  CoreFoundation                      0x0000000109cfca19 __CFRunLoopDoSources0 + 185
    39  CoreFoundation                      0x0000000109cfbfff __CFRunLoopRun + 1279
    40  CoreFoundation                      0x0000000109cfb889 CFRunLoopRunSpecific + 409
    41  GraphicsServices                    0x000000010c5019c6 GSEventRunModal + 62
    42  UIKit                               0x00000001069995d6 UIApplicationMain + 159
    43  FoodTracker                         0x00000001057e7b67 main + 55
    44  libdyld.dylib                       0x000000010af13d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

Here is my Code:

And the connections inspector of the button:

答:
This is due to FoodTracker VC in storyboard has an outlet created but not connected.

How to resolve the issue? Follow these steps.

Open your storyboard, click on view controller below view controller scene.

Check for all outlets for ViewController.

Remove those outlets created and are not connected to ViewController.swift implementation file.

Keep me updated on the same.

Body:
I'm currently working myself through this tutorial:
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ConnectTheUIToCode.html#//apple_ref/doc/uid/TP40015214-CH22-SW1
After creating the function for the button(at ~2/3 on the page) I tried running the code and got the Exception:

2017-12-08 11:24:31.343183+0100 FoodTracker[2159:154603] ***

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FoodTracker.ViewController 0x7fea6f406820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key setDefaultLabelText.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109d7512b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001060fcf41 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109d75079 -[NSException raise] + 9
    3   Foundation                          0x0000000105b1ba63 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x0000000106b39117 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x0000000106e2ac2d -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x0000000109d183cd -[NSArray makeObjectsPerformSelector:] + 317
    7   UIKit                               0x0000000106e295e3 -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x0000000106b403ff -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    9   UIKit                               0x0000000106b40d2b -[UIViewController loadView] + 177
    10  UIKit                               0x0000000106b4105c -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x0000000106b418b9 -[UIViewController view] + 27
    12  UIKit                               0x0000000106a0c7cf -[UIWindow addRootViewControllerViewIfPossible] + 122
    13  UIKit                               0x0000000106a0ced7 -[UIWindow _setHidden:forced:] + 294
    14  UIKit                               0x0000000106a1fe54 -[UIWindow makeKeyAndVisible] + 42
    15  UIKit                               0x00000001069928b8 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4737
    16  UIKit                               0x0000000106997aeb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1720
    17  UIKit                               0x0000000106d616f8 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 924
    18  UIKit                               0x00000001071374c8 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    19  UIKit                               0x0000000106d612f1 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 249
    20  UIKit                               0x0000000106d61b6b -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 696
    21  UIKit                               0x00000001076dfa69 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 262
    22  UIKit                               0x00000001076df922 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 444
    23  UIKit                               0x00000001073bc9c8 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 221
    24  UIKit                               0x00000001075bbb06 _performActionsWithDelayForTransitionContext + 100
    25  UIKit                               0x00000001073bc88b -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 231
    26  UIKit                               0x0000000107136b25 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    27  UIKit                               0x000000010699636a -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 523
    28  UIKit                               0x0000000106f71605 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 369
    29  FrontBoardServices                  0x000000010bc38cc0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 338
    30  FrontBoardServices                  0x000000010bc417b5 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 235
    31  libdispatch.dylib                   0x000000010ae9733d _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x000000010ae9c9f3 _dispatch_block_invoke_direct + 592
    33  FrontBoardServices                  0x000000010bc6d498 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    34  FrontBoardServices                  0x000000010bc6d14e -[FBSSerialQueue _performNext] + 464
    35  FrontBoardServices                  0x000000010bc6d6bd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    36  CoreFoundation                      0x0000000109d18101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    37  CoreFoundation                      0x0000000109db7f71 __CFRunLoopDoSource0 + 81
    38  CoreFoundation                      0x0000000109cfca19 __CFRunLoopDoSources0 + 185
    39  CoreFoundation                      0x0000000109cfbfff __CFRunLoopRun + 1279
    40  CoreFoundation                      0x0000000109cfb889 CFRunLoopRunSpecific + 409
    41  GraphicsServices                    0x000000010c5019c6 GSEventRunModal + 62
    42  UIKit                               0x00000001069995d6 UIApplicationMain + 159
    43  FoodTracker                         0x00000001057e7b67 main + 55
    44  libdyld.dylib                       0x000000010af13d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Here is my Code:

And the connections inspector of the button:


问:
Rewriting pre-written code to implement class. (Python)
Few days into Python, I wrote this a day ago to get the gist of Python Grammar. While it might not be efficient it works as i intended.

```<code>def LongerString():
    if len(String1) == len(String2):
        return len(String1)
    elif len(String1) > len(String2):
        return len(String1)
    elif len(String1) < len(String2):
        return len(String2)

def ShorterString():
    if len(String1) == len(String2):
        return len(String1)
    elif not len(String1) > len(String2):
        return len(String1)
    elif not len(String1) < len(String2):
        return len(String2)

#String1 and 2 from userinput

String1 = input('Input String1\n')
String2 = input('Input String2\n')

#After finishing comparing, evaluates in %

score = 0
for i in range(ShorterString()):
    if String1[i] == String2[i]:
        score += 1
print(score, "/", LongerString(), "Match", float(score / LongerString()) * 100, "%")
</code>```

As my progress goes, decided to re-write this code under single class to
get better understanding of how class is used. But looks like I'm missing something. Below is my little attempt.

```<code>class CompareString:

    def LongerString():
        if len(String1) == len(String2):
            return len(String1)
        elif len(String1) > len(String2):
            return len(String1)
        elif len(String1) < len(String2):
            return len(String2)

    def ShorterString():
        if len(String1) == len(String2):
            return len(String1)
        elif not len(String1) > len(String2):
            return len(String1)
        elif not len(String1) < len(String2):
            return len(String2)

    def Result():
        for i in range(ShorterString()):
            if String1[i] == String2[i]:
                score += 1
        print(score, "/", LongerString(), "Match", float(score / LongerString()) * 100, "%")

String1 = input('Input String1\n')
String2 = input('Input String2\n')
CompareString.Result()
</code>```

When trying to run latter code i get an error message "line 20, in Result
    for i in range(ShorterString()):
NameError: name 'ShorterString' is not defined"

答:
For the immediate problem, you need to call your methods via self - ie self.LongerString() - and they need to accept self as the first argument.

But this isn't really how you use classes. You should write an __init__ method that takes the two strings and stores them as instance attributes, then refer to those throughout.

(Also note, you should use PEP8 style for your variable names.)

```<code>class CompareString:

    def __init__(self, string1, string2):
        self.string1 = string1
        self.string2 = string2

    def longer_string(self):
        if len(self.string1) == len(self.string2):
            ...

    def result(self):
         ... call self.longer_string() etc ...

compare = CompareString(string1, string2)
print compare.result()
</code>```

(Also also note, your longer_string method could just be return max(len(self.string1), len(self.string2)), and your shorter_string method similarly.)

(Also also also note, your result method should not iterate over a range, but just over zip(self.string1, self.string2), so you don't even need either of those other methods.)

Body:
Few days into Python, I wrote this a day ago to get the gist of Python Grammar. While it might not be efficient it works as i intended.

def LongerString():
    if len(String1) == len(String2):
        return len(String1)
    elif len(String1) > len(String2):
        return len(String1)
    elif len(String1) < len(String2):
        return len(String2)

def ShorterString():
    if len(String1) == len(String2):
        return len(String1)
    elif not len(String1) > len(String2):
        return len(String1)
    elif not len(String1) < len(String2):
        return len(String2)

#String1 and 2 from userinput

String1 = input('Input String1\n')
String2 = input('Input String2\n')

#After finishing comparing, evaluates in %

score = 0
for i in range(ShorterString()):
    if String1[i] == String2[i]:
        score += 1
print(score, "/", LongerString(), "Match", float(score / LongerString()) * 100, "%")

As my progress goes, decided to re-write this code under single class to
get better understanding of how class is used. But looks like I'm missing something. Below is my little attempt.

class CompareString:

    def LongerString():
        if len(String1) == len(String2):
            return len(String1)
        elif len(String1) > len(String2):
            return len(String1)
        elif len(String1) < len(String2):
            return len(String2)

    def ShorterString():
        if len(String1) == len(String2):
            return len(String1)
        elif not len(String1) > len(String2):
            return len(String1)
        elif not len(String1) < len(String2):
            return len(String2)

    def Result():
        for i in range(ShorterString()):
            if String1[i] == String2[i]:
                score += 1
        print(score, "/", LongerString(), "Match", float(score / LongerString()) * 100, "%")

String1 = input('Input String1\n')
String2 = input('Input String2\n')
CompareString.Result()

When trying to run latter code i get an error message "line 20, in Result
    for i in range(ShorterString()):
NameError: name 'ShorterString' is not defined"

Body:
For the immediate problem, you need to call your methods via self - ie self.LongerString() - and they need to accept self as the first argument.

But this isn't really how you use classes. You should write an __init__ method that takes the two strings and stores them as instance attributes, then refer to those throughout.

(Also note, you should use PEP8 style for your variable names.)

class CompareString:

    def __init__(self, string1, string2):
        self.string1 = string1
        self.string2 = string2

    def longer_string(self):
        if len(self.string1) == len(self.string2):
            ...

    def result(self):
         ... call self.longer_string() etc ...

compare = CompareString(string1, string2)
print compare.result()

(Also also note, your longer_string method could just be return max(len(self.string1), len(self.string2)), and your shorter_string method similarly.)

(Also also also note, your result method should not iterate over a range, but just over zip(self.string1, self.string2), so you don't even need either of those other methods.)


问:
Using xpath containing whitespace
```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));
</code>```

<p>how to use normalize-space in my case? "situacao" has white spaces </p>

答:
Try using single quotes in your xpath expression. Here I suppose that suticao contains the string "Example Example":</p>

```<code>List <WebElement> tableSituacao
= driver.findElements(
      By.xpath("//*[@id='tabela']/tbody/tr/td[5][contains(text(),'" + suticao + "')]");
</code>```

Title: Using xpath containing whitespace

Body:
List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));

how to use normalize-space in my case? "situacao" has white spaces

Body:
Try using single quotes in your xpath expression. Here I suppose that suticao contains the string "Example Example":

List <WebElement> tableSituacao
= driver.findElements(
      By.xpath("//*[@id='tabela']/tbody/tr/td[5][contains(text(),'" + suticao + "')]");


问:
system call variable splitting because of space in value in php
I am calling two system variables in a file and when fetching the variables in the page, the value is splitting into two.

Here is my code

```<code>system('php '.$app_name.'/send_survey_mail.php '.$name ." ". $name_person."  ".$location.' > mail_text.txt', $output);
</code>```

If am passing values like name "John emmanual" and location "United States", it's splitting into two because of space. Can any one please help solve this issue?

答:
hey use the double quotes in command:</p>

```<code>system('php '.$app_name.'/send_survey_mail.php "'.$name.'" "'. $name_person.'"  "'.$location.'" > mail_text.txt', $output);
</code>```

Body:
I am calling two system variables in a file and when fetching the variables in the page, the value is splitting into two.

Here is my code

system('php '.$app_name.'/send_survey_mail.php '.$name ." ". $name_person."  ".$location.' > mail_text.txt', $output);

If am passing values like name "John emmanual" and location "United States", it's splitting into two because of space. Can any one please help solve this issue?

Body:
hey use the double quotes in command:

system('php '.$app_name.'/send_survey_mail.php "'.$name.'" "'. $name_person.'"  "'.$location.'" > mail_text.txt', $output);


问:
Finding the different elements between two ArrayLists in Java
How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

答:
It depends on what do you want to check.

If you want to get all the unique elements for both lists (i.e. sum of all elements that are unique for the first list and all elements that unique for the second list) also known as symmetric difference you can use as mentioned above disjunction method from Apache Commons Collections 4.0:

```<code>CollectionUtils.disjunction(a, b);
</code>```

If you want to get all unique elements only from one list (i.e. elements that exist only in one list, but don't exist in the other) also known as relative complement you can subtract from this list the other one using subtract method from Apache Commons Collections 4.0:

```<code>CollectionUtils.subtract(a, b); //gives all unique elements of a that don't exist in b
</code>```

Body:
It depends on what do you want to check.

If you want to get all the unique elements for both lists (i.e. sum of all elements that are unique for the first list and all elements that unique for the second list) also known as symmetric difference you can use as mentioned above disjunction method from Apache Commons Collections 4.0:

CollectionUtils.disjunction(a, b);

If you want to get all unique elements only from one list (i.e. elements that exist only in one list, but don't exist in the other) also known as relative complement you can subtract from this list the other one using subtract method from Apache Commons Collections 4.0:

CollectionUtils.subtract(a, b); //gives all unique elements of a that don't exist in b


问:
Using and interpreting output from gvlma
I want to test whether all assumptions for my linear regression model hold. I did this manually and it seems to be fine. However, I want to double check with the function gvlma. The output I get is:

```<code> gvlma(x = m_lag)

                Value p-value                   Decision
 Global Stat        82.475 0.00000 Assumptions NOT satisfied!
 Skewness           72.378 0.00000 Assumptions NOT satisfied!
 Kurtosis            1.040 0.30778    Assumptions acceptable.
 Link Function       6.029 0.01407 Assumptions NOT satisfied!
 Heteroscedasticity  3.027 0.08187    Assumptions acceptable.
</code>```

My question is:

How do I interpret Global Stat

Since the assumption is violated, what can I do about it now? (Same with the other 2 assumptions which were not accepted)

答:
Global Stat- Are the relationships between your X predictors and Y roughly linear?. Rejection of the null (p < .05) indicates a non-linear relationship between one or more of your X’s and Y

Skewness - Is your distribution skewed positively or negatively, necessitating a transformation to meet the assumption of normality? Rejection of the null (p < .05) indicates that you should likely transform your data.

Kurtosis- Is your distribution kurtotic (highly peaked or very shallowly peaked), necessitating a transformation to meet the assumption of normality? Rejection of the null (p < .05) indicates that you should likely transform your data.

Link Function- Is your dependent variable truly continuous, or categorical? Rejection of the null (p < .05) indicates that you should use an alternative form of the generalized linear model (e.g. logistic or binomial regression).

Heteroscedasticity- Is the variance of your model residuals constant across the range of X (assumption of homoscedastiity)? Rejection of the null (p < .05) indicates that your residuals are heteroscedastic, and thus non-constant across the range of X. Your model is better/worse at predicting for certain ranges of your X scales.

Body:
I want to test whether all assumptions for my linear regression model hold. I did this manually and it seems to be fine. However, I want to double check with the function gvlma. The output I get is:

 gvlma(x = m_lag)

                Value p-value                   Decision
 Global Stat        82.475 0.00000 Assumptions NOT satisfied!
 Skewness           72.378 0.00000 Assumptions NOT satisfied!
 Kurtosis            1.040 0.30778    Assumptions acceptable.
 Link Function       6.029 0.01407 Assumptions NOT satisfied!
 Heteroscedasticity  3.027 0.08187    Assumptions acceptable.

My question is:

How do I interpret Global Stat

Since the assumption is violated, what can I do about it now? (Same with the other 2 assumptions which were not accepted)


问:
Calculate the duration between now and the next midnight using Chrono
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

```<code>extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}
</code>```

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

答:
One way is to calculate the seconds missing to next midnight, keeping in mind that time::Tm accounts for both Daylight Saving Time and time zones:

tm_utcoff: i32

Identifies the time zone that was used to compute this broken-down time value, including any adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example, for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.

```<code>extern crate time;
use std::time::Duration;

fn duration_until_next_midnight() -> Duration {
    let tnow = time::now();

    Duration::new(
        (86400 - tnow.to_timespec().sec % 86400 -
        i64::from(tnow.tm_utcoff)) as u64,
        0,
    )
}
</code>```

If you want nanoseconds precision you have to do some more maths ...

Body:
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

Body:
One way is to calculate the seconds missing to next midnight, keeping in mind that time::Tm accounts for both Daylight Saving Time and time zones:

tm_utcoff: i32

Identifies the time zone that was used to compute this broken-down time value, including any adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example, for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.

extern crate time;
use std::time::Duration;

fn duration_until_next_midnight() -> Duration {
    let tnow = time::now();

    Duration::new(
        (86400 - tnow.to_timespec().sec % 86400 -
        i64::from(tnow.tm_utcoff)) as u64,
        0,
    )
}

If you want nanoseconds precision you have to do some more maths ...


问:
Jython support in editors?
I've recently started writing some performance tests in The Grinder 3, and one of the first things I noticed is that PyCheckMate doesn't work because it can't find some of the imports. Which editor(s) provide the best support for Jython?</p>

答:
As a long-time fan of the Eclipse IDE, I've used the Pydev plugin when working with Python and Jython projects.

You get code completion, syntax highlighting, refactoring, outline view, debugging tools, and all the other features you'd expect out of a top-notch editor.

OwnerDisplayName: Hank Gay

Title: Jython support in editors?

OwnerDisplayName: David Crow


问:
Code contracts - Assume vs Requires
What's the diference between these two statements ?</p>

```<code>Contract.Requires(string.IsNullOrWhiteSpace(userName));

Contract.Assume(string.IsNullOrWhiteSpace(userName));
</code>```

答:
Imagine you have a method like this:

```<code>bool ContainsAnX(string s)
{
    return s.Contains("X");
}
</code>```

Now, this method will always fail if you pass null to it, so you want to ensure this never happens. This is what Contract.Requires is for. It sets a precondition for the method, which must be true in order for the method to run correctly. In  this case we would have:

```<code>bool ContainsAnX(string s)
{
    Contract.Requires(s != null);

    return s.Contains("X");
}
</code>```

(Note: Requires and Ensures must always be at the start of a method, as they are information about the method as a whole.  Assume is used in the code itself, as it is information about that point in the code.)

Now, in your code that calls the method "ContainsAnX", you must ensure that the string is not null. Your method might look like this:

```<code>void DoSomething()
{
    var example = "hello world";

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}
</code>```

This will work fine, and the static checker can prove that example is not null.

However, you might be calling into external libraries, which don't have any information about the values they return (i.e. they don't use Code Contracts).  Let's change the example:

```<code>void DoSomething()
{
    var example = OtherLibrary.FetchString();

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}
</code>```

If the OtherLibrary doesn't use Code Contracts, the static checker will complain that example might be null.

Maybe their documentation for the library says that the method will never return null (or should never!). In this case, we know more than the static checker does, so we can tell it to Assume that the variable will never be null:

```<code>void DoSomething()
{
    var example = OtherLibrary.FetchString();

    Contract.Assume(example != null);

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}
</code>```

Now this will be okay with the static checker. If you have runtime contracts enabled, the Assume will also be checked at run time.

Another case where you might need Assume is when your preconditions are very complex and the static checker is having a hard time proving them. In this case you can give it a bit of a nudge to help it along :)

In terms of runtime behavior there won't be much difference between using Assume and Requires. However, results with the static checker will differ greatly. The meaning of each is different as well, in terms of who is responsible for the error in case of failure:

Requires means that the code which calls this method must ensure the condition holds.

Assume means that this method is making an assumption which should always hold true.

Title: Code contracts - Assume vs Requires

Body:
What's the diference between these two statements ?

Contract.Requires(string.IsNullOrWhiteSpace(userName));

Contract.Assume(string.IsNullOrWhiteSpace(userName));

Body:
Imagine you have a method like this:

bool ContainsAnX(string s)
{
    return s.Contains("X");
}

Now, this method will always fail if you pass null to it, so you want to ensure this never happens. This is what Contract.Requires is for. It sets a precondition for the method, which must be true in order for the method to run correctly. In  this case we would have:

bool ContainsAnX(string s)
{
    Contract.Requires(s != null);

    return s.Contains("X");
}

(Note: Requires and Ensures must always be at the start of a method, as they are information about the method as a whole.  Assume is used in the code itself, as it is information about that point in the code.)

Now, in your code that calls the method "ContainsAnX", you must ensure that the string is not null. Your method might look like this:

void DoSomething()
{
    var example = "hello world";

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}

This will work fine, and the static checker can prove that example is not null.

However, you might be calling into external libraries, which don't have any information about the values they return (i.e. they don't use Code Contracts).  Let's change the example:

void DoSomething()
{
    var example = OtherLibrary.FetchString();

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}

If the OtherLibrary doesn't use Code Contracts, the static checker will complain that example might be null.

Maybe their documentation for the library says that the method will never return null (or should never!). In this case, we know more than the static checker does, so we can tell it to Assume that the variable will never be null:

void DoSomething()
{
    var example = OtherLibrary.FetchString();

    Contract.Assume(example != null);

    if (ContainsAnX(example))
        Console.WriteLine("The string contains an 'X'.");
    else
        Console.WriteLine("The string does not contain an 'X'.");
}

Now this will be okay with the static checker. If you have runtime contracts enabled, the Assume will also be checked at run time.

Another case where you might need Assume is when your preconditions are very complex and the static checker is having a hard time proving them. In this case you can give it a bit of a nudge to help it along :)

In terms of runtime behavior there won't be much difference between using Assume and Requires. However, results with the static checker will differ greatly. The meaning of each is different as well, in terms of who is responsible for the error in case of failure:

Requires means that the code which calls this method must ensure the condition holds.

Assume means that this method is making an assumption which should always hold true.


问:
Pandas resampling: how to generate offset rules string from TimeDelta
Is there a way to generate the offset rule string accepted by DataFrame.resample (e.g. 'T', '3W', '2D', etc) starting from a TimeDelta or another object representing a time frequency?

I know that DataFrame.resample can accept a TimeDelta, but I like to know how to generate the string programmatically without having to invent my own function.

```<code>td = pd.TimeDelta('3min')
str(td)
</code>```

Output

```<code>'0 days 00:03:00'
</code>```

Actually I would like to obtain an offset rule string: e.g. '3T'

答:
In case someone else needs to write their own function like myself, here is the code:</p>

```<code>def timedelta_to_string(timedelta):
    """
    Converts a pandas.Timedelta to a string rappresentation
    compatible with pandas.Timedelta constructor format
    """
    c = timedelta.components
    format = ''
    if c.days != 0:
        format += '%dD' % c.days
    if c.hours > 0:
        format += '%dh' % c.hours
    if c.minutes > 0:
        format += '%dm' % c.minutes
    if c.seconds > 0:
        format += '%ds' % c.seconds
    if c.milliseconds > 0:
        format += '%dms' % c.milliseconds
    if c.microseconds > 0:
        format += '%dus' % c.microseconds
    if c.nanoseconds > 0:
        format += '%dns' % c.nanoseconds
return format
</code>```

Body:
Is there a way to generate the offset rule string accepted by DataFrame.resample (e.g. 'T', '3W', '2D', etc) starting from a TimeDelta or another object representing a time frequency?

I know that DataFrame.resample can accept a TimeDelta, but I like to know how to generate the string programmatically without having to invent my own function.

td = pd.TimeDelta('3min')
str(td)

Output

'0 days 00:03:00'

Actually I would like to obtain an offset rule string: e.g. '3T'

Body:
In case someone else needs to write their own function like myself, here is the code:

def timedelta_to_string(timedelta):
    """
    Converts a pandas.Timedelta to a string rappresentation
    compatible with pandas.Timedelta constructor format
    """
    c = timedelta.components
    format = ''
    if c.days != 0:
        format += '%dD' % c.days
    if c.hours > 0:
        format += '%dh' % c.hours
    if c.minutes > 0:
        format += '%dm' % c.minutes
    if c.seconds > 0:
        format += '%ds' % c.seconds
    if c.milliseconds > 0:
        format += '%dms' % c.milliseconds
    if c.microseconds > 0:
        format += '%dus' % c.microseconds
    if c.nanoseconds > 0:
        format += '%dns' % c.nanoseconds
return format


问:
Render component in Drawer with Material-ui Lists
This feels like it should be self-explanatory in the Docs, but they abstract out a key part of the List code to another file and don't show it. So, I'm left asking you fine folks.

I'm looking to do something pretty simple: Use a List-based sidebar with Material-ui (beta-version) to render a component in a Drawer. I have the list setup, but I can't figure out how to make the ListItems link to the components and perform the render. Here's my code:

```<code>class DashboardScreen extends Component {
constructor(props) {
    super(props);
}

render() {
    return (
        <div className={this.props.classes.container}>
            <Appbar pagetitle="Dashboard" />
            <div className={this.props.classes.appFrame}>
                <Drawer
                    type="permanent"
                    classes={{
                        paper: this.props.classes.drawerPaper,
                    }}
                    anchor="left">
                    <div className={this.props.classes.drawerHeader} />
                    <List>
                        <ListItem button>
                            <ListItemIcon>
                                <AssessmentIcon />
                            </ListItemIcon>
                            <ListItemText primary="Analytics"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <ImportContactsIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Investigation"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <AssignmentIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Survey"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <AssignmentTurnedInIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Response"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <SettingsIcon />
                            </ListItemIcon>
                            <ListItemText primary="Settings"/>
                        </ListItem>
                    </List>
                </Drawer>
                <main className={this.props.classes.content}>
                    Testing Stuff!
                </main>
            </div>
        </div>
    )
}
}
</code>```

What I'm rendering is just another separate component called "Analytics". There's nothing special about it. How do I get the first ListItem, with text = "Analytics", render said component <Analytics />?

答:
Did you try to simply change ListItemText with your custom component?</p>

```<code><ListItem button>
    <ListItemIcon>
          <AssessmentIcon />
    </ListItemIcon>
    <Analytics />
</ListItem>
</code>```

Body:
This feels like it should be self-explanatory in the Docs, but they abstract out a key part of the List code to another file and don't show it. So, I'm left asking you fine folks.

I'm looking to do something pretty simple: Use a List-based sidebar with Material-ui (beta-version) to render a component in a Drawer. I have the list setup, but I can't figure out how to make the ListItems link to the components and perform the render. Here's my code:

class DashboardScreen extends Component {
constructor(props) {
    super(props);
}

render() {
    return (

            <Appbar pagetitle="Dashboard" />

                <Drawer
                    type="permanent"
                    classes={{
                        paper: this.props.classes.drawerPaper,
                    }}
                    anchor="left">

                    <List>
                        <ListItem button>
                            <ListItemIcon>
                                <AssessmentIcon />
                            </ListItemIcon>
                            <ListItemText primary="Analytics"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <ImportContactsIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Investigation"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <AssignmentIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Survey"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <AssignmentTurnedInIcon />
                            </ListItemIcon>
                            <ListItemText primary="Create Response"/>
                        </ListItem>
                        <ListItem button>
                            <ListItemIcon>
                                <SettingsIcon />
                            </ListItemIcon>
                            <ListItemText primary="Settings"/>
                        </ListItem>
                    </List>
                </Drawer>

                    Testing Stuff!

    )
}
}

What I'm rendering is just another separate component called "Analytics". There's nothing special about it. How do I get the first ListItem, with text = "Analytics", render said component <Analytics />?

Body:
Did you try to simply change ListItemText with your custom component?

<ListItem button>
    <ListItemIcon>
          <AssessmentIcon />
    </ListItemIcon>
    <Analytics />
</ListItem>


问:
Java - spiral move from 2-D Array inside out
I am trying to realise an algorithm where I can move in an array of unknown size counterclockwise in that order:

16 15  14  13
5   4   3   12
6   1   2   11
7   8   9   10

Any ideas?

答:
Looks like you need to:

set n to 1 and face right

Move n steps and turn left

Move n steps and turn left

Increase n, repeat from step 2


问:
Expand occurrences into single events
Are there any options to expand recurring events into single events and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves?

Currently the Outlook Calendar REST API returns occurrences with their SeriesMaster, but we need to merge and expand them programmatically.

答:
This is exactly what GET /me/calendarview does. That expands recurring meetings and returns any instances that fall within the start/end parameters of the view. If you just do GET /me/events then you only get the series master.

If you want to expand from a series master you can always do GET /me/events/{id-of-series-master}/instances?startDateTime=XXXX&endDateTime=XXXX.

Note with both cases you have to specify a time window, so there is no way to say "just give me ALL the instances". This is because there is the possibility to have recurring events with no end date, so there is no "all" :).

Title: Expand occurrences into single events


问:
Laravel access directly to json array in blade without using foreach statement
in this result:

```<code>LengthAwarePaginator {#251 ▼
  #total: 2
  #lastPage: 1
  #items: Collection {#246 ▼
    #items: array:2 [▼
      0 => ProductCategories {#247 ▼
        ...
        #attributes: array:6 [▼
          "id" => 1
          "category_name" => "test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        #original: array:6 [▼
          "id" => 1
          "category_name" => "test test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        ...
      }
      1 => ProductCategories {#248 ▶}
    ]
  }
</code>```

which i get from this query:

```<code>$categories = ProductCategories::paginate(10);
dd($categories);
</code>```

i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:

```<code>{{$categories->images->thumbnail}}
</code>```

but i get Undefined property error and i can't show that

答:
If you want to make it right, you should keep image related data in a separate table and use a relationship between category and image:

```<code>public function images()
{
    return $this->hasMany(Image::class);
}
</code>```

But since you're keeping images data as JSON string, the first thing you want to do is to cast it to array. Add this to the model:

```<code>protected $casts = [
    'images' => 'array',
];
</code>```

Then in Blade view:

```<code>@foreach ($categories as $category)
    {{ $category->images['thumbnail'] }}
@endforeach
</code>```

Body:
in this result:

LengthAwarePaginator {#251 ▼
  #total: 2
  #lastPage: 1
  #items: Collection {#246 ▼
    #items: array:2 [▼
      0 => ProductCategories {#247 ▼
        ...
        #attributes: array:6 [▼
          "id" => 1
          "category_name" => "test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        #original: array:6 [▼
          "id" => 1
          "category_name" => "test test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        ...
      }
      1 => ProductCategories {#248 ▶}
    ]
  }

which i get from this query:

$categories = ProductCategories::paginate(10);
dd($categories);

i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:

{{$categories->images->thumbnail}}

but i get Undefined property error and i can't show that

Body:
If you want to make it right, you should keep image related data in a separate table and use a relationship between category and image:

public function images()
{
    return $this->hasMany(Image::class);
}

But since you're keeping images data as JSON string, the first thing you want to do is to cast it to array. Add this to the model:

protected $casts = [
    'images' => 'array',
];

Then in Blade view:

@foreach ($categories as $category)
    {{ $category->images['thumbnail'] }}
@endforeach


问:
php xml schema formatting
I have a php page what post's a xml to Heartinternet API and after a long time I have got it to work but now I cant find away to only pull only one part out of the replyed XML

```<code>$some_xml = '<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:package="http://www.heartinternet.co.uk/whapi/package-2.2">
  <command>
    <info>
      <package:info>
        <package:id>171371a16973b1bf</package:id>
      </package:info>
    </info>
    <extension>
      <ext-package:preAuthenticate xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2"/>
    </extension>
    <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
  </command>
</epp>';
</code>```

This is the code what is posted to the API. Full code can been seen here.

This is what I get back and can't figure out how to pull one line from the reply.

```<code><?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>
</code>```

The one line I need to show is ext-package:redirectURL.

If anyone could help me or point me in the right direction to find how to sort this I would be grateful!

答:
```<code><?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>
</code>```

that is what i get sent back from the API its not in my test page at all

Full page source

if i add

```<code>$xml = simplexml_load_string($returned_xml);
$xml->registerXPathNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$redirectUrl = $xml->xpath('/u:epp/u:response/u:resData/ext-package:redirectURL');
echo $redirectUrl[0];
</code>```

to the page i just get

XML Parsing Error: no element found

Location: https://custom-hosting.co.uk/

Line Number 1, Column 1:

Title: php xml schema formatting

Body:
I have a php page what post's a xml to Heartinternet API and after a long time I have got it to work but now I cant find away to only pull only one part out of the replyed XML

$some_xml = '<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:package="http://www.heartinternet.co.uk/whapi/package-2.2">
  <command>
    <info>
      <package:info>
        <package:id>171371a16973b1bf</package:id>
      </package:info>
    </info>
    <extension>
      <ext-package:preAuthenticate xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2"/>
    </extension>
    <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
  </command>
</epp>';

This is the code what is posted to the API. Full code can been seen here.

This is what I get back and can't figure out how to pull one line from the reply.

<?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>

The one line I need to show is ext-package:redirectURL.

If anyone could help me or point me in the right direction to find how to sort this I would be grateful!

Body:
<?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>

that is what i get sent back from the API its not in my test page at all

Full page source

if i add

$xml = simplexml_load_string($returned_xml);
$xml->registerXPathNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$redirectUrl = $xml->xpath('/u:epp/u:response/u:resData/ext-package:redirectURL');
echo $redirectUrl[0];

to the page i just get

XML Parsing Error: no element found

Location: https://custom-hosting.co.uk/

Line Number 1, Column 1: