问:
How to create XML file with top 50 records from another XML file in PHP
I have an XML file and has 300 elements. I just want to pull 10 latest records from it and create another XML file.

I will really appreciate if you can just give me some ideas about it?

PHP

```<code>$file = '/directory/xmlfile.xml';
if(!$xml = simplexml_load_file($file)){
    exit('Failed to open '.$file);
} else{
    print_r($xml);
    // I want to do some logic here to retrieve top 10 records from file and then create another xml file with 10 records
}
</code>```

XML Sample Data

```<code><data>
    <total>212</total>
    <start>0</start>
    <count>212</count>
    <data>
        <item0>
            <id>123</id>
            <title>abc-test1</title>
            <clientContact>
                <id>111</id>
                <firstName>abc</firstName>
                <lastName>xyz</lastName>
                <email>abc@xyz.ca</email>
            </clientContact>
            <isOpen>1</isOpen>
            <isPublic>1</isPublic>
            <isJobcastPublished>1</isJobcastPublished>
            <owner>
                <id>222</id>
                <firstName>testname</firstName>
                <lastName>testlastname</lastName>
                <address>
                    <address1>test address,</address1>
                    <address2>test</address2>
                    <city>City</city>
                    <state>state</state>
                    <zip>2222</zip>
                    <countryID>22</countryID>
                    <countryName>Country</countryName>
                    <countryCode>ABC</countryCode>
                </address>
                <email>test@test.com</email>
                <customText1>test123</customText1>
                <customText2>testxyz</customText2>
            </owner>
            <publicDescription>
                <p>test info</p>
            </publicDescription>
            <status>test</status>
            <dateLastModified>22222</dateLastModified>
            <customText4>test1</customText4>
            <customText10>test123</customText10>
            <customText11>test</customText11>
            <customText16>rtest</customText16>
            <_score>123</_score>
        </item0>
        <item1>
        ...
        </item1>
        ...
    </data>
</data>
</code>```

答:
Consider XSLT, the special-purpose language designed to transform/manipulate XML to various end uses like extracting top ten <item*> tags. No need of foreach or if logic. PHP maintains an XSLT processor that can be enabled in .ini file (php-xsl).

Specifically, XSLT runs the Identity Transform to copy document as is then writes a blank template for item nodes with position over 10. XML was a bit difficult due to same parent/child <data> tags.

XSLT (save as .xsl file which is a well-formed xml)

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[substring(name(),1,4)='item' and position() > 10]"/>

</xsl:stylesheet>
</code>```

PHP

```<code>$file = '/directory/xmlfile.xml';

if(!$xml = simplexml_load_file($file)) {
    exit('Failed to open '.$file);
} else {
    // Load XSLT
    $xsl = new DOMDocument;
    $xsl->load('/path/to/xsl_script.xsl');

    // Configure transformer
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl);

    // Transform XML source
    $newXML = new DOMDocument;
    $newXML = $proc->transformToXML($xml);

    // Echo new XML tree
    echo $newXML;

    // Save output to file
    $xmlfile = '/path/to/output.xml';
    file_put_contents($xmlfile, $newXML);
}
</code>```

Body:
I have an XML file and has 300 elements. I just want to pull 10 latest records from it and create another XML file.

I will really appreciate if you can just give me some ideas about it?

PHP

$file = '/directory/xmlfile.xml';
if(!$xml = simplexml_load_file($file)){
    exit('Failed to open '.$file);
} else{
    print_r($xml);
    // I want to do some logic here to retrieve top 10 records from file and then create another xml file with 10 records
}

XML Sample Data

<data>
    <total>212</total>
    <start>0</start>
    <count>212</count>
    <data>
        <item0>
            <id>123</id>
            <title>abc-test1</title>
            <clientContact>
                <id>111</id>
                <firstName>abc</firstName>
                <lastName>xyz</lastName>
                <email>abc@xyz.ca</email>
            </clientContact>
            <isOpen>1</isOpen>
            <isPublic>1</isPublic>
            <isJobcastPublished>1</isJobcastPublished>
            <owner>
                <id>222</id>
                <firstName>testname</firstName>
                <lastName>testlastname</lastName>
                <address>
                    <address1>test address,</address1>
                    <address2>test</address2>
                    <city>City</city>
                    <state>state</state>
                    <zip>2222</zip>
                    <countryID>22</countryID>
                    <countryName>Country</countryName>
                    <countryCode>ABC</countryCode>
                </address>
                <email>test@test.com</email>
                <customText1>test123</customText1>
                <customText2>testxyz</customText2>
            </owner>
            <publicDescription>

test info

            </publicDescription>
            <status>test</status>
            <dateLastModified>22222</dateLastModified>
            <customText4>test1</customText4>
            <customText10>test123</customText10>
            <customText11>test</customText11>
            <customText16>rtest</customText16>
            <_score>123</_score>
        </item0>
        <item1>
        ...
        </item1>
        ...
    </data>
</data>

Body:
Consider XSLT, the special-purpose language designed to transform/manipulate XML to various end uses like extracting top ten <item*> tags. No need of foreach or if logic. PHP maintains an XSLT processor that can be enabled in .ini file (php-xsl).

Specifically, XSLT runs the Identity Transform to copy document as is then writes a blank template for item nodes with position over 10. XML was a bit difficult due to same parent/child <data> tags.

XSLT (save as .xsl file which is a well-formed xml)

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[substring(name(),1,4)='item' and position() &gt; 10]"/>

</xsl:stylesheet>

PHP

$file = '/directory/xmlfile.xml';

if(!$xml = simplexml_load_file($file)) {
    exit('Failed to open '.$file);
} else {
    // Load XSLT
    $xsl = new DOMDocument;
    $xsl->load('/path/to/xsl_script.xsl');

    // Configure transformer
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl);

    // Transform XML source
    $newXML = new DOMDocument;
    $newXML = $proc->transformToXML($xml);

    // Echo new XML tree
    echo $newXML;

    // Save output to file
    $xmlfile = '/path/to/output.xml';
    file_put_contents($xmlfile, $newXML);
}


来源: stackexchange

问:
What do you recommend using for graphically visualizing a WSDL?
I'm looking for a good solution for graphically viewing a SOAP-based web service and possibly interacting with it (for testing purposes). Online (browser-based) solutions would be interesting too.</p>

答:
I've had success with a combination of the Elipse WTP WSDL Editor and SoapUI.

Eclipse WTP WSDL Editor -http://wiki.eclipse.org/index.php/Introduction_to_the_WSDL_Editor

SoapUI - http://www.soapui.org/

OwnerDisplayName: Abdullah Jibaly

ContentLicense: CC BY-SA 2.5


问:
How to create the screen in optimized way?
Hello everybody I am trying to create a screen (to see the image click here)
I have set it's backround image also created required list components which are click able by extending Field class. Now my problem is I am not able to set that rounded white color as backround of the list. Please help me. And also because I am new to the blackberry please also tell me the optimized way to create this screen.</p>

答:
i think like this

1) header bar - create manager and embed 2 buttons and 1 label in it
2) bottom bar - create a global class that contains the buttons and define a method that responds to the click event of these buttons
  call that class in this main screen
3) for middle part use a list field which is scrollable


问:
ASP.NET Mvc Button in jumbotron can't be moved up
I've tried margin-bottom, padding, top:5px; but nothing seems to be moving it.

Find out more! »

css contains too many stuff for me to find the css I need to change. Is there anyway I can change it from my Index view?

答: open developer tools from your browser, "Press F12 in case of Chrome", Click on the "Select an element from page to view it" as marked in picture, then in right corner as marked RED, change CSS code and view its effect, after successful change, copy that code and paste in your custom css file, and add it at the last of included CSS files, as last added CSS file has the highest priority in order of execution

ContentLicense: CC BY-SA 3.0


问:
RelativeLayout not respecting parent bounds
I'm having problems while rendering a RelativeLayout at runtime inside a Canvas. I know this is Xamarin.Android, but it's actually pretty identical to "original" Android, so I'll accept every solution that works.

I have this xml that renders correctly inside my view (scroll down for the  "score_progress_bar" xml):

```<code><LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content">
            <include
                layout="@layout/score_progress_bar"
                android:layout_width="50dp"
                android:layout_height="50dp" />
</LinearLayout>
</code>```

And here is the correct result:

If I try to load the same thing via a Canvas, I'm not getting the same result. Here's the code where I try to load the same control at runtime:

```<code>var id = Application.Context.Resources.GetIdentifier("score_progress_bar", "layout", Application.Context.PackageName);

var ll = new LinearLayout(Application.Context);
ll.SetBackgroundColor(AndroidColor.Red);
ll.Measure(50, 50);
ll.Layout(0, 0, 50, 50);

var li = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService);
var v = (RelativeLayout)li.Inflate(id, null, true);
v.LayoutParameters = new RelativeLayout.LayoutParams(50, 50);
v.Measure(50, 50);
v.Layout(0, 0, 50, 50);

