问:
How to deal with offsets in UIScrollView zooming for UIImageview?
Simply I have UIScrollView with one view for zooming inside that view: UIImageView.

This is how it looks when I just display the image:

When I pinch:

And when I swipe down after pinch:

And now I have black space I do not want to see. Is there a way to set some offsets and prevent from scrolling far after the image?

In code I simply use:

```<code>//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}
</code>```

答:
Simply implement UIScrollViewDelegate:

```<code>//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}

public func scrollViewDidZoom(_ scrollView: UIScrollView) {

    let imageViewSize = photoImageView.frame.size
    let scrollViewSize = scrollView.bounds.size

    let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
    let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0

    if verticalPadding >= 0 {
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
    } else {
        scrollView.contentSize = imageViewSize
    }
}
</code>```

and prepare view on viewDidLoad:

```<code>private func setupInitialView() {

    photoImageView.sizeToFit()

    let imageViewSize = photoImageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = min(widthScale, heightScale)
    scrollView.setZoomScale(scrollView.minimumZoomScale, animated: false)

    scrollViewDidZoom(scrollView)
}
</code>```

Body:
Simply I have UIScrollView with one view for zooming inside that view: UIImageView.

This is how it looks when I just display the image:

When I pinch:

And when I swipe down after pinch:

And now I have black space I do not want to see. Is there a way to set some offsets and prevent from scrolling far after the image?

In code I simply use:

//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}

Body:
Simply implement UIScrollViewDelegate:

//MARK: - UIScrollViewDelegate

public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return photoImageView
}

public func scrollViewDidZoom(_ scrollView: UIScrollView) {

    let imageViewSize = photoImageView.frame.size
    let scrollViewSize = scrollView.bounds.size

    let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
    let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0

    if verticalPadding >= 0 {
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
    } else {
        scrollView.contentSize = imageViewSize
    }
}

and prepare view on viewDidLoad:

private func setupInitialView() {

    photoImageView.sizeToFit()

    let imageViewSize = photoImageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = min(widthScale, heightScale)
    scrollView.setZoomScale(scrollView.minimumZoomScale, animated: false)

    scrollViewDidZoom(scrollView)
}


来源: stackexchange

问:
Replace div with another div (ASP.NET MVC)
I have PartialView

Here is code

```<code>  <div id="question1" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question1)
</div>
<div id="question2" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question2)
</div>
<div id="question3" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question3)
</div>
<div  id="question4" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question4)
</div>
</code>```

I call PartialView via AJAX

Code here:

```<code><script>
$(document).ready(function () {
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)

    $.ajax({
        type: "GET",
        url: "/interwier/QuestionBlock",
        data: { id: id },
        success: function (data) {
            $("#questions").html(data);

        },
        error: function () {
            alert("Smth wrong in controller");
        }
    });
});
</code>```

How I can display div with id=question1 when I click button replace it with div with id= question2? Button is not in PartialView.

Update

I decide to change logic and delete PartialView

I make code in div like this

```<code> <div id="questions" class="qustion-div-one">
        <div id="question1" style="font-size:20px; margin-bottom:10px;">
            @Html.DisplayFor(modelItem => Model.Question1)
        </div>
        <div id="question2" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question2)
        </div>
        <div id="question3" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question3)
        </div>
        <div id="question4" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question4)
        </div>
    </div>
</code>```

I need on button click make question1 hidden, and question2 visible, on next click question2 will be hidden and question3 visible and etc.

Or just simple remove question1 and change  for question2 etc.

How I can do this?

UPDATE 2

I try to do this script

```<code> $('#next').click(function () {
    $('#questions>div').toggle();
});
</code>```

but it opens all 3 divs, but i need question2 div

答:
you can do this many ways or you can also utilise the collapsible panels to show the questions.

Below is the simple approach to do this.

CSS class.

```<code>.inactive {  display:none; }

.active { display:block; }
</code>```

In html at the bottom add button

```<code><button id="next">Next</button>
</code>```

On page ready you need to write below code.

```<code>$(document).ready(function() {
    $('#questions div').attr( "class", "inactive" );
    $('#questions div:first-child').attr( "class", "active" );
});

$('#next').click(function() {
  var div = $('#questions div.active');
  div.attr("class", "inactive");
  if(div.next().length>0){
     div.next().attr( "class", "active");
  }
  else{
    $('#questions div:first-child').attr( "class", "active" );
  }
});
</code>```

live example: https://jsfiddle.net/a0du6u5d/1/

ContentLicense: CC BY-SA 3.0

Body:
I have PartialView

Here is code

    @Html.DisplayFor(modelItem => Model.Question1)

    @Html.DisplayFor(modelItem => Model.Question2)

    @Html.DisplayFor(modelItem => Model.Question3)

    @Html.DisplayFor(modelItem => Model.Question4)

I call PartialView via AJAX

Code here:

Body:
you can do this many ways or you can also utilise the collapsible panels to show the questions.

Below is the simple approach to do this.

CSS class.

.inactive {  display:none; }

.active { display:block; }

In html at the bottom add button

<button id="next">Next</button>

On page ready you need to write below code.

$(document).ready(function() {
    $('#questions div').attr( "class", "inactive" );
    $('#questions div:first-child').attr( "class", "active" );
});

$('#next').click(function() {
  var div = $('#questions div.active');
  div.attr("class", "inactive");
  if(div.next().length>0){
     div.next().attr( "class", "active");
  }
  else{
    $('#questions div:first-child').attr( "class", "active" );
  }
});

live example: https://jsfiddle.net/a0du6u5d/1/


问:
mod_fcgid with php opcode caching
I have been using apache web server with mpm-worker and mod_fcgid.

I have read about mod_fcgid that it can not make use of opcode caching.

http://www.brandonturner.net/blog/2009/07/fastcgi_with_php_opcode_cache/

apc cache module seems to be enabled in my php  configuration.

I am not sure if my spawned php codes are never shared.

Should I remove APC? Does it have any overhead?

答:
I am not sure if my spawned php codes are never shared.

You might find this question helpful.

Should I remove APC? Does it have any overhead?

As for the overhead, if you have n processes, then you'll have n caches.
It's not space efficient but it might still help reducing CPU cycles tho.

ContentLicense: CC BY-SA 2.5

Title: mod_fcgid with php opcode caching


问:
Load different layout in activity based on button clicked from fragment
I have 2 buttons in a fragment. I want to send intent to Activity from fragment and load a layout based on the button clicked. How can I achieve this?</p>

答:
Got a solution to this. Passing a string (using putExtra) to help decide which layout to be loaded.

Fragment Code:

```<code>Button button1 = (Button) rootView.findViewById(R.id.id_button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button1_pressed");
            (getActivity()).startActivity(intent);
        }
    });

    Button button2 = (Button) rootView.findViewById(R.id.id_button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button2_pressed");
            (getActivity()).startActivity(intent);
</code>```

Activity Code:

```<code>    final Intent intent = getIntent();
    final String data = intent.getStringExtra(EXTRA_DATA);

    if (data.equals("button1_pressed"))
    setContentView(R.layout.scrolling_details_button1);

    if (data.equals("button2_pressed"))
        setContentView(R.layout.scrolling_details_button2);
</code>```

Thanks!!

Body:
Got a solution to this. Passing a string (using putExtra) to help decide which layout to be loaded.

Fragment Code:

Button button1 = (Button) rootView.findViewById(R.id.id_button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button1_pressed");
            (getActivity()).startActivity(intent);
        }
    });

    Button button2 = (Button) rootView.findViewById(R.id.id_button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ScrollingDetailsActivity.class);
            intent.putExtra(ScrollingDetailsActivity.EXTRA_DATA,"Button2_pressed");
            (getActivity()).startActivity(intent);

Activity Code:

    final Intent intent = getIntent();
    final String data = intent.getStringExtra(EXTRA_DATA);

    if (data.equals("button1_pressed"))
    setContentView(R.layout.scrolling_details_button1);

    if (data.equals("button2_pressed"))
        setContentView(R.layout.scrolling_details_button2);

Thanks!!


问:
RED Robot Framework Editor - Unexpected error: NoClassDefFoundError: com/github/markusbernhardt/selenium2library/utils/WebDriverCache
Im using RED robot framework editor with Java. Though i have added the jar file that contains
'com/github/markusbernhardt/selenium2library/utils/WebDriverCache', it errors as "NoClassDefFoundError"

I use robotframework-selenium2library-java-1.4.0.8 for creating java library.

Below is the console command generated in RED editor.

```<code>Command: C:\jython2.7.0\bin\jython.exe -J-Dpython.path=C:\jython2.7.0\Lib\site-packages -J-cp .;C:\Java\JarsKCC\Misc.jar;C:\Java\JarsKCC\KCCUtils.jar;C:\Java\JarsKCC\GetElementList.jar;C:\jython2.7.0\selenium-server-standalone-3.3.1.jar;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8 -m robot.run -P C:\jython2.7.0\Lib\site-packages\Selenium2Library --listener C:\Users\CON_RT~1\AppData\Local\Temp\RobotTempDir2533122362618779828\TestRunnerAgent.py:56178:False -s KCC_Automation.TestSuites.TestSeparateWebdriverInstance C:\Java\Workspace\KCC_Automation
Suite Executor: Robot Framework 3.0.2 (Jython 2.7.0 on java1.8.0_121)
</code>```

Error received while execution is,

```<code>[ ERROR ] Unexpected error: NoClassDefFoundError:
com/github/markusbernhardt/selenium2library/utils/WebDriverCache
java.lang.NoClassDefFoundError:
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at robot.utils.importer$py.import_$32(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:274)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.utils.importer$py._import_class_or_module$5(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:77)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.utils.importer$py.import_class_or_module$4(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:74)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.model.itemlist$py.visit$11(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py:75)
at robot.model.itemlist$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.model.itemlist$py.visit$11(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py:75)
at robot.model.itemlist$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.utils.application$py._execute$10(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py:94)
at robot.utils.application$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py)
at robot.utils.application$py.execute_cli$5(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py:49)
at robot.utils.application$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py)
at runpy$py._run_code$9(C:\jython2.7.0\Lib\runpy.py:73)
at runpy$py.call_function(C:\jython2.7.0\Lib\runpy.py)
at runpy$py._run_module_as_main$14(C:\jython2.7.0\Lib\runpy.py:161)
at runpy$py.call_function(C:\jython2.7.0\Lib\runpy.py)
Caused by: java.lang.ClassNotFoundException:
com.github.markusbernhardt.selenium2library.utils.WebDriverCache
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 190 more
</code>```

Java code I used from this blog

Note: I also verified with the dependency jar file 'robotframework-selenium2library-java-1.4.0.8-jar-with-dependencies'. I still face the same issue.

答:
The examples in the 'blog' / stackoverflow post had some issues, with the key one being that the name of the class was changed since the answer was written on SO. However, when I compiled the jar file and added the jar file to the class path section of the red.xml none of the errors mentioned in the question were encountered. As the referred SO question had two approaches, I tried them both.

It appears to me that you have specified the directory and not the jar file for the robotframework-selenium2library-java-1.4.0.8.

```<code>C:\jython2.7.0\bin\jython.exe
-J-Dpython.path=C:\jython2.7.0\Lib\site-packages
-J-cp .
;C:\Java\JarsKCC\Misc.jar
;C:\Java\JarsKCC\KCCUtils.jar
;C:\Java\JarsKCC\GetElementList.jar
;C:\jython2.7.0\selenium-server-standalone-3.3.1.jar
;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8
-m robot.run
-P C:\jython2.7.0\Lib\site-packages\Selenium2Library
--listener C:\Users\CON_RT~1\AppData\ ... \TestRunnerAgent.py:56178:False
-s KCC_Automation.TestSuites.TestSeparateWebdriverInstance
C:\Java\Workspace\KCC_Automation
</code>```

So my advice is to change this so that the classpath reflects the jar file:
;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8\some-jar-name.jar

Body:
Im using RED robot framework editor with Java. Though i have added the jar file that contains
'com/github/markusbernhardt/selenium2library/utils/WebDriverCache', it errors as "NoClassDefFoundError"

I use robotframework-selenium2library-java-1.4.0.8 for creating java library.

Below is the console command generated in RED editor.

Command: C:\jython2.7.0\bin\jython.exe -J-Dpython.path=C:\jython2.7.0\Lib\site-packages -J-cp .;C:\Java\JarsKCC\Misc.jar;C:\Java\JarsKCC\KCCUtils.jar;C:\Java\JarsKCC\GetElementList.jar;C:\jython2.7.0\selenium-server-standalone-3.3.1.jar;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8 -m robot.run -P C:\jython2.7.0\Lib\site-packages\Selenium2Library --listener C:\Users\CON_RT~1\AppData\Local\Temp\RobotTempDir2533122362618779828\TestRunnerAgent.py:56178:False -s KCC_Automation.TestSuites.TestSeparateWebdriverInstance C:\Java\Workspace\KCC_Automation
Suite Executor: Robot Framework 3.0.2 (Jython 2.7.0 on java1.8.0_121)

Error received while execution is,

[ ERROR ] Unexpected error: NoClassDefFoundError:
com/github/markusbernhardt/selenium2library/utils/WebDriverCache
java.lang.NoClassDefFoundError:
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at robot.utils.importer$py.import_$32(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:274)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.utils.importer$py._import_class_or_module$5(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:77)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.utils.importer$py.import_class_or_module$4(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py:74)
at robot.utils.importer$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\importer.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.model.itemlist$py.visit$11(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py:75)
at robot.model.itemlist$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.model.itemlist$py.visit$11(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py:75)
at robot.model.itemlist$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\itemlist.py)
at robot.model.visitor$py.visit_suite$2(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py:88)
at robot.model.visitor$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\visitor.py)
at robot.model.testsuite$py.visit$19(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py:161)
at robot.model.testsuite$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\model\testsuite.py)
at robot.utils.application$py._execute$10(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py:94)
at robot.utils.application$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py)
at robot.utils.application$py.execute_cli$5(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py:49)
at robot.utils.application$py.call_function(C:\jython2.7.0\Lib\site-packages\robot\utils\application.py)
at runpy$py._run_code$9(C:\jython2.7.0\Lib\runpy.py:73)
at runpy$py.call_function(C:\jython2.7.0\Lib\runpy.py)
at runpy$py._run_module_as_main$14(C:\jython2.7.0\Lib\runpy.py:161)
at runpy$py.call_function(C:\jython2.7.0\Lib\runpy.py)
Caused by: java.lang.ClassNotFoundException:
com.github.markusbernhardt.selenium2library.utils.WebDriverCache
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 190 more

Java code I used from this blog

Note: I also verified with the dependency jar file 'robotframework-selenium2library-java-1.4.0.8-jar-with-dependencies'. I still face the same issue.

Body:
The examples in the 'blog' / stackoverflow post had some issues, with the key one being that the name of the class was changed since the answer was written on SO. However, when I compiled the jar file and added the jar file to the class path section of the red.xml none of the errors mentioned in the question were encountered. As the referred SO question had two approaches, I tried them both.

It appears to me that you have specified the directory and not the jar file for the robotframework-selenium2library-java-1.4.0.8.

C:\jython2.7.0\bin\jython.exe
-J-Dpython.path=C:\jython2.7.0\Lib\site-packages
-J-cp .
;C:\Java\JarsKCC\Misc.jar
;C:\Java\JarsKCC\KCCUtils.jar
;C:\Java\JarsKCC\GetElementList.jar
;C:\jython2.7.0\selenium-server-standalone-3.3.1.jar
;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8
-m robot.run
-P C:\jython2.7.0\Lib\site-packages\Selenium2Library
--listener C:\Users\CON_RT~1\AppData\ ... \TestRunnerAgent.py:56178:False
-s KCC_Automation.TestSuites.TestSeparateWebdriverInstance
C:\Java\Workspace\KCC_Automation

So my advice is to change this so that the classpath reflects the jar file:
;C:\jython2.7.0\robotframework-selenium2library-java-1.4.0.8\some-jar-name.jar


问:
Get selected row of angularjs ui-grid
I've looked at multiple articles on this ui-grid and its giving me fits.  I'm trying to get the selected row object.  I'm either getting an undefined or can not read property of 'getSelectedRows'.  Any help is greatly appreciated.

I started with this article here and the documentation doesnt seem to be all that great either.

Here is my code:

```<code>        vm.gridOptions = {
        enableRowSelection: false,
        enableSelectAll: false,
        showGridFooter:true

    };

    vm.gridOptions.columnDefs = [
        { name: 'productName' },
        { name: 'unitPrice' }
    ];

    vm.gridOptions.multiSelect = false;

    vm.getSelectedRows = function () {
        vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();
    }

     productDataService.getProductList()
         .then(function (result) {
             vm.gridOptions.data = result.data;
             vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();<--Property undefined error here
             $timeout(function() {
                 if (vm.gridApi.selection.selectedRow) {
                     vm.gridApi.selection.selectRow(vm.gridOptions.data[0]);
                 }
             });
         });

    vm.gridOptions.onRegisterApi = function(gridApi) {
        vm.gridApi = gridApi;
    }
</code>```

答:
Hope this helps:

angular.module('app', ['ui.grid', 'ui.grid.selection'])
  .controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    var vm = this;
    vm.gridOptions = {
      enableRowSelection: false,
      enableSelectAll: false,
      showGridFooter:true,
      data: [{productName: "Moroni", unitPrice: 50},
             {productName: "Tiancum", unitPrice: 43},
             {productName: "Jacob", unitPrice: 27},
             {productName: "Nephi", unitPrice: 29},
             {productName: "Enos", unitPrice: 34}]
    };
    vm.gridOptions.columnDefs = [
        { name: 'productName' },
        { name: 'unitPrice' }
    ];
    vm.gridOptions.multiSelect = false;
    vm.getSelectedRows = function () {
        vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();
    }
    vm.getProductList = function() {
      vm.gridOptions.data = vm.resultSimulatedData;
      vm.mySelectedRows = vm.gridApi.selection.getSelectedRows(); //<--Property undefined error here
      if (vm.mySelectedRows[0]) {
        alert('Selected Row: ' + vm.mySelectedRows[0].productName + ', ' + vm.mySelectedRows[0].unitPrice + '.');
      } else {
        alert('Select a row first');
      }
      $timeout(function() {
          if (vm.gridApi.selection.selectedRow) {
              vm.gridApi.selection.selectRow(vm.gridOptions.data[0]);
          }
      });
    };
    vm.gridOptions.onRegisterApi = function(gridApi) {
      vm.gridApi = gridApi;
    };
    vm.resultSimulatedData = [{productName: "Moroni1", unitPrice: 50},
                               {productName: "Tiancum1", unitPrice: 43},
                               {productName: "Jacob1", unitPrice: 27},
                               {productName: "Nephi1", unitPrice: 29},
                               {productName: "Enos1", unitPrice: 34}];
    return vm;
  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.css" />
<div ng-app="app" ng-controller="MainCtrl as vm">
  <button ng-click="vm.getProductList()">Get Product List</button>
  <div ui-grid="vm.gridOptions" ui-grid-selection class="gridStyle">
  </div>
</div></code>```

If you can share more of your code that might help me to further help you.

Title: Get selected row of angularjs ui-grid

Body:
I've looked at multiple articles on this ui-grid and its giving me fits.  I'm trying to get the selected row object.  I'm either getting an undefined or can not read property of 'getSelectedRows'.  Any help is greatly appreciated.

I started with this article here and the documentation doesnt seem to be all that great either.

Here is my code:

        vm.gridOptions = {
        enableRowSelection: false,
        enableSelectAll: false,
        showGridFooter:true

    };

    vm.gridOptions.columnDefs = [
        { name: 'productName' },
        { name: 'unitPrice' }
    ];

    vm.gridOptions.multiSelect = false;

    vm.getSelectedRows = function () {
        vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();
    }

     productDataService.getProductList()
         .then(function (result) {
             vm.gridOptions.data = result.data;
             vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();<--Property undefined error here
             $timeout(function() {
                 if (vm.gridApi.selection.selectedRow) {
                     vm.gridApi.selection.selectRow(vm.gridOptions.data[0]);
                 }
             });
         });

    vm.gridOptions.onRegisterApi = function(gridApi) {
        vm.gridApi = gridApi;
    }

Body:
Hope this helps:

angular.module('app', ['ui.grid', 'ui.grid.selection'])
  .controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    var vm = this;
    vm.gridOptions = {
      enableRowSelection: false,
      enableSelectAll: false,
      showGridFooter:true,
      data: [{productName: "Moroni", unitPrice: 50},
             {productName: "Tiancum", unitPrice: 43},
             {productName: "Jacob", unitPrice: 27},
             {productName: "Nephi", unitPrice: 29},
             {productName: "Enos", unitPrice: 34}]
    };
    vm.gridOptions.columnDefs = [
        { name: 'productName' },
        { name: 'unitPrice' }
    ];
    vm.gridOptions.multiSelect = false;
    vm.getSelectedRows = function () {
        vm.mySelectedRows = vm.gridApi.selection.getSelectedRows();
    }
    vm.getProductList = function() {
      vm.gridOptions.data = vm.resultSimulatedData;
      vm.mySelectedRows = vm.gridApi.selection.getSelectedRows(); //<--Property undefined error here
      if (vm.mySelectedRows[0]) {
        alert('Selected Row: ' + vm.mySelectedRows[0].productName + ', ' + vm.mySelectedRows[0].unitPrice + '.');
      } else {
        alert('Select a row first');
      }
      $timeout(function() {
          if (vm.gridApi.selection.selectedRow) {
              vm.gridApi.selection.selectRow(vm.gridOptions.data[0]);
          }
      });
    };
    vm.gridOptions.onRegisterApi = function(gridApi) {
      vm.gridApi = gridApi;
    };
    vm.resultSimulatedData = [{productName: "Moroni1", unitPrice: 50},
                               {productName: "Tiancum1", unitPrice: 43},
                               {productName: "Jacob1", unitPrice: 27},
                               {productName: "Nephi1", unitPrice: 29},
                               {productName: "Enos1", unitPrice: 34}];
    return vm;
  }]);

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.css" />
<div ng-app="app" ng-controller="MainCtrl as vm">
  <button ng-click="vm.getProductList()">Get Product List</button>
  <div ui-grid="vm.gridOptions" ui-grid-selection class="gridStyle">
  </div>
</div>

If you can share more of your code that might help me to further help you.


问:
Creating a Javascript API for a GWT application
All the GWT examples/tutorials talk about GWT client-side code being activated by events such as onPageLoad(). I want to use GWT to create a library that can be invoked by user-written Javascript function calls. Can anyone point me to the information needed to do this?</p>

答:
Thanks for your contributions.

gwt-exporter looks useful in theory, but so far I've failed to get it to work - it seems to be a fine piece of software ruined by poor documentation.

But I think I can probably do what I need using JSNI "by hand", now I'm starting to understand the architecture better.


问:
Return Collection after update()?
Using Raw, how to return collection of updated row?

For example:

```<code>$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
</code>```

I was expecting dd($updated) to return updated row of collection but it returned 1.

```<code>{{$updated->votes}} should return 123
</code>```

答:
That's not how it works. You can't expect this query will return you an object:

```<code>$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
</code>```

If you want to use Query Builder only as you mentioned in your question, you'll need to get an object manually:

```<code>$data = DB::table('users')->where('id', 1)->first();
</code>```

With Eloquent you can use the updateOrCreate():

```<code>$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);
</code>```

This will return an object. update() will return boolean, so you can't use it here.

Title: Return Collection after update()?

Body:
Using Raw, how to return collection of updated row?

For example:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

I was expecting dd($updated) to return updated row of collection but it returned 1.

{{$updated->votes}} should return 123

Body:
That's not how it works. You can't expect this query will return you an object:

$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);

If you want to use Query Builder only as you mentioned in your question, you'll need to get an object manually:

$data = DB::table('users')->where('id', 1)->first();

With Eloquent you can use the updateOrCreate():

$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);

This will return an object. update() will return boolean, so you can't use it here.


问:
Restrict java to only execute signed jars?
Java jars can be signed with the JDK jarsigner tool.  This, in conjuction with the policytool,  appears to only allow you to add privileges to the jar when it is run.  I would like a default "Revoke access to run."  Is it possible to make java do white-listing in such a way that only jar files that have been signed by a certain set of certificates are allowed to run at all?</p>

答:
If this is for a browser based application, this can be accomplished using a deployment rule set.

https://blogs.oracle.com/java-platform-group/entry/introducing_deployment_rule_sets

http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/security/deployment_rules.html


问:
NodeJS & ExpressJS: How to store user info in session after logged in?
I did lot of research but I am new on this, I couldn't find something concrete.
When a user is logged-in I would like to store some user info in session like Name, Profile_picture, Id, so I can use it for example in the navigation bar.

How can I achieve this?

For example in PHP is too easy just adding this line of code the information stays in what ever page you visit (before session expire)

```<code>session_start();
$_SESSION['user_id']
</code>```

答:
You can use express-session or cookie-session(https://www.npmjs.com/package/cookie-session)

If you use cookie session & you made any change session variable or in server side, then no need to restart server.

It will help you to increase your development speed, because you, no need to restart server.

```<code>app.use(cookieSession({
 name: 'session',
 keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})
</code>```

Body:
I did lot of research but I am new on this, I couldn't find something concrete.
When a user is logged-in I would like to store some user info in session like Name, Profile_picture, Id, so I can use it for example in the navigation bar.

How can I achieve this?

For example in PHP is too easy just adding this line of code the information stays in what ever page you visit (before session expire)

session_start();
$_SESSION['user_id']

Body:
You can use express-session or cookie-session(https://www.npmjs.com/package/cookie-session)

If you use cookie session & you made any change session variable or in server side, then no need to restart server.

It will help you to increase your development speed, because you, no need to restart server.

app.use(cookieSession({
 name: 'session',
 keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})


问:
Why use the SQL Server 2008 geography data type?
I am redesigning a customer database and one of the new pieces of information I would like to store along with the standard address fields (Street, City, etc.) is the geographic location of the address.  The only use case I have in mind is to allow users to map the coordinates on Google maps when the address cannot otherwise be found, which often happens when the area is newly developed, or is in a remote/rural location.

My first inclination was to store latitude and longitude as decimal values, but then I remembered that SQL Server 2008 R2 has a geography data type.  I have absolutely no experience using geography, and from my initial research, it looks to be overkill for my scenario.

For example, to work with latitude and longitude stored as decimal(7,4), I can do this:

```<code>insert into Geotest(Latitude, Longitude) values (47.6475, -122.1393)
select Latitude, Longitude from Geotest
</code>```

but with geography, I would do this:

```<code>insert into Geotest(Geolocation) values (geography::Point(47.6475, -122.1393, 4326))
select Geolocation.Lat, Geolocation.Long from Geotest
</code>```

Although it's not that much more complicated, why add complexity if I don't have to?

Before I abandon the idea of using geography, is there anything I should consider?  Would it be faster to search for a location using a spatial index vs. indexing the Latitude and Longitude fields?  Are there advantages to using geography that I am not aware of?  Or, on the flip side, are there caveats that I should know about which would discourage me from using geography?

Update

@Erik Philips brought up the ability to do proximity searches with geography, which is very cool.

On the other hand, a quick test is showing that a simple select to get the latitude and longitude is significantly slower when using geography (details below).  , and a comment on the accepted answer to another SO question on geography has me leery:

@SaphuA You're welcome. As a sidenote be VERY carefull of using a
  spatial index on a nullable GEOGRAPHY datatype column. There are some
  serious performance issue, so make that GEOGRAPHY column non-nullable
  even if you have to remodel your schema. – Tomas Jun 18 at 11:18

All in all, weighing the likelihood of doing proximity searches vs. the trade-off in performance and complexity, I've decided to forgo the use of geography in this case.

Details of the test I ran:

I created two tables, one using geography and another using decimal(9,6) for latitude and longitude:

```<code>CREATE TABLE [dbo].[GeographyTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Location] [geography] NOT NULL,
    CONSTRAINT [PK_GeographyTest] PRIMARY KEY CLUSTERED ( [RowId] ASC )
)