ll.AddView(v);
ll.Draw(Native);
</code>```

Just to be clear, "Native" is my Canvas object and I'm setting a red background color to the LinearLayout so I can see where this is loaded in my view.

The result I'm getting is weird, the LinearLayout is being rendered correctly but the "score_progress_bar" object is not, it seems like it has margin somewhere or that the bounds are not set (notice that the TextView with the number "25" is not in the view center):

If you need the "score_progress_xml", here it is (it's just a RelativeLayout with some views):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/score_white_background"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp" />
    <ProgressBar
        android:id="@+id/progressRing"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:indeterminate="false"
        android:progressDrawable="@drawable/score_background_ring"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        android:progress="25" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="25"
        android:textSize="17dp"
        android:textColor="#000000"
        android:id="@+id/progressText"
        android:gravity="center" />
</RelativeLayout>
</code>```

Do you have any idea on what's going on here?

Edit: found a solution thanks to SushiHangover!
Just to complete this question in case someone else may need it, here's how I solved in this specific case:

```<code>var id = Application.Context.Resources.GetIdentifier("score_progress_bar", "layout", Application.Context.PackageName);
var li = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService);
var progressView = (RelativeLayout)li.Inflate(id, null, true);

var measuredWidth = View.MeasureSpec.MakeMeasureSpec(50, MeasureSpecMode.Exactly);
var measuredHeight = View.MeasureSpec.MakeMeasureSpec(50, MeasureSpecMode.Exactly);
progressView.Measure(measuredWidth, measuredHeight);
progressView.Layout(0, 0, progressView.MeasuredWidth, progressView.MeasuredWidth);

progressView.Draw(Native);
</code>```

答:
You need to use the result from View.MeasureSpec.MakeMeasureSpec as the origin of your X/Y measurements for the call to View.Measure and then use View.MeasuredWidth, which should be 50 in your case, in your View.Layout call. Now the View and all of its children are laid out correctly and you can Draw to your Canvas.

Here is a stripped down a version of the routine that I use to generate a series of countdown bitmaps (they get fed as Textures to OpenGL).

```<code>var xy = 200;
var inflater = (LayoutInflater)ApplicationContext.GetSystemService(LayoutInflaterService);
var progressIncludeID = ApplicationContext.Resources.GetIdentifier("progress_include", "layout", ApplicationContext.PackageName);
var pseudoProgressView = (RelativeLayout)inflater.Inflate(progressIncludeID, null, false);

int measuredWidth = View.MeasureSpec.MakeMeasureSpec(xy, MeasureSpecMode.Exactly);
int measuredHeight = View.MeasureSpec.MakeMeasureSpec(xy, MeasureSpecMode.Exactly);
pseudoProgressView.Measure(measuredWidth, measuredHeight);
pseudoProgressView.Layout(0, 0, pseudoProgressView.MeasuredWidth, pseudoProgressView.MeasuredWidth);

var imageBitmap = Bitmap.CreateBitmap(xy, xy, Bitmap.Config.Argb8888);
var canvas = new Canvas(imageBitmap);
pseudoProgressView.Draw(canvas);
</code>```

The top ProgressBar in the image below is rendered within a include -based RelativeLayout on-screen and the one on the bottom is a ImageView showing the BitMap of a completely off-screen rendering of the same RelativeLayout inflated axml:

Body:
I'm having problems while rendering a RelativeLayout at runtime inside a Canvas. I know this is Xamarin.Android, but it's actually pretty identical to "original" Android, so I'll accept every solution that works.

I have this xml that renders correctly inside my view (scroll down for the  "score_progress_bar" xml):

<LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content">
            <include
                layout="@layout/score_progress_bar"
                android:layout_width="50dp"
                android:layout_height="50dp" />
</LinearLayout>

And here is the correct result:

If I try to load the same thing via a Canvas, I'm not getting the same result. Here's the code where I try to load the same control at runtime:

var id = Application.Context.Resources.GetIdentifier("score_progress_bar", "layout", Application.Context.PackageName);

var ll = new LinearLayout(Application.Context);
ll.SetBackgroundColor(AndroidColor.Red);
ll.Measure(50, 50);
ll.Layout(0, 0, 50, 50);

var li = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService);
var v = (RelativeLayout)li.Inflate(id, null, true);
v.LayoutParameters = new RelativeLayout.LayoutParams(50, 50);
v.Measure(50, 50);
v.Layout(0, 0, 50, 50);

ll.AddView(v);
ll.Draw(Native);

Just to be clear, "Native" is my Canvas object and I'm setting a red background color to the LinearLayout so I can see where this is loaded in my view.

The result I'm getting is weird, the LinearLayout is being rendered correctly but the "score_progress_bar" object is not, it seems like it has margin somewhere or that the bounds are not set (notice that the TextView with the number "25" is not in the view center):

If you need the "score_progress_xml", here it is (it's just a RelativeLayout with some views):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/score_white_background"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp" />
    <ProgressBar
        android:id="@+id/progressRing"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:indeterminate="false"
        android:progressDrawable="@drawable/score_background_ring"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        android:progress="25" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="25"
        android:textSize="17dp"
        android:textColor="#000000"
        android:id="@+id/progressText"
        android:gravity="center" />
</RelativeLayout>

Do you have any idea on what's going on here?

Edit: found a solution thanks to SushiHangover!
Just to complete this question in case someone else may need it, here's how I solved in this specific case:

var id = Application.Context.Resources.GetIdentifier("score_progress_bar", "layout", Application.Context.PackageName);
var li = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService);
var progressView = (RelativeLayout)li.Inflate(id, null, true);

var measuredWidth = View.MeasureSpec.MakeMeasureSpec(50, MeasureSpecMode.Exactly);
var measuredHeight = View.MeasureSpec.MakeMeasureSpec(50, MeasureSpecMode.Exactly);
progressView.Measure(measuredWidth, measuredHeight);
progressView.Layout(0, 0, progressView.MeasuredWidth, progressView.MeasuredWidth);

progressView.Draw(Native);

Body:
You need to use the result from View.MeasureSpec.MakeMeasureSpec as the origin of your X/Y measurements for the call to View.Measure and then use View.MeasuredWidth, which should be 50 in your case, in your View.Layout call. Now the View and all of its children are laid out correctly and you can Draw to your Canvas.

Here is a stripped down a version of the routine that I use to generate a series of countdown bitmaps (they get fed as Textures to OpenGL).

var xy = 200;
var inflater = (LayoutInflater)ApplicationContext.GetSystemService(LayoutInflaterService);
var progressIncludeID = ApplicationContext.Resources.GetIdentifier("progress_include", "layout", ApplicationContext.PackageName);
var pseudoProgressView = (RelativeLayout)inflater.Inflate(progressIncludeID, null, false);

int measuredWidth = View.MeasureSpec.MakeMeasureSpec(xy, MeasureSpecMode.Exactly);
int measuredHeight = View.MeasureSpec.MakeMeasureSpec(xy, MeasureSpecMode.Exactly);
pseudoProgressView.Measure(measuredWidth, measuredHeight);
pseudoProgressView.Layout(0, 0, pseudoProgressView.MeasuredWidth, pseudoProgressView.MeasuredWidth);

var imageBitmap = Bitmap.CreateBitmap(xy, xy, Bitmap.Config.Argb8888);
var canvas = new Canvas(imageBitmap);
pseudoProgressView.Draw(canvas);

The top ProgressBar in the image below is rendered within a include -based RelativeLayout on-screen and the one on the bottom is a ImageView showing the BitMap of a completely off-screen rendering of the same RelativeLayout inflated axml:


问:
Cant' get WinAppDriver working with appium 1.6.3
I am trying to run a simple test of launching a calculator app on windows 10 64bit, I have got appium@1.6.3 installed. As per the doc with installation of appium, winappdriver will also be installed. However when I try to run my test, I see below error, which complains about winappdriver not installed.

```<code>C:\WINDOWS\system32>appium
[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"},null,null,null,null]
[Appium] Creating new WindowsDriver session
[Appium] Capabilities:
[Appium]   app: 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'
[Appium]   platformName: 'Windows'
[Appium]   deviceName: 'WindowsPC'
[BaseDriver] The following capabilities were provided, but are not recognized by appium: app.
[BaseDriver] Session created with session id: c0c6c7e6-b782-4b14-8192-bc78e5b38008
[WinAppDriver] Verifying WinAppDriver is installed with correct checksum
[HTTP] <-- POST /wd/hub/session - - ms - -
[debug] [WinAppDriver] Deleting WinAppDriver session
[MJSONWP] Encountered internal error running command: Error: Could not verify WinAppDriver install; re-run install
    at WinAppDriver.start$ (../../lib/winappdriver.js:35:13)
    at tryCatch (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:315:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:136:37)
</code>```

Also attaching my test script:

```<code>var wd = require("wd");
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should();
//enable chai assertion chaining
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

var serverConfig = {
    host:'127.0.0.1',
    port:4723,

};

var capabilities = {
    app:'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App',
    platformName:'Windows',
    deviceName:'WindowsPC'
};

var driver;

describe('test calculator',function(){
it('test launch calculator',function(done){

  driver = wd.promiseChainRemote(serverConfig);
  console.log(driver)
  this.timeout(10000);
    var cap=driver.init(capabilities);
    console.log(cap)
         done();
})
});
</code>```

答:
I know that my reply is too late

I just wanted others to know
that the win app driver version in used in appium is too old(0.7) so just download it directly from GitHub (0.9)

Body:
I am trying to run a simple test of launching a calculator app on windows 10 64bit, I have got appium@1.6.3 installed. As per the doc with installation of appium, winappdriver will also be installed. However when I try to run my test, I see below error, which complains about winappdriver not installed.