CREATE TABLE [dbo].[LatLongTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Latitude] [decimal](9, 6) NULL,
    [Longitude] [decimal](9, 6) NULL,
    CONSTRAINT [PK_LatLongTest] PRIMARY KEY CLUSTERED ([RowId] ASC)
)
</code>```

and inserted a single row using the same latitude and longitude values into each table:

```<code>insert into GeographyTest(Location) values (geography::Point(47.6475, -122.1393, 4326))
insert into LatLongTest(Latitude, Longitude) values (47.6475, -122.1393)
</code>```

Finally, running the following code shows that, on my machine, selecting the latitude and longitude is approximately 5 times slower when using geography.

```<code>declare @lat float, @long float,
        @d datetime2, @repCount int, @trialCount int,
        @geographyDuration int, @latlongDuration int,
        @trials int = 3, @reps int = 100000

create table #results
(
    GeographyDuration int,
    LatLongDuration int
)

set @trialCount = 0

while @trialCount < @trials
begin

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Location.Lat,  @long = Location.Long from GeographyTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @geographyDuration = datediff(ms, @d, sysdatetime())

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Latitude,  @long = Longitude from LatLongTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @latlongDuration = datediff(ms, @d, sysdatetime())

    insert into #results values(@geographyDuration, @latlongDuration)

    set @trialCount = @trialCount + 1

end

select *
from #results

select avg(GeographyDuration) as AvgGeographyDuration, avg(LatLongDuration) as AvgLatLongDuration
from #results

drop table #results
</code>```

Results:

```<code>GeographyDuration LatLongDuration
----------------- ---------------
5146              1020
5143              1016
5169              1030

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
5152                 1022
</code>```

What was more surprising is that even when no rows are selected, for example selecting where RowId = 2, which doesn't exist, geography was still slower:

```<code>GeographyDuration LatLongDuration
----------------- ---------------
1607              948
1610              946
1607              947

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
1608                 947
</code>```

答:
```<code>    CREATE FUNCTION [dbo].[fn_GreatCircleDistance]
(@Latitude1 As Decimal(38, 19), @Longitude1 As Decimal(38, 19),
            @Latitude2 As Decimal(38, 19), @Longitude2 As Decimal(38, 19),
            @ValuesAsDecimalDegrees As bit = 1,
            @ResultAsMiles As bit = 0)
RETURNS decimal(38,19)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar  decimal(38,19)

    -- Add the T-SQL statements to compute the return value here
/*
Credit for conversion algorithm to Chip Pearson
Web Page: www.cpearson.com/excel/latlong.aspx
Email: chip@cpearson.com
Phone: (816) 214-6957 USA Central Time (-6:00 UTC)
Between 9:00 AM and 7:00 PM

Ported to Transact SQL by Paul Burrows BCIS
*/
DECLARE  @C_RADIUS_EARTH_KM As Decimal(38, 19)
SET @C_RADIUS_EARTH_KM = 6370.97327862
DECLARE  @C_RADIUS_EARTH_MI As Decimal(38, 19)
SET @C_RADIUS_EARTH_MI = 3958.73926185
DECLARE  @C_PI As Decimal(38, 19)
SET @C_PI =  pi()

DECLARE @Lat1 As Decimal(38, 19)
DECLARE @Lat2 As Decimal(38, 19)
DECLARE @Long1 As Decimal(38, 19)
DECLARE @Long2 As Decimal(38, 19)
DECLARE @X As bigint
DECLARE @Delta As Decimal(38, 19)

If @ValuesAsDecimalDegrees = 1
Begin
    set @X = 1
END
Else
Begin
    set @X = 24
End

-- convert to decimal degrees
set @Lat1 = @Latitude1 * @X
set @Long1 = @Longitude1 * @X
set @Lat2 = @Latitude2 * @X
set @Long2 = @Longitude2 * @X

-- convert to radians: radians = (degrees/180) * PI
set @Lat1 = (@Lat1 / 180) * @C_PI
set @Lat2 = (@Lat2 / 180) * @C_PI
set @Long1 = (@Long1 / 180) * @C_PI
set @Long2 = (@Long2 / 180) * @C_PI

-- get the central spherical angle
set @Delta = ((2 * ASin(Sqrt((power(Sin((@Lat1 - @Lat2) / 2) ,2)) +
    Cos(@Lat1) * Cos(@Lat2) * (power(Sin((@Long1 - @Long2) / 2) ,2))))))

If @ResultAsMiles = 1
Begin
    set @ResultVar = @Delta * @C_RADIUS_EARTH_MI
End
Else
Begin
    set @ResultVar = @Delta * @C_RADIUS_EARTH_KM
End

    -- Return the result of the function
    RETURN @ResultVar

END
</code>```

Body:
I am redesigning a customer database and one of the new pieces of information I would like to store along with the standard address fields (Street, City, etc.) is the geographic location of the address.  The only use case I have in mind is to allow users to map the coordinates on Google maps when the address cannot otherwise be found, which often happens when the area is newly developed, or is in a remote/rural location.

My first inclination was to store latitude and longitude as decimal values, but then I remembered that SQL Server 2008 R2 has a geography data type.  I have absolutely no experience using geography, and from my initial research, it looks to be overkill for my scenario.

For example, to work with latitude and longitude stored as decimal(7,4), I can do this:

insert into Geotest(Latitude, Longitude) values (47.6475, -122.1393)
select Latitude, Longitude from Geotest

but with geography, I would do this:

insert into Geotest(Geolocation) values (geography::Point(47.6475, -122.1393, 4326))
select Geolocation.Lat, Geolocation.Long from Geotest

Although it's not that much more complicated, why add complexity if I don't have to?

Before I abandon the idea of using geography, is there anything I should consider?  Would it be faster to search for a location using a spatial index vs. indexing the Latitude and Longitude fields?  Are there advantages to using geography that I am not aware of?  Or, on the flip side, are there caveats that I should know about which would discourage me from using geography?

Update

@Erik Philips brought up the ability to do proximity searches with geography, which is very cool.

On the other hand, a quick test is showing that a simple select to get the latitude and longitude is significantly slower when using geography (details below).  , and a comment on the accepted answer to another SO question on geography has me leery:

@SaphuA You're welcome. As a sidenote be VERY carefull of using a
  spatial index on a nullable GEOGRAPHY datatype column. There are some
  serious performance issue, so make that GEOGRAPHY column non-nullable
  even if you have to remodel your schema. – Tomas Jun 18 at 11:18

All in all, weighing the likelihood of doing proximity searches vs. the trade-off in performance and complexity, I've decided to forgo the use of geography in this case.

Details of the test I ran:

I created two tables, one using geography and another using decimal(9,6) for latitude and longitude:

CREATE TABLE [dbo].[GeographyTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Location] [geography] NOT NULL,
    CONSTRAINT [PK_GeographyTest] PRIMARY KEY CLUSTERED ( [RowId] ASC )
)

CREATE TABLE [dbo].[LatLongTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Latitude] [decimal](9, 6) NULL,
    [Longitude] [decimal](9, 6) NULL,
    CONSTRAINT [PK_LatLongTest] PRIMARY KEY CLUSTERED ([RowId] ASC)
)

and inserted a single row using the same latitude and longitude values into each table:

insert into GeographyTest(Location) values (geography::Point(47.6475, -122.1393, 4326))
insert into LatLongTest(Latitude, Longitude) values (47.6475, -122.1393)

Finally, running the following code shows that, on my machine, selecting the latitude and longitude is approximately 5 times slower when using geography.

declare @lat float, @long float,
        @d datetime2, @repCount int, @trialCount int,
        @geographyDuration int, @latlongDuration int,
        @trials int = 3, @reps int = 100000

create table #results
(
    GeographyDuration int,
    LatLongDuration int
)

set @trialCount = 0

while @trialCount < @trials
begin

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Location.Lat,  @long = Location.Long from GeographyTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @geographyDuration = datediff(ms, @d, sysdatetime())

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Latitude,  @long = Longitude from LatLongTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @latlongDuration = datediff(ms, @d, sysdatetime())

    insert into #results values(@geographyDuration, @latlongDuration)

    set @trialCount = @trialCount + 1

end

select *
from #results

select avg(GeographyDuration) as AvgGeographyDuration, avg(LatLongDuration) as AvgLatLongDuration
from #results

drop table #results

Results:

GeographyDuration LatLongDuration
----------------- ---------------
5146              1020
5143              1016
5169              1030

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
5152                 1022

What was more surprising is that even when no rows are selected, for example selecting where RowId = 2, which doesn't exist, geography was still slower:

GeographyDuration LatLongDuration
----------------- ---------------
1607              948
1610              946
1607              947

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
1608                 947


问:
jquery mobile menu to close after i click a menu item
based on this demo: http://webdesignerwall.com/demo/mobile-nav/ this is my code.

```<code><script type="text/javascript">
    jQuery(document).ready(function($){

        /* prepend menu icon */
        $('#nav-wrap').prepend('<div id="menu-icon"><img id="logo" src="<?php echo site_url(); ?>/wp-content/themes/blue-and-grey/images/mobileimages/hme_btn.png" /></div>');

        /* toggle nav */
        $("#menu-icon").on("click", function(){
            $("#nav").slideToggle();
            $(this).toggleClass("active");
        });

    });
    </script>
</code>```

what i need is the menu to "close" after i click a menu item because it's a single page website, and i don't want it to stay opened after i clicked. how do i do that?

thank you so much!

答: you can use $( "#nav" ).panel( "close" );

Body:
based on this demo: http://webdesignerwall.com/demo/mobile-nav/ this is my code.

what i need is the menu to "close" after i click a menu item because it's a single page website, and i don't want it to stay opened after i clicked. how do i do that?

thank you so much!


问:
FB SDK produces a PHP Fatal error
First noticed [27-Mar-2017 17:47:16 GMT+0] a FB SDK integration that worked very well allowing people to login to our site via their Facebook account just stopped working. The server logs show the following error

```<code>PHP Fatal error:  Cannot use object of type stdClass as array in fb-sdk/FacebookRedirectLoginHelper.php on line 191
</code>```

We have not done any relevant code change that should have initiated it.
Have we missed an upgrade?

答:
Better solution is to migrate to SDK 5
https://developers.facebook.com/docs/php/howto/example_facebook_login</p>

Title: FB SDK produces a PHP Fatal error

Body:
First noticed [27-Mar-2017 17:47:16 GMT+0] a FB SDK integration that worked very well allowing people to login to our site via their Facebook account just stopped working. The server logs show the following error

PHP Fatal error:  Cannot use object of type stdClass as array in fb-sdk/FacebookRedirectLoginHelper.php on line 191

We have not done any relevant code change that should have initiated it.
Have we missed an upgrade?


问:
How to call protected constructor in c#?
How to call protected constructor?

```<code>public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???
</code>```

This obviously fails test:

```<code>public class FooMock:Foo{}
var foo=new FooMock();
Assert(typeof(Foo), foo.GetType());
</code>```

答:
may be this will help:

abstract parent class:

```<code> public abstract class Animal
    {

        private string name;

        public Animal(string name)
        {

            this.Name = name;
        }

        public Animal() { }
        public string Name
        {

            get { return this.name; }

            set { this.name = value; }

        }

        public virtual void talk()
        {

            Console.WriteLine("Hi,I am  an animal");

        }

    }
</code>```

class with protected constructor:

```<code>public class Lion : Animal
    {
        private string yahoo;

        protected Lion(string name) : base(name)
        {

            this.Yahoo = "Yahoo!!!";
        }

        public string Yahoo
        {
            get
            {
                return yahoo;
            }

            set
            {
                yahoo = value;
            }
        }

        public Lion() { }
    }
</code>```

class Kiara derived from Lion class :

```<code> public class Kiara : Lion
    {

        public Kiara(string name) : base(name)
        {

        }

        public override void talk()
        {

            Console.WriteLine("HRRRR I'm a Kiara");

        }

        public Kiara() { }

    }
</code>```

class Simba derived from Lion class :

```<code>    public class Simba : Lion
    {

        public Simba(string name) : base(name)
        {

        }

        public override void talk()
        {

            Console.WriteLine("HRRRR I'm a {0}  and this is my daughter:{1} {2}",
            new Simba("Simba").Name,
            new Kiara("Kiara").Name,
            new Simba("Simba").Yahoo);
        }

        public Simba() { }

    }
</code>```

implementation in main function:

```<code>       public static void Main(string[] args)
        {

            Animal lion = new Simba();
            lion.Name = "Simba";
            lion.talk();
            Animal lion1 = new Kiara();
            lion1.Name = "Kiara";
            lion1.talk();
        }