C:\WINDOWS\system32>appium
[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"},null,null,null,null]
[Appium] Creating new WindowsDriver session
[Appium] Capabilities:
[Appium]   app: 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'
[Appium]   platformName: 'Windows'
[Appium]   deviceName: 'WindowsPC'
[BaseDriver] The following capabilities were provided, but are not recognized by appium: app.
[BaseDriver] Session created with session id: c0c6c7e6-b782-4b14-8192-bc78e5b38008
[WinAppDriver] Verifying WinAppDriver is installed with correct checksum
[HTTP] <-- POST /wd/hub/session - - ms - -
[debug] [WinAppDriver] Deleting WinAppDriver session
[MJSONWP] Encountered internal error running command: Error: Could not verify WinAppDriver install; re-run install
    at WinAppDriver.start$ (../../lib/winappdriver.js:35:13)
    at tryCatch (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:315:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:136:37)

Also attaching my test script:

var wd = require("wd");
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should();
//enable chai assertion chaining
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

var serverConfig = {
    host:'127.0.0.1',
    port:4723,

};

var capabilities = {
    app:'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App',
    platformName:'Windows',
    deviceName:'WindowsPC'
};

var driver;

describe('test calculator',function(){
it('test launch calculator',function(done){

  driver = wd.promiseChainRemote(serverConfig);
  console.log(driver)
  this.timeout(10000);
    var cap=driver.init(capabilities);
    console.log(cap)
         done();
})
});


问:
How to match URL with href in jQuery?
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

```<code><li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
</code>```

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

```<code>$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

```<code>$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

<ul class="leftNav">
<li data-left-nav-href="/p/clothing/dresses/N-10635"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li data-left-nav-href="/p/clothing/bottoms/capris/N-10764"><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

答:
Assuming there isn't any '?' character in the actual path you could use something like this for both the location and the href:</p>

```<code>function getBaseURL(url) {
    return url.split('?')[0];
}
</code>```

Title: How to match URL with href in jQuery?

Body:
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

dresses

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

dresses

capris

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

dresses

capris

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

Body:
Assuming there isn't any '?' character in the actual path you could use something like this for both the location and the href:

function getBaseURL(url) {
    return url.split('?')[0];
}


问:
MSAL library sign in without response
I'm trying an application that is able to display all and create new events for the Outlook calendar. I am using the MSAL library to get the authentication code. The problem is that although the login screen appears when I touch the buttons enter or cancel I do not notice any reaction. This is my code:</p>

```<code>class OutlookManagerController: BaseViewController {
    let oClientKey = "a07745a5-3b90-4385-a2b2-8223dbf68688"
    let authScopes = ["openid+https://outlook.office.com/contacts.read+offline_access"]

    func getAcessToken(){
        if let application = try? MSALPublicClientApplication.init(clientId: oClientKey) {
            application.acquireToken(forScopes: authScopes) { (result, error) in
                if result != nil {
                    let userToken = result!.accessToken!
                    print(userToken)

                } else {
                    print(error!.localizedDescription)
                }
            }
        }
        else {
            print("Unable to create application.")
        }
    }
}
</code>```

答:
```<code>func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    MSALPublicClientApplication.handleMSALResponse(url)
    return true
}
</code>```

Title: MSAL library sign in without response

Body:
I'm trying an application that is able to display all and create new events for the Outlook calendar. I am using the MSAL library to get the authentication code. The problem is that although the login screen appears when I touch the buttons enter or cancel I do not notice any reaction. This is my code:

class OutlookManagerController: BaseViewController {
    let oClientKey = "a07745a5-3b90-4385-a2b2-8223dbf68688"
    let authScopes = ["openid+https://outlook.office.com/contacts.read+offline_access"]

    func getAcessToken(){
        if let application = try? MSALPublicClientApplication.init(clientId: oClientKey) {
            application.acquireToken(forScopes: authScopes) { (result, error) in
                if result != nil {
                    let userToken = result!.accessToken!
                    print(userToken)

                } else {
                    print(error!.localizedDescription)
                }
            }
        }
        else {
            print("Unable to create application.")
        }
    }
}


问:
Friendship and Interfaces
I'm having a compilation error using Apple's Clang 7.0 with the following friendship code, using C++11 standard. I wonder what's really wrong with it since it seems to be valid for me. I'm describing the setting and the error I'm having:

MyInterface

```<code>namespace namespace1
{

class MyInterface
{
friend class MyClass;
public:
    virtual void some_method(void) = 0;
    ...
private:
    type some_attribute;
    ...
}

}
</code>```

MyClass::MyMethod Implementation

```<code>namespace namespace2
{

void MyClass::MyMethod(MyInterface* MyConcrete)
{
    ...
    // MyConcrete implements MyInterface
    if(MyConcrete->some_attribute == some_value) // Error*
    {
       ...
    }
    ...
}

}
</code>```

Error

```<code>error: 'some_attribute' is a private member of 'namespace1::MyInterface'
</code>```

I really expected that MyClass would have access to some_attribute in MyConcrete (which implemented MyInterface) regardless of the class access modifier. Any clues why this error is happening? Any suggestions?

Thank you!

答:
friend class MyClass; in the context of ::namespace1::MyInterface refers to the class ::namespace1::MyClass, which is a different class from ::namespace2::MyClass.  (That's the whole point of namespaces, right?)

Change the friend declaration to read like this:

```<code>friend class ::namespace2::MyClass;
</code>```

Note that this requires that the type ::namespace2::MyClass has already been declared, so you either need to forward-declare it (namespace namespace2 { class MyClass; }) or you need to make sure that the definition is included prior to the definition of ::namespace1::MyInterface.

(See this demo.)

Title: Friendship and Interfaces

Body:
I'm having a compilation error using Apple's Clang 7.0 with the following friendship code, using C++11 standard. I wonder what's really wrong with it since it seems to be valid for me. I'm describing the setting and the error I'm having:

MyInterface

namespace namespace1
{

class MyInterface
{
friend class MyClass;
public:
    virtual void some_method(void) = 0;
    ...
private:
    type some_attribute;
    ...
}

}

MyClass::MyMethod Implementation

namespace namespace2
{

void MyClass::MyMethod(MyInterface* MyConcrete)
{
    ...
    // MyConcrete implements MyInterface
    if(MyConcrete->some_attribute == some_value) // Error*
    {
       ...
    }
    ...
}

}

Error

error: 'some_attribute' is a private member of 'namespace1::MyInterface'

I really expected that MyClass would have access to some_attribute in MyConcrete (which implemented MyInterface) regardless of the class access modifier. Any clues why this error is happening? Any suggestions?

Thank you!

Body:
friend class MyClass; in the context of ::namespace1::MyInterface refers to the class ::namespace1::MyClass, which is a different class from ::namespace2::MyClass.  (That's the whole point of namespaces, right?)

Change the friend declaration to read like this:

friend class ::namespace2::MyClass;

Note that this requires that the type ::namespace2::MyClass has already been declared, so you either need to forward-declare it (namespace namespace2 { class MyClass; }) or you need to make sure that the definition is included prior to the definition of ::namespace1::MyInterface.

(See this demo.)


问:
Using `ipywidgets.iteract`, is it possible to locate the output beside the widgets and not below them?
When using the ipywidgets.interact function in Jupyter notebooks, the output is always below the widgets. Is it possible to show it besides the widgets?
In other words, instead of this:

(taken from this example),

I would like to see something like this:

答:
You can do that with the interactive function along with HBox and or VBox

Using this answer as an example with the following lines for the desired effect:

```<code>hb = widgets.VBox([my_plts.children[0],my_plts.children[1]])

widgets.HBox([my_plts.children[2], hb])
</code>```

However the plot does not appear at first you have to start moving the sliders for it to render. At least that's been my experience. I'm sure there is a way to fix it but I'm to lazy to investigate. Hope that helps!

Body:
You can do that with the interactive function along with HBox and or VBox

Using this answer as an example with the following lines for the desired effect:

hb = widgets.VBox([my_plts.children[0],my_plts.children[1]])

widgets.HBox([my_plts.children[2], hb])

However the plot does not appear at first you have to start moving the sliders for it to render. At least that's been my experience. I'm sure there is a way to fix it but I'm to lazy to investigate. Hope that helps!


问:
Whats wrong with my JS / jQuery code?
I'm trying to build an autocomplete jQuery input. I have a form that contains an input, and I want the autocomplete to work with Yelp's API to autocomplete restaurant names. when I run the page and type anything into the input textbox, nothing happens

here is my code:

```<code><html>
<body>
<input id="restaurantSearch" />

```

```

'

答:
I haven't tried this code, since I don't have a Yelp account (thus no auth tokens), but I immediately see a few problems in your code.  For one thing, autocomplete isn't a jQuery function, but rather a jQuery-ui function.  You'll need to include the jQuery-ui javascript.

Next, there's numerous code errors that any browser console should have brought to your attention.  For example, the alert(req); inside the autocomplete call is wrong for a couple reasons... for one thing, you are calling autocomplete with a hash parameter, which is the way you set properties.  Therefore, you can't put function calls in there like that.  Look at the way the source property of the hash is defined - in the form: attributeName : value

Also, even if that code were legal to place there, req hadn't even been defined yet.

It seems like you don't have a proper # of matching end braces, but I might be wrong about that - it never hurts to indent code within braces so you can easily line up matching braces visually.

It looks like you're using at least one of the browsers' development tools (Firebug, webkit developer mode, etc)... at least that's what I'm guessing since you used console.log() in your ajax callback.  Assuming this is the case, your console should tell you that there's errors in your code.

As for the above comment about cross-domain Ajax, it's simply incorrect... JSONP with a callback is a technique that gets around cross-domain restrictions, and is supported in at least jQuery 1.4.  So, I don't think your problem is that part of your code.

Good luck.

Title: Whats wrong with my JS / jQuery code?

Body:
I'm trying to build an autocomplete jQuery input. I have a form that contains an input, and I want the autocomplete to work with Yelp's API to autocomplete restaurant names. when I run the page and type anything into the input textbox, nothing happens

here is my code:

<input id="restaurantSearch" />

'


问:
Java Spring Boot/Mysql - Doing a query with a HashSet as a Parameter
I'm doing a Spring Boot application with JPA and I have and object (let's call it Conversation) which has a property that is a HashSet of another object (User). In the ConversationRepository there's the following method:

```<code>@Query("SELECT c FROM Conversation c WHERE ?1 MEMBER OF c.users
Conversation findByUsers(Set<User> users);
</code>```

However, when I try to use this query passing a HashSet of User as parameter (which it has two users stored), there's a SQLException (1241) which says that the operand should contain 2 columns.

What is the correct way to do a query with a HashSet as a parameter?

答:
Your method is not passing the first parameter value. Your query expecting two inputs and your method signature has only one. try passing the value for ?1.

Modify your query like

@Query("SELECT c FROM Conversation c WHERE :value MEMBER OF c.users

Conversation findByUsers(User value, Set users);

Body:
I'm doing a Spring Boot application with JPA and I have and object (let's call it Conversation) which has a property that is a HashSet of another object (User). In the ConversationRepository there's the following method:

@Query("SELECT c FROM Conversation c WHERE ?1 MEMBER OF c.users
Conversation findByUsers(Set<User> users);

However, when I try to use this query passing a HashSet of User as parameter (which it has two users stored), there's a SQLException (1241) which says that the operand should contain 2 columns.

What is the correct way to do a query with a HashSet as a parameter?


问:
Where are variables set in cmake?
I'm having trouble with a make process, so after some reading I was led to the CMakeLists.txt file, which as I understand, is a configuration of sorts for cmake (which in turn generated makefiles).

So, I'm looking through a CMakeLists.txt file.  I'm seeing references to something called ${PROJECT_SOURCE_DIR} but it doesn't seem to be declared anywhere in the file.  Where is it declared?

答: There are many automatic variables, which are set by CMake or by other means. See variables documentation.

Title: Where are variables set in cmake?


问:
How to add onclick to an element using Javascript
I have an HTML button like so:

```<code><div class="row text-center">
   <button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>
</code>```

I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:

```<code>$("#button1").addEventListener("click", showAlert());
</code>```

However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

答:
try jquery function:</p>

```<code>$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;
</code>```

Body:
I have an HTML button like so:

   <button id="button1" type="submit" class="btn btn-primary">Submit</button>

I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:

$("#button1").addEventListener("click", showAlert());

However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

Body:
try jquery function:

$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;


问:
In Power Builder trying to replace a escape character with ~ sign
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

```<code>Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")
</code>```

Any help here please.

答:
Here is my current code:</p>

```<code>llSigCount = ldsSig.Retrieve(iuQstr.isPtID, iuQstr.ilPtVisitID, iuQstr.ilQstrID, AUTH_EVENT_TYPE)

IF llSigCount > 0 THEN
    lsSignature = ldsSig.GetItemString(1, "cf_name_date")
IF POS(Signature, "'") > 0 THEN
  Signature = Replace (Signature, POS(Signature, "'"), 1, "~'")
END IF
    dw_edit.Modify("auth_signature_t.Text='" + lsSignature + "'")
END IF
</code>```

Body:
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")

Any help here please.

Body:
Here is my current code:

llSigCount = ldsSig.Retrieve(iuQstr.isPtID, iuQstr.ilPtVisitID, iuQstr.ilQstrID, AUTH_EVENT_TYPE)

IF llSigCount > 0 THEN
    lsSignature = ldsSig.GetItemString(1, "cf_name_date")
IF POS(Signature, "'") > 0 THEN
  Signature = Replace (Signature, POS(Signature, "'"), 1, "~'")
END IF
    dw_edit.Modify("auth_signature_t.Text='" + lsSignature + "'")
END IF


问:
How to share objects between different functions
I'm trying to make it so that if a user activates test, it will display a test menu in the chatroom and if that same user posts a reaction on any message, it will delete that test menu:

```<code>import discord, asyncio

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")

@client.event
async def on_reaction_add(reaction, user):
    if user == message.author:
        await client.delete_message(menu)

client.run('ClientToken')
</code>```

However, the code is not reading the objects like message.author or menu from the other function.

答:
You could just create a dictionary to hold the message and author values.</p>

```<code>test = {'message': None, 'author': None}

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")
        test['message'] = menu
        test['author'] = message.author

@client.event
async def on_reaction_add(reaction, user):
    if user == test['author']:
        await client.delete_message(test['message'])
</code>```

Body:
I'm trying to make it so that if a user activates test, it will display a test menu in the chatroom and if that same user posts a reaction on any message, it will delete that test menu:

import discord, asyncio

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")

@client.event
async def on_reaction_add(reaction, user):
    if user == message.author:
        await client.delete_message(menu)

client.run('ClientToken')

However, the code is not reading the objects like message.author or menu from the other function.

Body:
You could just create a dictionary to hold the message and author values.

test = {'message': None, 'author': None}

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")
        test['message'] = menu
        test['author'] = message.author

@client.event
async def on_reaction_add(reaction, user):
    if user == test['author']:
        await client.delete_message(test['message'])


问:
Convert all words from text file to UpperCase using cmd or vbsscript
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

```<code>@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)
</code>```

but i do not see where to put the location of the test.txt file

答:
File: fucase.vbs

```<code>Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\Test.txt", 1, True)

Do Until f.AtEndOfStream
  WScript.Echo UCase(f.ReadLine)
Loop

f.Close
</code>```

Batch (or cmd) call:

```<code>cscript fucase.vbs
</code>```

Body:
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)

but i do not see where to put the location of the test.txt file

Body:
File: fucase.vbs

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\Test.txt", 1, True)

Do Until f.AtEndOfStream
  WScript.Echo UCase(f.ReadLine)
Loop

f.Close

Batch (or cmd) call:

cscript fucase.vbs


问:
How to bring ALL data from a query in MySQL?
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

```<code>SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;
</code>```

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?

答:
Look at your joins, 'JOIN' is the same as 'INNER JOIN' which only shows results which is in both tables, you'll need to use a LEFT or FULL join to get what you need.

Theres a diagram here which explains them well

Body:
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?


问:
Understanding the Scala Map object when mapping to the head of a list
Hi I have the following data and want to map it to the first item in the second parameter. So for:

```<code>1 -> List((1,11))
1 -> List((1,1), (1,111))
</code>```

I want:

```<code>(1,11)
(1,1)
</code>```

When this data is in an RDD I can do the following:

```<code>scala> val m = sc.parallelize(Seq(11 -> List((1,11)), 1 -> List((1,1),(1,111))))
m: org.apache.spark.rdd.RDD[(Int, List[(Int, Int)])] = ParallelCollectionRDD[198] at parallelize at <console>:47

scala> m.map(_._2.head).collect.foreach(println)
(1,11)
(1,1)
</code>```

However, when it is in a Map object (result of a groupBy) I get the following:

```<code>scala> val m = Map(11 -> List((1,11)), 1 -> List((1,1)))
m: scala.collection.immutable.Map[Int,List[(Int, Int)]] = Map(11 -> List((1,11)), 1 -> List((1,1), (1,111)))

scala> m.map(_._2.head)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)
</code>```

When I map to the whole list I get what I would expect, but not when I call head on it

```<code>scala> m.map(_._2)
res2: scala.collection.immutable.Iterable[List[(Int, Int)]] = List(List((1,11)), List((1,1), (1,111)))
</code>```

I can also get the result I want if I do either of the following:

```<code>scala> m.map(_._2).map(_.head)
res4: scala.collection.immutable.Iterable[(Int, Int)] = List((1,11), (1,1))

scala> m.values.map(_.head)
res5: Iterable[(Int, Int)] = List((1,11), (1,1))
</code>```

Could someone explain please what is going on here?

答:
The map operation on a scala.collection.immutable.Map behave differently depending on the return type of the map operation.

When the return type if of Type Tuple2[T,P]:

the output of the Map operation results in an another Map with the first element of the tuple _1 as the key and the second element _2 as the value.

for example

```<code>scala> m.map(_ => 10 -> 1)
res14: scala.collection.immutable.Map[Int,Int] = Map(10 -> 1) // note the return type is Map.
</code>```

When the return type is anything other than Tuple2:

when the return type is anything other than Tuple2 then output of the map operation is a list.

```<code>scala> m.map(_ => 10 )
res15: scala.collection.immutable.Iterable[Int] = List(10, 10) // note that the return type now is a List.
</code>```

so with the above established fact, for a Map of value Map(11 -> List((1,11)), 1 -> List((1,1))) the operation m.map(_._2.head) produces Tuple2 values (1, 11) and (1,1). since the first value (_1) of each Tuple2 item is 1 (i.e. the key of each value is 1), the (1,1) overwrites (1,11) and we end up with a single value of (1,1).

In other cases the map operation doesnt return types of Tuple2 and hence it results in List type instead of Maptypes hence the difference is results.

Body:
Hi I have the following data and want to map it to the first item in the second parameter. So for:

1 -> List((1,11))
1 -> List((1,1), (1,111))

I want:

(1,11)
(1,1)

When this data is in an RDD I can do the following:

scala> val m = sc.parallelize(Seq(11 -> List((1,11)), 1 -> List((1,1),(1,111))))
m: org.apache.spark.rdd.RDD[(Int, List[(Int, Int)])] = ParallelCollectionRDD[198] at parallelize at <console>:47

scala> m.map(_._2.head).collect.foreach(println)
(1,11)
(1,1)

However, when it is in a Map object (result of a groupBy) I get the following:

scala> val m = Map(11 -> List((1,11)), 1 -> List((1,1)))
m: scala.collection.immutable.Map[Int,List[(Int, Int)]] = Map(11 -> List((1,11)), 1 -> List((1,1), (1,111)))

scala> m.map(_._2.head)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)

When I map to the whole list I get what I would expect, but not when I call head on it

scala> m.map(_._2)
res2: scala.collection.immutable.Iterable[List[(Int, Int)]] = List(List((1,11)), List((1,1), (1,111)))

I can also get the result I want if I do either of the following:

scala> m.map(_._2).map(_.head)
res4: scala.collection.immutable.Iterable[(Int, Int)] = List((1,11), (1,1))

scala> m.values.map(_.head)
res5: Iterable[(Int, Int)] = List((1,11), (1,1))

Could someone explain please what is going on here?

Body:
The map operation on a scala.collection.immutable.Map behave differently depending on the return type of the map operation.

When the return type if of Type Tuple2[T,P]:

the output of the Map operation results in an another Map with the first element of the tuple _1 as the key and the second element _2 as the value.

for example

scala> m.map(_ => 10 -> 1)
res14: scala.collection.immutable.Map[Int,Int] = Map(10 -> 1) // note the return type is Map.

When the return type is anything other than Tuple2:

when the return type is anything other than Tuple2 then output of the map operation is a list.

scala> m.map(_ => 10 )
res15: scala.collection.immutable.Iterable[Int] = List(10, 10) // note that the return type now is a List.

so with the above established fact, for a Map of value Map(11 -> List((1,11)), 1 -> List((1,1))) the operation m.map(_._2.head) produces Tuple2 values (1, 11) and (1,1). since the first value (_1) of each Tuple2 item is 1 (i.e. the key of each value is 1), the (1,1) overwrites (1,11) and we end up with a single value of (1,1).

In other cases the map operation doesnt return types of Tuple2 and hence it results in List type instead of Maptypes hence the difference is results.


问:
ruby module NameError: uninitialized constant error
I am trying to create a gem, but when trying to load a module in test I get the following error. I used "Configurable Ruby gems: Custom error messages and testing" to set environment variables from users and that's where most of the code is from.

```<code>  1) Msg91sms::Configuration with configuration block returns the correct authkey
     Failure/Error: raise Errors::Configuration, "Msg94 auth key missing!" unless @authkey

     NameError:
       uninitialized constant Msg91sms::Configuration::Errors
     # ./lib/msg91sms/configuration.rb:10:in `authkey'
     # ./spec/msg91sms/configuration_spec.rb:7:in `block (3 levels) in <top (required)>'
</code>```

but as per the folder structure and everything this should be Msg91sms::Errors::Configuration. I put only one here even though all tests are failing due to improper module loading.

The gem with this error can be found here: https://github.com/flyingboy007/msg91sms/tree/development

bundle exec rspec will throw all errors.

It should be something with naming or improper loading. But I can't figure out.

After following the answer by @sergio, I am now getting this error:

```<code>  1) Msg91sms::Configuration with configuration block returns the correct authkey
     Failure/Error: raise ::Msg91sms::Errors::Configuration, "Msg91 auth key missing!" unless @authkey

     NameError:
       uninitialized constant Msg91sms::Errors
     # ./lib/msg91sms/configuration.rb:10:in `authkey'
     # ./spec/msg91sms/configuration_spec.rb:7:in `block (3 levels) in <top (required)>'
</code>```

Could someone tell me what am doing wrong here?

答:
```<code>raise Errors::Configuration, "Msg94 auth key missing!" unless @authkey
</code>```

Use fully qualified name to help ruby lookup the class.

```<code>raise ::Msg91sms::Errors::Configuration, "Msg94 auth key missing!" unless @authkey
</code>```

The folder structure is like Errors::Configuration but the error is showing like Configuration::Errors..Dont know why..

It's trying to find Errors::Configuration within Msg91sms::Configuration (the current scope at that point). But since there's no Msg91sms::Configuration::Errors, it fails with that message.

Body:
I am trying to create a gem, but when trying to load a module in test I get the following error. I used "Configurable Ruby gems: Custom error messages and testing" to set environment variables from users and that's where most of the code is from.

  1) Msg91sms::Configuration with configuration block returns the correct authkey
     Failure/Error: raise Errors::Configuration, "Msg94 auth key missing!" unless @authkey

     NameError:
       uninitialized constant Msg91sms::Configuration::Errors
     # ./lib/msg91sms/configuration.rb:10:in `authkey'
     # ./spec/msg91sms/configuration_spec.rb:7:in `block (3 levels) in <top (required)>'

but as per the folder structure and everything this should be Msg91sms::Errors::Configuration. I put only one here even though all tests are failing due to improper module loading.