</code>```

Body:
How to call protected constructor?

public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???

This obviously fails test:

public class FooMock:Foo{}
var foo=new FooMock();
Assert(typeof(Foo), foo.GetType());

Body:
may be this will help:

abstract parent class:

 public abstract class Animal
    {

        private string name;

        public Animal(string name)
        {

            this.Name = name;
        }

        public Animal() { }
        public string Name
        {

            get { return this.name; }

            set { this.name = value; }

        }

        public virtual void talk()
        {

            Console.WriteLine("Hi,I am  an animal");

        }

    }

class with protected constructor:

public class Lion : Animal
    {
        private string yahoo;

        protected Lion(string name) : base(name)
        {

            this.Yahoo = "Yahoo!!!";
        }

        public string Yahoo
        {
            get
            {
                return yahoo;
            }

            set
            {
                yahoo = value;
            }
        }

        public Lion() { }
    }

class Kiara derived from Lion class :

 public class Kiara : Lion
    {

        public Kiara(string name) : base(name)
        {

        }

        public override void talk()
        {

            Console.WriteLine("HRRRR I'm a Kiara");

        }

        public Kiara() { }

    }

class Simba derived from Lion class :

    public class Simba : Lion
    {

        public Simba(string name) : base(name)
        {

        }

        public override void talk()
        {

            Console.WriteLine("HRRRR I'm a {0}  and this is my daughter:{1} {2}",
            new Simba("Simba").Name,
            new Kiara("Kiara").Name,
            new Simba("Simba").Yahoo);
        }

        public Simba() { }

    }

implementation in main function:

       public static void Main(string[] args)
        {

            Animal lion = new Simba();
            lion.Name = "Simba";
            lion.talk();
            Animal lion1 = new Kiara();
            lion1.Name = "Kiara";
            lion1.talk();
        }


问:
Fortran 77 conversion to C++
I have a Fortran 77 application that uses Common declarations to "share" memory variables.  Back in the day, when memory was expensive and hard to come by this was the way around it.

The equipment being controlled sets status flags.  These flags reside in these Common variables.

Any suggestions on how to implement the Common functionality in c++?

A class perhaps, with all the common variables being public.  Thus any program instantiating that class will have access to the contents of the Common variables.

Are there any tutorials/guidelines for converting Fortran to C or C++?

Thanks

答:
First of all, you can get rid of common blocks by using Fortran 90 modules.

If you do want to directly convert common blocks to C++ you would have to make a whole bunch of global/static variables or use an unnamed namespace.

However, that violates information hiding and most people would advise you against thoughtless use of global variables.

More generally, you might be interested in looking up the Barton-Nackman book Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples. It's a bit outdated, but that shouldn't matter too much. It teaches you C++ for scientific or engineering applications assuming that you have a Fortran / procedural background.

Title: Fortran 77 conversion to C++


问:
vlcj webcam stream in java
I am trying to make a simple program that will live stream from my webcam.

```<code>public static void main(String[] args) throws Exception
{
    int port = nextAvailable();
    //String media = "/root/Desktop/525600.mp4";
    String media = "/dev/video0";
    String[] options = {":sout=#duplicate{dst=rtp{sdp=rtsp://:"+port+"/stream},dst=display}", ":sout-all", ":sout-keep"};
    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(args);
    HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
    mediaPlayer.playMedia(media,options);
    System.out.println("Using port: "+port);
    Thread.currentThread().join();
}
</code>```

if I use the commented media (/root/Desktop/525600.mp4), the stream works without any issues. However, I do not know how to stream from the webcam. I tried /dev/video0 but it gives the following errors:

[00007fae70008f78] core access error: read error: Invalid argument

[00007fae70008f78] filesystem access error: read error: Invalid
  argument

[00007fae7000d3d8] core stream error: cannot pre fill buffer

What am I doing wrong?

答:
Simply replaced

```<code>String media = "/dev/video0";
</code>```

with

```<code>String media = "v4l2:///dev/video0";
</code>```

and it works now.

Title: vlcj webcam stream in java

Body:
I am trying to make a simple program that will live stream from my webcam.

public static void main(String[] args) throws Exception
{
    int port = nextAvailable();
    //String media = "/root/Desktop/525600.mp4";
    String media = "/dev/video0";
    String[] options = {":sout=#duplicate{dst=rtp{sdp=rtsp://:"+port+"/stream},dst=display}", ":sout-all", ":sout-keep"};
    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(args);
    HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
    mediaPlayer.playMedia(media,options);
    System.out.println("Using port: "+port);
    Thread.currentThread().join();
}

if I use the commented media (/root/Desktop/525600.mp4), the stream works without any issues. However, I do not know how to stream from the webcam. I tried /dev/video0 but it gives the following errors:

[00007fae70008f78] core access error: read error: Invalid argument

[00007fae70008f78] filesystem access error: read error: Invalid
  argument

[00007fae7000d3d8] core stream error: cannot pre fill buffer

What am I doing wrong?

Body:
Simply replaced

String media = "/dev/video0";

with

String media = "v4l2:///dev/video0";

and it works now.


问:
parsing a json-string in classic-asp
I have a string like this here:

```<code>{
    "status":"SUCCESS",
    "response":{
        "offset":0,
        "max":50,
        "count":1,
        "locations":[
            {
                "identifier":"0022",
                "id":322433,
                "dateCreated":"2015-10-29T11:26:29.000+01:00",
                "lastUpdated":"2017-02-13T06:22:35.000+01:00",
                "name":"Something something",
                "street":"Some street",
                "streetNo":"3",
                "streetAndNumber":"some text 3",
                "addressExtra":null,
                "zip":"12345",
                "city":"foobar",
                "cellphone":null,
                "fax": null",
                "website":null,
                "email":null,
                "descriptionShort":"desc",
                "descriptionLong":"desc2",
                "openingHoursNotes":"desc3",
                "lastSyncStarted":"2016-09-12T11:14:24.000+02:00",
                "country":"DE",
                "lat":49.000,
                "lng":8.0000,
                "imprint":null,
                "addressDisplay":null,
                "autoSync":null,
                "phone":"null,
                "status":"ACTIVE",
                "keywords":[
                    "some keywords"
                ],
                "categories":[
                    534
                ],
                "locationSyncable":false,
                "businessId":11111,
                "socialPostId":null,
                "hasFacebook":false,
                "endDate":"2017-02-28T00:00:00.000+01:00",
                "openingHours":[
                    {
                        "dayOfWeek":1,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":2,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":3,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":4,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":5,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":6,
                        "from1":"07:30",
                        "to1":"12:00"
                    }
                ],
                "openNow":true,
                "activeDirectoriesCount":45,
                "activeListingsCount":33,
                "publishedListingsCount":45,
                "profileCompleteness":100,
                "missingMandatoryFields":[

                ],
                "visibilityIndex":559,
                "dataPoints":0,
                "province":"Germany"
            }
        ]
    }
}
</code>```

I have to retrieve the value of the 1st occurente of id - in that case above it should return 322433.

Why am I saying it like this? Because I thought about using a substr (or something like this) or a regexp to obtain the value I need, and a lookup for id:" ends in multiple occurences - also it wouldn't be clean and just a messy workaround.

So, I know there are several related questions and I been through all of them, but I'm totally new to classic asp. Coming from PHP and beeing spoiled with a JSON-parser built-in, I'm kinda lost here.

I found a class on git, which should take care of that, but I can't get it running.

See this here. I tried the exact same thing. Saved the file, included it like my other files and tried to create a new Class, but it ended in a class not defined error.

Maybe this is even way too over? I really just need this once. No dynamic generated output or so. This is always coming as a response from a curl-request and I simply need to get this specific id. Performance plays a kinda relevant role and I guess, using a whole class for that purpose would overdo it.

I tried this VScript as well, but I was kinda lost here, as mentioned above.

To provide all of my code, I'll show you the function where I am stuck right now:

function determineLocationId(identifier)

    Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
    Dim privateKey
    privateKey = "very secret"

    IdentifyUrl = "someUrl"
    With http
      Call .Open("GET", IdentifyUrl, false)
      Call .SetRequestHeader("Content-Type", "application/json; charset=UTF-8")
      Call .SetRequestHeader("CharSet", "utf-8")
      Call .Send()
    End With
    If Left(http.Status, 1) = 2 Then
      response.write("updated")
    Else
      'Output error
      Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
    End If

    response.write(http.responseText) 'this outputs the json from above
    response.end()

    determineLocationId = identifier
end function
```

答:
You can try this:</p>

```<code>Dim str, parser, match, id

str = http.responseText

Set parser = New Regexp
With parser
    .Pattern = """id"":(\d+)"
    .Global = False
End With

Set match = parser.Execute(str)
id = match(0).SubMatches(0)

response.write(id)
</code>```

Title: parsing a json-string in classic-asp

Body:
I have a string like this here:

{
    "status":"SUCCESS",
    "response":{
        "offset":0,
        "max":50,
        "count":1,
        "locations":[
            {
                "identifier":"0022",
                "id":322433,
                "dateCreated":"2015-10-29T11:26:29.000+01:00",
                "lastUpdated":"2017-02-13T06:22:35.000+01:00",
                "name":"Something something",
                "street":"Some street",
                "streetNo":"3",
                "streetAndNumber":"some text 3",
                "addressExtra":null,
                "zip":"12345",
                "city":"foobar",
                "cellphone":null,
                "fax": null",
                "website":null,
                "email":null,
                "descriptionShort":"desc",
                "descriptionLong":"desc2",
                "openingHoursNotes":"desc3",
                "lastSyncStarted":"2016-09-12T11:14:24.000+02:00",
                "country":"DE",
                "lat":49.000,
                "lng":8.0000,
                "imprint":null,
                "addressDisplay":null,
                "autoSync":null,
                "phone":"null,
                "status":"ACTIVE",
                "keywords":[
                    "some keywords"
                ],
                "categories":[
                    534
                ],
                "locationSyncable":false,
                "businessId":11111,
                "socialPostId":null,
                "hasFacebook":false,
                "endDate":"2017-02-28T00:00:00.000+01:00",
                "openingHours":[
                    {
                        "dayOfWeek":1,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":2,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":3,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":4,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":5,
                        "from1":"07:00",
                        "to1":"17:00"
                    },
                    {
                        "dayOfWeek":6,
                        "from1":"07:30",
                        "to1":"12:00"
                    }
                ],
                "openNow":true,
                "activeDirectoriesCount":45,
                "activeListingsCount":33,
                "publishedListingsCount":45,
                "profileCompleteness":100,
                "missingMandatoryFields":[

                ],
                "visibilityIndex":559,
                "dataPoints":0,
                "province":"Germany"
            }
        ]
    }
}

I have to retrieve the value of the 1st occurente of id - in that case above it should return 322433.

Why am I saying it like this? Because I thought about using a substr (or something like this) or a regexp to obtain the value I need, and a lookup for id:" ends in multiple occurences - also it wouldn't be clean and just a messy workaround.