The gem with this error can be found here: https://github.com/flyingboy007/msg91sms/tree/development

bundle exec rspec will throw all errors.

It should be something with naming or improper loading. But I can't figure out.

After following the answer by @sergio, I am now getting this error:

  1) Msg91sms::Configuration with configuration block returns the correct authkey
     Failure/Error: raise ::Msg91sms::Errors::Configuration, "Msg91 auth key missing!" unless @authkey

     NameError:
       uninitialized constant Msg91sms::Errors
     # ./lib/msg91sms/configuration.rb:10:in `authkey'
     # ./spec/msg91sms/configuration_spec.rb:7:in `block (3 levels) in <top (required)>'

Could someone tell me what am doing wrong here?

Body:
raise Errors::Configuration, "Msg94 auth key missing!" unless @authkey

Use fully qualified name to help ruby lookup the class.

raise ::Msg91sms::Errors::Configuration, "Msg94 auth key missing!" unless @authkey

The folder structure is like Errors::Configuration but the error is showing like Configuration::Errors..Dont know why..

It's trying to find Errors::Configuration within Msg91sms::Configuration (the current scope at that point). But since there's no Msg91sms::Configuration::Errors, it fails with that message.


问:
How to ease nested looping?
I find myself looping over vectors of vectors a lot:

```<code>std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}
</code>```

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

答:
I think what you are looking for is Iterator pattern.

http://en.wikipedia.org/wiki/Iterator

Title: How to ease nested looping?

Body:
I find myself looping over vectors of vectors a lot:

std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody


问:
Construct generic class of concrete class from interface
I have a WCF service which accepts any entity which implements an interface. When it receives one of these entities I would like to publish an event i.e.

```<code>public void Receive(IFruit fruit)
{
      messageHub.Publish(new FruitReceived<IFruit>(fruit));
}
</code>```

However I would like to reify the interface so instead of everything that handles fruit subscribing to the event FruitReceived<IFruit> they can subscribe to only the type they're interested in such as FruitReceived<Apple>.

Currently I can do this through some lengthy reflection:

```<code>var fruitType = fruit.GetType();
var evt = typeof(FruitReceived<>)
    .MakeGenericType(fruitType)
    .GetConstructor(fruitType)
    .Invoke(fruit);
</code>```

This is a bit of a performance hit (even with caching the constructors) and also hard to read.

I was hoping that there's a simpler way to achieve this? I have spent so much time thinking about this solution that it's the only one I can come up with.

For reference the publish method simplifies to something like this:

```<code>public void Publish<TEvent>(TEvent evt)
{
    if(_subscriptions.ContainsKey(typeof(TEvent))
    {
        IEnumerable<IEventHandler<TEvent>> handlers = _subscriptions[typeof(TEvent)];

        foreach(var handler in handlers)
        {
            handler.HandleEvent(evt);
        }
    }
}
</code>```

答:
The underlying problem seems to be that you're receiving an instance of IFruit but downstream you want to distinguish between different concrete types.

The benefit of casting a class as an interface it implements is that consumers only need to know what the declared type is. They know it's an IFruit and that's all they need to know. As soon as they need to know more than that the benefit is reduced.

In other words, if you care at all about the difference between an Apple and an Orange then why cast it as an IFruit? Of course there are differences between implementations, but those differences - even the existence of different implementations - should be transparent to anything that depends on an IFruit.

There's no perfectly neat way to handle this. If you're not creating the generic type (as in your post) then you're doing this:

```<code>if(fruit is Apple)
</code>```

There's going to be type creation or type inspection no matter what.

You could move the problem. Have a single event handler that handles FruitReceived<IFruit>. Then that event handler creates the more specific event type and re-raises it so that the more specific event handler can catch it. That way you can have event handlers specific to Apple, Orange, etc.

It's not perfect but it moves the problem from where the event is getting raised to another class that facilitates raising the more specific event type.