So, I know there are several related questions and I been through all of them, but I'm totally new to classic asp. Coming from PHP and beeing spoiled with a JSON-parser built-in, I'm kinda lost here.

I found a class on git, which should take care of that, but I can't get it running.

See this here. I tried the exact same thing. Saved the file, included it like my other files and tried to create a new Class, but it ended in a class not defined error.

Maybe this is even way too over? I really just need this once. No dynamic generated output or so. This is always coming as a response from a curl-request and I simply need to get this specific id. Performance plays a kinda relevant role and I guess, using a whole class for that purpose would overdo it.

I tried this VScript as well, but I was kinda lost here, as mentioned above.

To provide all of my code, I'll show you the function where I am stuck right now:

function determineLocationId(identifier)

    Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
    Dim privateKey
    privateKey = "very secret"

    IdentifyUrl = "someUrl"
    With http
      Call .Open("GET", IdentifyUrl, false)
      Call .SetRequestHeader("Content-Type", "application/json; charset=UTF-8")
      Call .SetRequestHeader("CharSet", "utf-8")
      Call .Send()
    End With
    If Left(http.Status, 1) = 2 Then
      response.write("updated")
    Else
      'Output error
      Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
    End If

    response.write(http.responseText) 'this outputs the json from above
    response.end()

    determineLocationId = identifier
end function

Body:
You can try this:

Dim str, parser, match, id

str = http.responseText

Set parser = New Regexp
With parser
    .Pattern = """id"":(\d+)"
    .Global = False
End With

Set match = parser.Execute(str)
id = match(0).SubMatches(0)

response.write(id)


问:
With highcharts, is it possible to adapt tooltip text with column color ?
I would like to know it is possible to adapt tooltip text with column color ?

For example, if my column is blue, so my tooltip title will be "Blue Title" and if it's orange, then the tooltip title will be "Orange Title".

Is that possible ?

Thanks in advance !

答:
Finally I found a solution by myself, just a little mistake I've made.

Here is my solution :

```<code>tooltip: {
            formatter: function () {

                    if (this.color == "#d8662c") {
                        return '<b>Title 1</b>';
                    } else if (this.color == "#009dc1") {
                        return '<b>Title 2</b>';
                    } else {
                        return return '<b>Title 3</b>';
                    }

                }
        }
</code>```

Body:
Finally I found a solution by myself, just a little mistake I've made.

Here is my solution :

tooltip: {
            formatter: function () {

                    if (this.color == "#d8662c") {
                        return '<b>Title 1</b>';
                    } else if (this.color == "#009dc1") {
                        return '<b>Title 2</b>';
                    } else {
                        return return '<b>Title 3</b>';
                    }

                }
        }


问:
CALayer clip subviews in animation
I want to make animation, that should look like that:
there a layer on the mainViewLayer, drawn Drop of water with transparent fillColor, I add under it another CAShapeLayer - with blue Color, there layers have the same bounds. and i want to animate its y position, that will imitate decreasing of water level.

```<code>    fallingWaterLayer = CAShapeLayer()
    fallingWaterLayer.frame = x.bounds
    fallingWaterLayer.fillColor = UIColor.blue.cgColor
    let path = CGPath(rect:fallingWaterLayer.bounds, transform:nil)
    fallingWaterLayer.path = path
    x.layer.addSublayer(fallingWaterLayer)
    mainLayer = DropLayer(x.bounds, shouldFillLayer:false)
    x.layer.addSublayer(mainLayer!)
</code>```

my animation looks like that:

```<code>    let animation = CABasicAnimation(keyPath: "bounds.origin.y")
    animation.toValue = x.bounds.size.width * -1
    animation.duration = 5.8
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeBoth
    animation.isRemovedOnCompletion = false
    fallingWaterLayer.add(animation, forKey: animation.keyPath)
</code>```

So the question is how can i make top Layer clips the blue rect, to make it look like animation is done inside the Drop of water?

答:
Every CALayer has a mask property, which can be any arbitrary other layer, so that seems like it would be a good solution.

https://developer.apple.com/reference/quartzcore/calayer/1410861-mask

The way the mask property works is that any transparent pixel of the mask will be clipped in the target layer. So you'll need to create a second, solid water drop layer to use as the mask - you can't re-use the same water drop outline, otherwise the water will be clipped to just the border of the water drop, instead of filling the inside.

Title: CALayer clip subviews in animation

Body:
I want to make animation, that should look like that:
there a layer on the mainViewLayer, drawn Drop of water with transparent fillColor, I add under it another CAShapeLayer - with blue Color, there layers have the same bounds. and i want to animate its y position, that will imitate decreasing of water level.

    fallingWaterLayer = CAShapeLayer()
    fallingWaterLayer.frame = x.bounds
    fallingWaterLayer.fillColor = UIColor.blue.cgColor
    let path = CGPath(rect:fallingWaterLayer.bounds, transform:nil)
    fallingWaterLayer.path = path
    x.layer.addSublayer(fallingWaterLayer)
    mainLayer = DropLayer(x.bounds, shouldFillLayer:false)
    x.layer.addSublayer(mainLayer!)

my animation looks like that:

    let animation = CABasicAnimation(keyPath: "bounds.origin.y")
    animation.toValue = x.bounds.size.width * -1
    animation.duration = 5.8
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeBoth
    animation.isRemovedOnCompletion = false
    fallingWaterLayer.add(animation, forKey: animation.keyPath)

So the question is how can i make top Layer clips the blue rect, to make it look like animation is done inside the Drop of water?


问:
C# Uploading a memorystream object to Web API
I have an CSV file in memory that I want to upload to a Web API.

If I save the CSV file to disk and upload it, it gets accepted.

However, I want to avoid the extra work and also make the code cleaner by simply uploading the text I have as a MemoryStream Object (I think that's the correct format?).

The following code works for uploading the file:

```<code>string webServiceUrl = "XXX";
string filePath = @"C:\test.csv";
string cred = "YYY";

using (var client = new WebClient()){
    client.Headers.Add("Authorization", "Basic " + cred);
    byte[] rawResponse = client.UploadFile(webServiceUrl, "POST", filePath);
    Console.WriteLine(System.Text.Encoding.ASCII.GetString(rawResponse));
}
</code>```

How would I do if I had a string with all the contents and I want to upload it in the same way without having to save it down to a file?

WebClient.UploadData or WebClient.UploadString perhaps?

Thank you

EDIT:

I tried what you said but by using a local file (in case there was something wrong with the string), but I get the same error.

Here is what I suppose the code would be using your solution

```<code>string webServiceUrl = "XXX";
string file = @"C:\test.csv";
string cred = "YYY";

FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);

using (var client = new WebClient())
{
    client.Headers.Add("Authorization", "Basic " + cred);
    using (var postStream = client.OpenWrite(webServiceUrl, "POST"))
    {
          postStream.Write(postArray, 0, postArray.Length);
    }
}
</code>```

Any thoughts?

答:
Use OpenWrite() from the WebClient.

```<code>using (var postStream = client.OpenWrite(endpointUrl))
{
    postStream.Write(memStreamContent, 0, memStream.Length);
}
</code>```

As documentation mentioned:

The OpenWrite method returns a writable stream that is used to send data to a resource.

Update

Try to set the position of the MemoryStream to 0 before uploading.

```<code>memoryStream.Position = 0;
</code>```

When you copy the file into the MemoryStream, the pointer is moved to the end of the stream, so when you then try to read it, you're getting a null byte instead of your stream data.

MSDN - CopyTo()

Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.

Body:
I have an CSV file in memory that I want to upload to a Web API.

If I save the CSV file to disk and upload it, it gets accepted.

However, I want to avoid the extra work and also make the code cleaner by simply uploading the text I have as a MemoryStream Object (I think that's the correct format?).

The following code works for uploading the file:

string webServiceUrl = "XXX";
string filePath = @"C:\test.csv";
string cred = "YYY";

using (var client = new WebClient()){
    client.Headers.Add("Authorization", "Basic " + cred);
    byte[] rawResponse = client.UploadFile(webServiceUrl, "POST", filePath);
    Console.WriteLine(System.Text.Encoding.ASCII.GetString(rawResponse));
}

How would I do if I had a string with all the contents and I want to upload it in the same way without having to save it down to a file?

WebClient.UploadData or WebClient.UploadString perhaps?

Thank you

EDIT:

I tried what you said but by using a local file (in case there was something wrong with the string), but I get the same error.

Here is what I suppose the code would be using your solution

string webServiceUrl = "XXX";
string file = @"C:\test.csv";
string cred = "YYY";

FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);

using (var client = new WebClient())
{
    client.Headers.Add("Authorization", "Basic " + cred);
    using (var postStream = client.OpenWrite(webServiceUrl, "POST"))
    {
          postStream.Write(postArray, 0, postArray.Length);
    }
}

Any thoughts?

Body:
Use OpenWrite() from the WebClient.

using (var postStream = client.OpenWrite(endpointUrl))
{
    postStream.Write(memStreamContent, 0, memStream.Length);
}

As documentation mentioned:

The OpenWrite method returns a writable stream that is used to send data to a resource.

Update

Try to set the position of the MemoryStream to 0 before uploading.

memoryStream.Position = 0;

When you copy the file into the MemoryStream, the pointer is moved to the end of the stream, so when you then try to read it, you're getting a null byte instead of your stream data.

MSDN - CopyTo()

Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.


问:
Receive notifications on android upon database change
I have an android app which is capable to interact with a (for now local, but in future online) RESTful database (using PHP and Slim framework).

A registered user can create/upload new text, view all its texts, delete and modify them.

The user can log through different devices (Android smartphones for now, but in future with Desktop computers as well) and perform said operations.

I need that EVERY device (on which the user is logged in) is notified upon each change in the database.

What is the best approach to implement such notification capability either on the PHP/MySQL server and in my android app?

I have heard about Google's Firebase Cloud Messaging but i'm not sure neither if it is the easiest and fastest way to do it, nor if it is compatible with my already working environment.

Please guide me in the right direction as i don't have a clue on what is best for my case.

答: You have to registered mobile device or desktop to fcm/gcm server or apns in case of iOS . When database is updated on server then it will get a trigger so on after save will send notification push with your payload. </p>


问:
How can i do this query by linq ,extensions methods or pure sql?
I have a table below

```<code> first      second
-------     ----------
100        0
200        0
0           400
</code>```

I want to get below result

```<code> first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100
</code>```

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?

答:
This is a "running total" query. It can be done in SQL, but it depends on how the table is layed out.

Here's a SO Answer to this question on how to do it in SQL.

Here's an SO Answer on how to do this using Linq.

Body:
I have a table below

 first      second
-------     ----------
100        0
200        0
0           400

I want to get below result

 first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?


问:
converting WGS84 vectors for import onto EPSG 3857 tiles in openlayers
I am importing bounding boxes I have converted to geojson WGS84 polygons but I am getting a strange projection error (see below):

I assume this is from me importing it as WGS 84 onto a 3857 projection (I could be wrong!). I tried setting the view to WGS 84 but the map is then blank with no error messages. Should I do an "on the fly" transformation to 3857 or should I convert it to 3857 beforehand?

答:
It looks like you computed the bounding boxes before reprojecting. Since a bounding box is the min and max x and y coordinates, it is only meaningful in one SRS, since it depends on the direction of the axes, which might be different (think about it). Your options are either

Reproject underlying data, then compute bounding boxes in the final SRS

Compute bounding boxes, convert them to polygons, then reproject. (They won't be bounding boxes now, however)


问:
How to remove index.php from CodeIgniter URL?

.htaccess code it's working fine on local host but it's not working fine on godaddy server. I tried so many .htaccess codes but I am unable to solve the problem.

            RewriteEngine On
            RewriteBase /CI/

```<code>        #Removes access to the system folder by users.
        #Additionally this will allow you to create a System.php controller,
        #previously this would not have been possible.
        #'system' can be replaced if you have renamed your system folder.
        RewriteCond %{REQUEST_URI} ^system.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #When your application folder isn't in the system folder
        #This snippet prevents user access to the application folder
        #Submitted by: Fabdrol
        #Rename 'application' to your applications folder name.
        RewriteCond %{REQUEST_URI} ^application.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #Checks to see if the user is attempting to access a valid file,
        #such as an image or css document, if this isn't true it sends the
        #request to index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]

        </IfModule>

        <IfModule !mod_rewrite.c>
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        # Submitted by: ElliotHaughin

        ErrorDocument 404 /index.php
        </IfModule>
</code>```

答:
Verify your .htaccess path firt
it should be in root directory of your project
and try this below htaccess code , its works for my on godaddy.

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /CI/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
</code>```

Now open  /application/config/config.php and do the following changes :

```<code>$config['base_url']  = 'http://www.rcshoper.com/CI/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
</code>```

Body:
.htaccess code it's working fine on local host but it's not working fine on godaddy server. I tried so many .htaccess codes but I am unable to solve the problem.

            RewriteEngine On
            RewriteBase /CI/

        #Removes access to the system folder by users.
        #Additionally this will allow you to create a System.php controller,
        #previously this would not have been possible.
        #'system' can be replaced if you have renamed your system folder.
        RewriteCond %{REQUEST_URI} ^system.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #When your application folder isn't in the system folder
        #This snippet prevents user access to the application folder
        #Submitted by: Fabdrol
        #Rename 'application' to your applications folder name.
        RewriteCond %{REQUEST_URI} ^application.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #Checks to see if the user is attempting to access a valid file,
        #such as an image or css document, if this isn't true it sends the
        #request to index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]

        </IfModule>

        <IfModule !mod_rewrite.c>
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        # Submitted by: ElliotHaughin

        ErrorDocument 404 /index.php
        </IfModule>

Body:
Verify your .htaccess path firt
it should be in root directory of your project
and try this below htaccess code , its works for my on godaddy.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /CI/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Now open  /application/config/config.php and do the following changes :

$config['base_url']  = 'http://www.rcshoper.com/CI/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';


问:
Login Validation of an imageview in android
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

```<code>enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

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

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}
</code>```

答:
Take one boolean flag and set it default false

```<code>boolean isImageAdded = false;
</code>```

now from where you are choosing the image from Camera or Gallary , if your image data is not null in onActivityResult method make isImageAdded = true

and in last for validation just check isImageAdded is it true or false.

Body:
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

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

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}

Body:
Take one boolean flag and set it default false

boolean isImageAdded = false;

now from where you are choosing the image from Camera or Gallary , if your image data is not null in onActivityResult method make isImageAdded = true

and in last for validation just check isImageAdded is it true or false.


问:
How to count rows with specific value?
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

```<code>SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId
</code>```

答:
Don't forget that COUNT() counts all non-null values, not just values > 0.

As a result, use:

```<code>COUNT(CASE WHEN goal > 0 THEN 1 ELSE NULL END)
</code>```

or shortened to:

```<code>COUNT(CASE WHEN GOAL > 0 THEN 1 END)
</code>```

Title: How to count rows with specific value?

Body:
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId

Body:
Don't forget that COUNT() counts all non-null values, not just values > 0.

As a result, use:

COUNT(CASE WHEN goal > 0 THEN 1 ELSE NULL END)

or shortened to:

COUNT(CASE WHEN GOAL > 0 THEN 1 END)


问:
IOS - Capture event on button pressed and pass to tableview
I’m trying to capture an event from a button pressed so I can pass it to a table view, its a timer where I can capture the time and pass it to the tableview but I can't seem to be able to capture the event type.

In the example below I can capture the time a goal was scored but I need the words Goal also passing to the tableview

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")

        cell.backgroundColor = self.view.backgroundColor

        **cell.textLabel?.text = "Help here to capture the button event"**
        cell.detailTextLabel?.text = time[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return time.count
    }

@IBAction func goalClicked(_ sender: UIButton) {

    let stopWatchString = stopWatch.elapsedTimeSinceStart()
    stopwatchLabel.text = stopWatchString

    time.insert(stopWatchString, at: 0)
    self.tableView.reloadData()
}
</code>```

Thanks

答:
Sorted it.

```<code>var event: String!
</code>```

then in the tableView

```<code>cell.textLabel?.Text = event
</code>```

Finally in the button function

```<code>event = "Goal"
tableView.reloadData()
</code>```

Body:
I’m trying to capture an event from a button pressed so I can pass it to a table view, its a timer where I can capture the time and pass it to the tableview but I can't seem to be able to capture the event type.

In the example below I can capture the time a goal was scored but I need the words Goal also passing to the tableview

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")

        cell.backgroundColor = self.view.backgroundColor

        **cell.textLabel?.text = "Help here to capture the button event"**
        cell.detailTextLabel?.text = time[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return time.count
    }

@IBAction func goalClicked(_ sender: UIButton) {

    let stopWatchString = stopWatch.elapsedTimeSinceStart()
    stopwatchLabel.text = stopWatchString

    time.insert(stopWatchString, at: 0)
    self.tableView.reloadData()
}

Thanks

Body:
Sorted it.

var event: String!

then in the tableView

cell.textLabel?.Text = event

Finally in the button function

event = "Goal"
tableView.reloadData()


问:
Import a git repo into an empty branch
Lets say a project has been developed in one repo, and the project website was developed in another.

Is there a way to import the website repo, with full history, into an empty branch of the project repo?

答: I guess this would be a case for git submodules</p>

Title: Import a git repo into an empty branch