Another reason why this is beneficial is that your design allows for multiple event handlers. So conceivably you could raise FruitEvent<IFruit> where the concrete type is an Apple, so you want an apple-specific event handler, but you also want a generic IFruit event handler to execute. If you convert your event to FruitEvent<Apple> before raising it then you won't execute the generic event handler.

Body:
I have a WCF service which accepts any entity which implements an interface. When it receives one of these entities I would like to publish an event i.e.

public void Receive(IFruit fruit)
{
      messageHub.Publish(new FruitReceived<IFruit>(fruit));
}

However I would like to reify the interface so instead of everything that handles fruit subscribing to the event FruitReceived<IFruit> they can subscribe to only the type they're interested in such as FruitReceived<Apple>.

Currently I can do this through some lengthy reflection:

var fruitType = fruit.GetType();
var evt = typeof(FruitReceived<>)
    .MakeGenericType(fruitType)
    .GetConstructor(fruitType)
    .Invoke(fruit);

This is a bit of a performance hit (even with caching the constructors) and also hard to read.

I was hoping that there's a simpler way to achieve this? I have spent so much time thinking about this solution that it's the only one I can come up with.

For reference the publish method simplifies to something like this:

public void Publish<TEvent>(TEvent evt)
{
    if(_subscriptions.ContainsKey(typeof(TEvent))
    {
        IEnumerable<IEventHandler<TEvent>> handlers = _subscriptions[typeof(TEvent)];

        foreach(var handler in handlers)
        {
            handler.HandleEvent(evt);
        }
    }
}

Body:
The underlying problem seems to be that you're receiving an instance of IFruit but downstream you want to distinguish between different concrete types.

The benefit of casting a class as an interface it implements is that consumers only need to know what the declared type is. They know it's an IFruit and that's all they need to know. As soon as they need to know more than that the benefit is reduced.

In other words, if you care at all about the difference between an Apple and an Orange then why cast it as an IFruit? Of course there are differences between implementations, but those differences - even the existence of different implementations - should be transparent to anything that depends on an IFruit.

There's no perfectly neat way to handle this. If you're not creating the generic type (as in your post) then you're doing this:

if(fruit is Apple)

There's going to be type creation or type inspection no matter what.

You could move the problem. Have a single event handler that handles FruitReceived<IFruit>. Then that event handler creates the more specific event type and re-raises it so that the more specific event handler can catch it. That way you can have event handlers specific to Apple, Orange, etc.

It's not perfect but it moves the problem from where the event is getting raised to another class that facilitates raising the more specific event type.

Another reason why this is beneficial is that your design allows for multiple event handlers. So conceivably you could raise FruitEvent<IFruit> where the concrete type is an Apple, so you want an apple-specific event handler, but you also want a generic IFruit event handler to execute. If you convert your event to FruitEvent<Apple> before raising it then you won't execute the generic event handler.


问:
ASP.NET Mvc Button in jumbotron can't be moved up
I've tried margin-bottom, padding, top:5px; but nothing seems to be moving it.

Find out more! »

css contains too many stuff for me to find the css I need to change. Is there anyway I can change it from my Index view?

答: margin-top:-5px should work. You can also position the anchor element via position: relative and bottom:5px</p>


问:
Unique Data Uplload in Python Excel
In New API(Python-Odo o) I Successfully upload Excel File.

But if second time i upload same file Data are Duplicated.
So How I upload only Unique Data.

If No Change in Excel file no changes in recored

But if Change in Data
this only recored updated reaming recored same as upload.

Thanks

答:
Hello viral,

When you upload first time data in excel that time take one unique column(i.e ID)
and when you second time upload data that time check the unique column, if found so only update their data else upload data as new record.

Title: Unique Data Uplload in Python Excel


问:
Shows "Unable to get repr for <class 'django.db.models.query.QuerySet'>" while retrieving data
I've been trying to retrieve all data from model StudentInfo.
But it shows the following error.

django.db.utils.ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
  allStudent

  Error in formatting: ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
  LINE 1: ...ile_no1", "student_studentinfo"."current_address", "student_s...

After debugging my code, I found the line that causes error is

allStudent = StudentInfo.objects.all()

And the debugging messages Shows:

Unable to get repr for class 'django.db.models.query.QuerySet'

Here is my model StudentInfo

```<code>class StudentInfo(models.Model):
    student_name = models.CharField("Student Name",max_length=20)
    admission_date = models.DateField("Admission Date")
    mobile_no1 = models.CharField("Mobile No.",max_length=12)
    current_address = models.CharField("Current Address",max_length=20,blank=True)
    batch_number = models.ForeignKey(BatchInfo)
    coaching_id = models.IntegerField("Coaching ID")

    def __unicode__(self):
        return self.student_name

    def __repr__(self):
        return str(self.student_name)
</code>```

And the other model BatchInfo that is related to StudentInfo

```<code>class BatchInfo(models.Model):
    batch_name = models.CharField("Batch Name",max_length=20)
    batch_started_from = models.DateField("Batch Started From")
    no_of_registered_student = models.IntegerField("Number of Registered Student so far",default=0)

    def __str__(self):
        return self.batch_name
    def __unicode__(self):
        return self.batch_name
</code>```

The strange part is that I've used the same style of code in other places which are perfectly functioning.

all_batch = BatchInfo.objects.all()

I try my best to solve it by my own but as a newbie, I found it very difficult for me. So I ask your help.
Thanks in advance.

答:
It looks like you are using Python 3.x

Change your

```<code>def __unicode__(self):
</code>```

to

```<code>def __str__(self):
</code>```

Body:
I've been trying to retrieve all data from model StudentInfo.
But it shows the following error.

django.db.utils.ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
  allStudent

  Error in formatting: ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
  LINE 1: ...ile_no1", "student_studentinfo"."current_address", "student_s...

After debugging my code, I found the line that causes error is

allStudent = StudentInfo.objects.all()

And the debugging messages Shows:

Unable to get repr for class 'django.db.models.query.QuerySet'

Here is my model StudentInfo

class StudentInfo(models.Model):
    student_name = models.CharField("Student Name",max_length=20)
    admission_date = models.DateField("Admission Date")
    mobile_no1 = models.CharField("Mobile No.",max_length=12)
    current_address = models.CharField("Current Address",max_length=20,blank=True)
    batch_number = models.ForeignKey(BatchInfo)
    coaching_id = models.IntegerField("Coaching ID")

    def __unicode__(self):
        return self.student_name

    def __repr__(self):
        return str(self.student_name)

And the other model BatchInfo that is related to StudentInfo

class BatchInfo(models.Model):
    batch_name = models.CharField("Batch Name",max_length=20)
    batch_started_from = models.DateField("Batch Started From")
    no_of_registered_student = models.IntegerField("Number of Registered Student so far",default=0)

    def __str__(self):
        return self.batch_name
    def __unicode__(self):
        return self.batch_name

The strange part is that I've used the same style of code in other places which are perfectly functioning.

all_batch = BatchInfo.objects.all()

I try my best to solve it by my own but as a newbie, I found it very difficult for me. So I ask your help.
Thanks in advance.

Body:
It looks like you are using Python 3.x

Change your

def __unicode__(self):

to

def __str__(self):


问:
Getter and Setter Aliasing in C#
How would I go about aliasing a variable from it's plural form so that referencing the plural form changes or returns the single form?

I have a global variable as such with a Getter and Setter:

```<code>public string UserName { get; set; }
</code>```

And would like to set up an aliased variable UserNames that would return UserName and when set would modify UserName?

I've tried public string UserNames { get => UserName; set => UserName = UserNames } but that didn't seem to work.

答:
Almost, you have to use value in your setter.

```<code>public string UserNames { get => UserName; set => UserName = value; }
</code>```

Title: Getter and Setter Aliasing in C#

Body:
How would I go about aliasing a variable from it's plural form so that referencing the plural form changes or returns the single form?

I have a global variable as such with a Getter and Setter:

public string UserName { get; set; }

And would like to set up an aliased variable UserNames that would return UserName and when set would modify UserName?

I've tried public string UserNames { get => UserName; set => UserName = UserNames } but that didn't seem to work.

Body:
Almost, you have to use value in your setter.

public string UserNames { get => UserName; set => UserName = value; }


问:
JOGL objects "Disappearing" when moving around a scene
I'm trying to implement a basic physics engine in Java and I'm using the JOGL bindings so I can visualize the results. I can create and rotate shapes easily enough, but have run into problems whilst manipulating the viewport and whilst moving the shapes.

I don't think a clipping issue - I've tried using the gluPerspective method with a massive range (0.0001f - 10000f) with no success. When I move the camera further away from my objects or move the objects themselves, they disappear.

Tutorials about JOGL are few and far between and many also use different versions of OpenGL, so I turn to the only friend I have left: the wonderful users of stack overflow. :)

Flattery aside, the code follows:

```<code>public class JoglEventListener implements GLEventListener, KeyListener, MouseListener, MouseMotionListener {
// keep pointer to associated canvas so we can refresh the screen (equivalent to glutPostRedisplay())
public GLCanvas canvas;
public Particle triforce;
public float x;

// constructor
public JoglEventListener(GLCanvas canvas) {
    this.canvas = canvas;
}

@Override
public void display(GLAutoDrawable drawable) {
    update();
    render(drawable);
}

@Override
public void init(GLAutoDrawable drawable) {
    triforce = new Particle();
    x = 0;
}

private void update() {
    triforce.integrate(0.0001);
    x = x + 0.25f;
}

 private void render(GLAutoDrawable drawable) {
    GL2 gl = drawable.getGL().getGL2();
    GLU glu = new GLU();

    gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    //gl.glFrustum (.5f, -.5f, -.5f * 1080, .5f * 960, 1.f, 500.f);
    glu.gluPerspective(0, 1, 0.1f, 100f);

    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();
    gl.glHint(GL2.GL_CLIP_VOLUME_CLIPPING_HINT_EXT,GL2.GL_FASTEST);
    glu.gluLookAt(0, 0, 1.5, 0, 0, -10, 0, 1, 0);
    //gl.glRotatef(90, 0f , 1f , 0f );
    //Draw some scale lines
    gl.glBegin(GL.GL_LINES);
    gl.glColor3f(0.75f, 0.75f, 0.75f);
    for (int i = 0; i < 20; i += 1)
    {
        gl.glVertex3f(-5.0f, 0.0f, i + 0.5f);
        gl.glVertex3f(5.0f, 0.0f, i + 0.5f);
    }
    gl.glEnd();

    //gl.glRotatef(x, 1f , 1f , 1f );

    gl.glPushMatrix();
    gl.glTranslated(triforce.position.x, triforce.position.y, triforce.position.z);
    gl.glBegin(GL.GL_TRIANGLE_STRIP);
    gl.glColor3f(1f, 0f, 0f);
    gl.glVertex3d(0, 0, -2);
    gl.glColor3f(0f, 1f, 0f);
    gl.glVertex3d(0, 0.25d, -2);
    gl.glColor3f(0f, 0f, 1f);
    gl.glVertex3d(0.25d, 0, -2);
    gl.glColor3f(1f, 1f, 0f);
    gl.glVertex3d(0.25d, 0.25d, -2.25d);
    gl.glEnd();
    gl.glPopMatrix();

    gl.glFlush();
}
</code>```

// (empty overridden methods omitted)

```<code>public Particle () {
    setMass(200d);
    velocity = new Vector3(0d, 30d, 40d);
    acceleration = new Vector3(0d, -20d, 0d);
    position = new Vector3(0d, 0d, 0d);
    damping = 0.99d;
}

public void integrate (double duration) {
    if (inverseMass <= 0.0d) {
        return;
    }
    assert (duration > 0.0);
    position.addScaledVector(velocity, duration);
    Vector3 resultingAcc = new Vector3(acceleration.x, acceleration.y, acceleration.z);
    velocity.addScaledVector(resultingAcc, duration);
    velocity.multEquals(Math.pow(damping, duration));
    //clearAccumulator();
}

public void setMass(double mass)
{
    assert(mass != 0);
    inverseMass = (1.0d)/mass;
}
</code>```

Before movement / starting position:

The shape drifts upward and is obscured from the right and top, becoming invisible:

Any help would be greatly appreciated! Thanks!

答:
In the render function, change the value of last parameter of gluPerspective from 100f to 1000f. It will solve your problem.

```<code>gl.gluPerspective(0, 1, 0.1f, 100f);
</code>```

to

```<code>gl.gluPerspective(0, 1, 0.1f, 500f);
</code>```

And I think in your code you have done a mistake in the above line writing glu.gluperspective

I think it is gl.gluPerspective.

Body:
I'm trying to implement a basic physics engine in Java and I'm using the JOGL bindings so I can visualize the results. I can create and rotate shapes easily enough, but have run into problems whilst manipulating the viewport and whilst moving the shapes.

I don't think a clipping issue - I've tried using the gluPerspective method with a massive range (0.0001f - 10000f) with no success. When I move the camera further away from my objects or move the objects themselves, they disappear.

Tutorials about JOGL are few and far between and many also use different versions of OpenGL, so I turn to the only friend I have left: the wonderful users of stack overflow. :)

Flattery aside, the code follows:

public class JoglEventListener implements GLEventListener, KeyListener, MouseListener, MouseMotionListener {
// keep pointer to associated canvas so we can refresh the screen (equivalent to glutPostRedisplay())
public GLCanvas canvas;
public Particle triforce;
public float x;

// constructor
public JoglEventListener(GLCanvas canvas) {
    this.canvas = canvas;
}

@Override
public void display(GLAutoDrawable drawable) {
    update();
    render(drawable);
}

@Override
public void init(GLAutoDrawable drawable) {
    triforce = new Particle();
    x = 0;
}

private void update() {
    triforce.integrate(0.0001);
    x = x + 0.25f;
}

 private void render(GLAutoDrawable drawable) {
    GL2 gl = drawable.getGL().getGL2();
    GLU glu = new GLU();

    gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    //gl.glFrustum (.5f, -.5f, -.5f * 1080, .5f * 960, 1.f, 500.f);
    glu.gluPerspective(0, 1, 0.1f, 100f);

    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();
    gl.glHint(GL2.GL_CLIP_VOLUME_CLIPPING_HINT_EXT,GL2.GL_FASTEST);
    glu.gluLookAt(0, 0, 1.5, 0, 0, -10, 0, 1, 0);
    //gl.glRotatef(90, 0f , 1f , 0f );
    //Draw some scale lines
    gl.glBegin(GL.GL_LINES);
    gl.glColor3f(0.75f, 0.75f, 0.75f);
    for (int i = 0; i < 20; i += 1)
    {
        gl.glVertex3f(-5.0f, 0.0f, i + 0.5f);
        gl.glVertex3f(5.0f, 0.0f, i + 0.5f);
    }
    gl.glEnd();

    //gl.glRotatef(x, 1f , 1f , 1f );

    gl.glPushMatrix();
    gl.glTranslated(triforce.position.x, triforce.position.y, triforce.position.z);
    gl.glBegin(GL.GL_TRIANGLE_STRIP);
    gl.glColor3f(1f, 0f, 0f);
    gl.glVertex3d(0, 0, -2);
    gl.glColor3f(0f, 1f, 0f);
    gl.glVertex3d(0, 0.25d, -2);
    gl.glColor3f(0f, 0f, 1f);
    gl.glVertex3d(0.25d, 0, -2);
    gl.glColor3f(1f, 1f, 0f);
    gl.glVertex3d(0.25d, 0.25d, -2.25d);
    gl.glEnd();
    gl.glPopMatrix();

    gl.glFlush();
}

// (empty overridden methods omitted)

public Particle () {
    setMass(200d);
    velocity = new Vector3(0d, 30d, 40d);
    acceleration = new Vector3(0d, -20d, 0d);
    position = new Vector3(0d, 0d, 0d);
    damping = 0.99d;
}

public void integrate (double duration) {
    if (inverseMass <= 0.0d) {
        return;
    }
    assert (duration > 0.0);
    position.addScaledVector(velocity, duration);
    Vector3 resultingAcc = new Vector3(acceleration.x, acceleration.y, acceleration.z);
    velocity.addScaledVector(resultingAcc, duration);
    velocity.multEquals(Math.pow(damping, duration));
    //clearAccumulator();
}

public void setMass(double mass)
{
    assert(mass != 0);
    inverseMass = (1.0d)/mass;
}

Before movement / starting position:

The shape drifts upward and is obscured from the right and top, becoming invisible:

Any help would be greatly appreciated! Thanks!

Body:
In the render function, change the value of last parameter of gluPerspective from 100f to 1000f. It will solve your problem.

gl.gluPerspective(0, 1, 0.1f, 100f);

to

gl.gluPerspective(0, 1, 0.1f, 500f);

And I think in your code you have done a mistake in the above line writing glu.gluperspective

I think it is gl.gluPerspective.


问:
How to Convert String to Char and Integer in Java ?
I have the following :

String contain 5* ;

char opr ;

int data ;

I would like to store the 5 in the data and * in the opr

any idea how to do it ?
 as i know if the string contain only Integer then I will split and the parse it but in this case the String contain int and char

Input :

String input = 5* ;

I want the Output will be like this :

this.opr = *

this.data = 5

答:
Under the dubious assumption that the issue is parsing a String in the form of number followed by op, this code will achieve the desired result.

```<code>public static void main(String[] args)
{
    final String input = "5*";
    int data = -1;
    String op = "";

    Pattern pat = Pattern.compile("([\\d]+)[\\s]*(.*)");

    Matcher m = pat.matcher(input);
    if (m.matches() && m.groupCount() == 2) {
        data = Integer.parseInt(m.group(1));
        op = m.group(2).trim();
    }
    System.out.printf("%2d with op %s%n", data, op);
}
</code>```

Output:

5 with op *

Body:
Under the dubious assumption that the issue is parsing a String in the form of number followed by op, this code will achieve the desired result.

public static void main(String[] args)
{
    final String input = "5*";
    int data = -1;
    String op = "";

    Pattern pat = Pattern.compile("([\\d]+)[\\s]*(.*)");

    Matcher m = pat.matcher(input);
    if (m.matches() && m.groupCount() == 2) {
        data = Integer.parseInt(m.group(1));
        op = m.group(2).trim();
    }
    System.out.printf("%2d with op %s%n", data, op);
}

Output:

5 with op *


问:
converting to time series using ts() in r
Good afternoon

I have a time series

```<code>v2<-c(12,13,15,17,18,12,11,12)
</code>```

which run from July 1996 to October 1997, just the months between July and October

when I try to convert to time series with

```<code>v2.ts<-ts(v2, frequency=12, start=c(1996,7), end=c(1997,10))
</code>```

It yields me this result

```<code>    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1996                        12  13  15  17  18  12

1997 11  12  12  13  15  17  18  12  11  12
</code>```

what parameters can I use to make it like:

```<code>     Jul Aug Sep Oct
1996  12  13  15  17

1997  18  12  11  12
</code>```

Thanks in advance for the help

答:
A ts series must be regularly spaced but the output shown has points that are one month apart except between Oct of the first year and July of the second year so it is not of that form.

There are several packages that can represent irregularly spaced series.  With the zoo package it would be done like this:

```<code>library(zoo)

z <- as.zoo(v2.ts)
z[cycle(z) %in% 7:10]
## Jul 1996 Aug 1996 Sep 1996 Oct 1996 Jul 1997 Aug 1997 Sep 1997 Oct 1997
##      12       13       15       17       18       12       11       12
</code>```

If you are not looking for a time series but just a matrix with the indicated elements then:

```<code>tapply(c(v2.ts), list(floor(time(v2.ts)), cycle(v2.ts)), c)[, 7:10]

##       7  8  9 10
## 1996 12 13 15 17
## 1997 18 12 11 12
</code>```

Body:
Good afternoon

I have a time series

v2<-c(12,13,15,17,18,12,11,12)

which run from July 1996 to October 1997, just the months between July and October

when I try to convert to time series with

v2.ts<-ts(v2, frequency=12, start=c(1996,7), end=c(1997,10))

It yields me this result

    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1996                        12  13  15  17  18  12

1997 11  12  12  13  15  17  18  12  11  12

what parameters can I use to make it like:

     Jul Aug Sep Oct
1996  12  13  15  17

1997  18  12  11  12

Thanks in advance for the help

Body:
A ts series must be regularly spaced but the output shown has points that are one month apart except between Oct of the first year and July of the second year so it is not of that form.

There are several packages that can represent irregularly spaced series.  With the zoo package it would be done like this:

library(zoo)

z <- as.zoo(v2.ts)
z[cycle(z) %in% 7:10]
## Jul 1996 Aug 1996 Sep 1996 Oct 1996 Jul 1997 Aug 1997 Sep 1997 Oct 1997
##      12       13       15       17       18       12       11       12

If you are not looking for a time series but just a matrix with the indicated elements then:

tapply(c(v2.ts), list(floor(time(v2.ts)), cycle(v2.ts)), c)[, 7:10]

##       7  8  9 10
## 1996 12 13 15 17
## 1997 18 12 11 12


问:
Align inline ordered DIVs?
How do I align part of child divs inline if I use display: flex; flex-direction: column; for the paternal div?

I tried to use display: inline-block for the child divs, also float:left, but no one of this work.

#container {
  display: flex;
  flex-direction: column;
}
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
}
.item1 {
  order: 2;
}
.item2 {
  order: 1;
}
.item3 {
  order: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item1 item" >2</div>
  <div class="item2 item" >1</div>
  <div class="item3 item" >3</div>
</div></code>```

答:
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
  display: inline-block;
}
.item1 {
  order: 2;
  display: block;
}
.item2 {
  order: 1;
  float: left;
}
.item3 {
  order: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item1 item" >2</div>
  <div class="item2 item" >1</div>
  <div class="item3 item" >3</div>
</div></code>```

Title: Align inline ordered DIVs?

Body:
How do I align part of child divs inline if I use display: flex; flex-direction: column; for the paternal div?

I tried to use display: inline-block for the child divs, also float:left, but no one of this work.

#container {
  display: flex;
  flex-direction: column;
}
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
}
.item1 {
  order: 2;
}
.item2 {
  order: 1;
}
.item3 {
  order: 3;
}

2

1

3

Body:
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
  display: inline-block;
}
.item1 {
  order: 2;
  display: block;
}
.item2 {
  order: 1;
  float: left;
}
.item3 {
  order: 3;
}

<div id="container">
  <div class="item1 item" >2</div>
  <div class="item2 item" >1</div>
  <div class="item3 item" >3</div>
</div>


问:
Locating elements on pastebin bin selenoum (python)
I have been trying to do this one thing for a couple of hours now. Basicly I'm doing

```<code>driver.find_element_by_class_name('paste_code')
</code>```

but I keep getting unable to locate element or something like that. Now the website can be found here https://pastebin.com/ all I need is some ID of the pastebin box where u type stuff. These are the ID's that I would like to get (only need one) Name, ID, Class. Thats bassicly all I need I am very new to python and selenium please no hate. :)

答:
If you need to type something into textarea, you might use value of id attribute:

```<code>driver.find_element_by_id('paste_code').send_keys("some text")
</code>```

Note that "paste_code" is an id/name value, while class name value is "paste_textarea"

Body:
I have been trying to do this one thing for a couple of hours now. Basicly I'm doing

driver.find_element_by_class_name('paste_code')

but I keep getting unable to locate element or something like that. Now the website can be found here https://pastebin.com/ all I need is some ID of the pastebin box where u type stuff. These are the ID's that I would like to get (only need one) Name, ID, Class. Thats bassicly all I need I am very new to python and selenium please no hate. :)

Body:
If you need to type something into textarea, you might use value of id attribute:

driver.find_element_by_id('paste_code').send_keys("some text")

Note that "paste_code" is an id/name value, while class name value is "paste_textarea"


问:
Storing null values inside ArrayList and Set
```<code>class Employee
{
  int id;

  Employee(int id)
  {
    this.id = id;
  }

  public int getID()
  {
    return id;
  }

  public void displayID()
  {
    System.out.println("ID="+id);
  }
}

public class Example
{
  public static void main(String[] args)
  {

    Employee employee1 = new Employee(100);
    Employee employee3 = null;

    List<Employee> arrayListEx = new ArrayList<Employee>();
    Set<Employee> setEx = new HashSet<Employee>();

    arrayListEx.add(employee1);
    arrayListEx.add(employee3);
    setEx.add(employee1);
    setEx.add(employee3);

  }
}
</code>```

<p>Friends,
As per my understanding Set should not allow null values to get added to it.
Should the above code snippet throw compile time error for "setEx.add(employee3)" ?
Please advice, Thanks in advance. </p>

答:
From the Java Hashset documentation: "This class permits the null element". The file will compile.

You mentioned you believe that Set doesn't allow nulls. This depends on its implementation (link to docs)

Body:
class Employee
{
  int id;

  Employee(int id)
  {
    this.id = id;
  }

  public int getID()
  {
    return id;
  }

  public void displayID()
  {
    System.out.println("ID="+id);
  }
}

public class Example
{
  public static void main(String[] args)
  {

    Employee employee1 = new Employee(100);
    Employee employee3 = null;

    List<Employee> arrayListEx = new ArrayList<Employee>();
    Set<Employee> setEx = new HashSet<Employee>();

    arrayListEx.add(employee1);
    arrayListEx.add(employee3);
    setEx.add(employee1);
    setEx.add(employee3);

  }
}

Friends,
As per my understanding Set should not allow null values to get added to it.
Should the above code snippet throw compile time error for "setEx.add(employee3)" ?
Please advice, Thanks in advance.


问:
How can I process images with OpenCV 3.2 with CUDA?
How can I use gpu accelerated functions in OpenCV 3.2 with CUDA? What should be passed as a two first arguments into

```<code>void cv::cuda::bilateralFilter  (   InputArray      src,
        OutputArray     dst,
        int     kernel_size,
        float   sigma_color,
        float   sigma_spatial,
        int     borderMode = BORDER_DEFAULT,
        Stream &    stream = Stream::Null()
    )
</code>```

I think it should be type cv::Mat from imread function, but I'm not sure.

答:
Yes, a cv::Mat can be used as the first and second argument to that function.

InputArray is the proxy class for passing read-only input arrays into OpenCV functions. See InputArray

OutputArray is very similar to InputArray except that it is used for input/output and output function parameters. See OutputArray

Body:
How can I use gpu accelerated functions in OpenCV 3.2 with CUDA? What should be passed as a two first arguments into

void cv::cuda::bilateralFilter  (   InputArray      src,
        OutputArray     dst,
        int     kernel_size,
        float   sigma_color,
        float   sigma_spatial,
        int     borderMode = BORDER_DEFAULT,
        Stream &    stream = Stream::Null()
    )

I think it should be type cv::Mat from imread function, but I'm not sure.


问:
Can we store files in Chrome Storage, instead of strings
I could read in the Chrome storage API page that we can store string values inside Chrome storage against keys. Is there any way to store files against keys inside Chrome storage?  </p>

答:
chrome.storage stores data as the JSON stringification of the values which it's given to store. So, yes, if you convert your file(s) into a form that can be converted to JSON (e.g. by JSON.stringify()), then the contents of the file can be stored. If the value that you are trying to store in chrome.storage can not be converted to JSON, then it can't be stored (e.g. DOM elements). chrome.storage does not inherently care what the data represents, only that it can be JSON stringified.

If you're asking, as stated in your comment, if it's a good idea to store thousands of different "files" totaling more than 5GB in chrome.storage, then the answer is: "NO!".

If you are looking for alternatives, then some are provided in Can you use HTML5 local storage to store a file? If not, how?

ContentLicense: CC BY-SA 4.0