问:
how to increase the height of scroll viewheight dynamically in swift 3?
How can i set the constraints that here two table views are using so that both are dynamical and i need to change the height of scroll view so that both table views and it needs to fit the whole screen and my layout will be as shown below in the image

答:
why you are using tableview in scrollview ? It is not good approach to use scrollable entity into scrollview!  You can take one tableview and can create multiple cell for every type of your content like payment view, cart view etc. You can use multiple section also as per requirement. For example, your Table details should be your first section, that can contain multiple rows.

By this way your height will be automatically managed by tableview.


来源: stackexchange

问:
Play! framework - handle a POST request
this is the route to handle the login POST request:

```<code>POST  /login/submit                 controllers.Users.loginSubmit(user : String, password : String)
</code>```

this is the login.scala.html:

```<code><form method="post" action="???">
  <input type="text" name="username" /><br/>
  <input type="password" name="password" /><br/>

  <input type="submit" value="Login" />
</form>
</code>```

I got two questions:

what should be the value of action?  is it "login/submit"?

how do you pass this form to be handled in the loginSubmit function?

thanks

答:
In Play Framework version 2.5.x Form.form() is deprecated and you should use inject a FormFactory

Here you can find example: The method form(Class) from Form class is deprecated in Play! Framework

Import:

```<code>import play.data.DynamicForm;
import play.data.FormFactory;
</code>```

Inject:

```<code>@Inject FormFactory formFactory;
</code>```

Controller:

```<code>public static Result loginSubmit(){
    DynamicForm dynamicForm = formFactory.form().bindFromRequest();
    Logger.info("Username is: " + dynamicForm.get("username"));
    Logger.info("Password is: " + dynamicForm.get("password"));
    return ok("ok, I recived POST data. That's all...");
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Play! framework - handle a POST request

Body:
this is the route to handle the login POST request:

POST  /login/submit                 controllers.Users.loginSubmit(user : String, password : String)

this is the login.scala.html:

<form method="post" action="???">
  <input type="text" name="username" />

  <input type="password" name="password" />

  <input type="submit" value="Login" />
</form>

I got two questions:

what should be the value of action?  is it "login/submit"?

how do you pass this form to be handled in the loginSubmit function?

thanks

Body:
In Play Framework version 2.5.x Form.form() is deprecated and you should use inject a FormFactory

Here you can find example: The method form(Class) from Form class is deprecated in Play! Framework

Import:

import play.data.DynamicForm;
import play.data.FormFactory;

Inject:

@Inject FormFactory formFactory;

Controller:

public static Result loginSubmit(){
    DynamicForm dynamicForm = formFactory.form().bindFromRequest();
    Logger.info("Username is: " + dynamicForm.get("username"));
    Logger.info("Password is: " + dynamicForm.get("password"));
    return ok("ok, I recived POST data. That's all...");
}


问:
Why is my prepareForSegue method not being called?
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}
</code>```

答:
If you want to send data from ViewControllerA to ViewControllerB you can pass data using prepare for segue method or instantiating ViewControllerB storyboard id and access its properties and pass data.

If you want to do vice-versa i.e. passing data back from ViewControllerB to ViewControllerA, you can use various patterns. Delegation , Notification , Kvo or using NSUserDefaults.

In your case Delegation Pattern will be best. Assign ViewController2 as delegate of your current class. And pass data(in your case control state) using protocols of your current class. Implement the protocol in  ViewController2 and access control state of your switches and do accordingly. You can refer my previous ans on this topic.Look here for my detailed ans in Objective-C.
Hope it helps. Hapy Coding!!

Body:
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}


问:
angular.js TypeError: $(...).owlCarousel is not a function
I am using angular js and data-ng-repeat to get data.
Below is my HTML.

```<code>      <div id="newsslide" class="owl-carousel owl-theme">
          <div class="item darkCyan" data-ng-repeat="items in NewsList">
                        Hello
          </div>
      </div>
</code>```

Here is my JS

```<code>    $scope.getNewsList = function (Id) {
    var getData = HomeService.getNewsList(Id);
    getData.then(function (_result) {
        $scope.getMediaList(Id);
        if (_result.data.length > 0) {
            $scope.NewsList = _result.data;
            $scope.NewsNoRecords = false;
            $timeout(function () {
                $("#newsslide").owlCarousel({
                    items: 3,
                    nav: false,
                    dots: true,
                    rtl:true,
                    // autoPlay: 3000,
                    navText: [
                    "<i class='fa fa-angle-left'></i>",
                    "<i class='fa fa-angle-right'></i>"
                    ]
                });
            }, 1000);
        }
        else {
            $scope.NewsNoRecords = true;
        }
    }, function (errorMsg) {
        $scope.loadingDataEntryList = false;
        console.log('Error in getting records - ' + JSON.stringify(errorMsg))
    });
}
</code>```

Data is binding Fine. But it shows

TypeError: $(...).owlCarousel is not a function.

I also tried to run  $("#newsslide").owlCarousel({}); through pasting in chrome developer console. I got error

Uncaught TypeError: $(...).owlCarousel is not a function
      at Anonymous:1:18.

Below is library sequence i added, [jQuery library was in head tag before this image. and thats why it cause problem]
[]1

I have searched a lot. Please help. Thanks

答:
These can be the potential reason.

It seems you have not added Jquery

Or Jquery is added after Angularjs

haven't added the "owl carousel" JS file

You need to add jquery before angularjs.

```<code><script src="jquery.min.js"></script>
<script src="angular.min.js"></script>
</code>```

Body:
I am using angular js and data-ng-repeat to get data.
Below is my HTML.

                        Hello

Here is my JS

    $scope.getNewsList = function (Id) {
    var getData = HomeService.getNewsList(Id);
    getData.then(function (_result) {
        $scope.getMediaList(Id);
        if (_result.data.length > 0) {
            $scope.NewsList = _result.data;
            $scope.NewsNoRecords = false;
            $timeout(function () {
                $("#newsslide").owlCarousel({
                    items: 3,
                    nav: false,
                    dots: true,
                    rtl:true,
                    // autoPlay: 3000,
                    navText: [
                    "",
                    ""
                    ]
                });
            }, 1000);
        }
        else {
            $scope.NewsNoRecords = true;
        }
    }, function (errorMsg) {
        $scope.loadingDataEntryList = false;
        console.log('Error in getting records - ' + JSON.stringify(errorMsg))
    });
}

Data is binding Fine. But it shows

TypeError: $(...).owlCarousel is not a function.

I also tried to run  $("#newsslide").owlCarousel({}); through pasting in chrome developer console. I got error

Uncaught TypeError: $(...).owlCarousel is not a function
      at Anonymous:1:18.

Below is library sequence i added, [jQuery library was in head tag before this image. and thats why it cause problem]
[]1

I have searched a lot. Please help. Thanks

Body:
These can be the potential reason.

It seems you have not added Jquery

Or Jquery is added after Angularjs

haven't added the "owl carousel" JS file

You need to add jquery before angularjs.

<script src="jquery.min.js"></script>
<script src="angular.min.js"></script>


问:
get value of any id in form click on another class php
I want a value for id iin_no click on client_name class in while loop, assume that there are 50 rows. on jQuery.

```<code><td>
  <a href="#">
    <strong class="text-custom client_name">
      <u><?php echo $fetch_data['Name_as_per_pan']; ?></u>
    </strong>
    </p>
  </a>
</td>

<div id="iin_no">
  <p><?php echo $fetch_data['iin']; ?>
</div>
</code>```

答:
This is perfectly working. Please change only id of iin_no to class.

```<code>$('strong.client_name').on('click',function(){
    var iin_no = $(this).parents('tr').find('div.iin_no').text();
});
</code>```

Body:
I want a value for id iin_no click on client_name class in while loop, assume that there are 50 rows. on jQuery.

      <?php echo $fetch_data['Name_as_per_pan']; ?>

<?php echo $fetch_data['iin']; ?>

Body:
This is perfectly working. Please change only id of iin_no to class.

$('strong.client_name').on('click',function(){
    var iin_no = $(this).parents('tr').find('div.iin_no').text();
});


问:
How to send AJAX POST request and play the audio in the response?
I am building an app where the user can click a button, and it sends data to the server. The server then computes audio based on the data in the request (most likely a POST), and returns a WAV file to the browser.

I have already built the part with accepting a post request and responding with the wav file, but I can't figure out how to send the request in JS and to play the response to the user.

Also, the playing of the audio must start (almost) as the first byte comes in, as the audio files are quite large, and the user can't just wait for the request to be completed.

I am also open to suggestions changing how the server sends the file: the server is made in flask

答:
Will something like this work?

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <audio controls>
        <source id="source" src="" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $.ajax({
            url: 'get.php',
            data: { attr1: 'value1' },
            success: function( data ) {
                console.log(data);
                $('audio #source').attr('src', data);
                $('audio').get(0).load();
                $('audio').get(0).play();
            }
        });
    </script>
</body>
</html>
</code>```

While the get.php just prints the audio file link. Note that I didn't get any WAV file so can't test on that.

```<code><?php echo 'http://junaidahmed.io/w/audio.mp3'; ?>
</code>```

That audio I'm printing above is a 30 minute and about 13mb file size. My internet is not fast enough to load the whole file in a second or two and yet it plays right away.

Body:
Will something like this work?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <audio controls>
        <source id="source" src="" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $.ajax({
            url: 'get.php',
            data: { attr1: 'value1' },
            success: function( data ) {
                console.log(data);
                $('audio #source').attr('src', data);
                $('audio').get(0).load();
                $('audio').get(0).play();
            }
        });
    </script>
</body>
</html>

While the get.php just prints the audio file link. Note that I didn't get any WAV file so can't test on that.

<?php echo 'http://junaidahmed.io/w/audio.mp3'; ?>

That audio I'm printing above is a 30 minute and about 13mb file size. My internet is not fast enough to load the whole file in a second or two and yet it plays right away.


问:
Windows Identity always anonymous in ASP.NET request pipeline
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

```<code><authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>
</code>```

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

答:
Try

```<code><system.web>
    <identity impersonate="true" />
</system.web>
</code>```

OR

Click On The Project Not the Solution => Open Properties Explorer not right click properties => you will find Anonymous Authentication set to disabled

Body:
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

<authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

Body:
Try

<system.web>
    <identity impersonate="true" />
</system.web>

OR

Click On The Project Not the Solution => Open Properties Explorer not right click properties => you will find Anonymous Authentication set to disabled


问:
Android studio action bar not showing in new activity
style.xml

<resources>

答:
try above in style.xml

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

and update your AndroidManifest file like above

```<code>  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karanvir.search">
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
     >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
       />
    <activity
        android:name=".Yahoo"
        android:label="@string/title_activity_yahoo"
       ></activity>
</application>
</code>```

Body:
style.xml

<resources>

Body:
try above in style.xml

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

and update your AndroidManifest file like above

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karanvir.search">
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
     >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
       />
    <activity
        android:name=".Yahoo"
        android:label="@string/title_activity_yahoo"
       ></activity>
</application>


问:
Create image patches, sklearn.feature_extraction.image.extract_patches_2d memory error
I was looking for a way to divide a numpy image into grid like patches.

This task has been answered a couple times.
Extracting patches of a certain size from the image in python efficiently

skleans extract_patches_2d looks exactly right.

http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html

However, I feel that i'm not understanding the docs.

I have a image, its not particularly large, a few Mb on disk. OpenCV has no trouble with it.

Its dimensions are

```<code>self.original_image.shape
(1536, 2048, 3)
</code>```

So let's extract it into blocks each 100 X 100. Back of the envelope calculation the number of patches should be something like

(1536 * 2048) / (100*100) = 314

```<code>patches=extract_patches_2d(self.original_image,(100,100))
Traceback (most recent call last):
  Debug Probe, prompt 46, line 1
  File "c:\Python27\Lib\site-packages\sklearn\feature_extraction\image.py", line 374, in extract_patches_2d
    extraction_step=1)
  File "c:\Python27\Lib\site-packages\sklearn\feature_extraction\image.py", line 296, in extract_patches
    patches = as_strided(arr, shape=shape, strides=strides)
  File "c:\Python27\Lib\site-packages\numpy\lib\stride_tricks.py", line 48, in as_strided
    array = np.asarray(DummyArray(interface, base=x))
  File "c:\Python27\Lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.
</code>```

This is a numpy memory error. What is causing that?

I get the feeling I don't follow entirely, lets make a tiny image and split that into pretty large sections

```<code>patches=extract_patches_2d(self.original_image[0:100,0:100],(50,50))
</code>```

That works, but yields thousands of patches

```<code>len(patches)
2601
</code>```

Not the ~ 4 I'd expect. What am I not understanding about this function? How do people go about getting patches, it seems like a common thing in computer vision.

Python 2.7 on Windows, packages recently installed and up to date

```<code>Ben@Laptop MINGW64 ~/Desktop
$ pip install -U scikit-learn

Requirement already up-to-date: scikit-learn in c:\python27\lib\site-packages
</code>```

答:
The function creates  all possible combinations of patches from the given image.
In your case, the first patch  will span  0:49 pixels row wise and 0: 49 pixels column wise. The second patch from 1:50 row wise and column wise and o on.
So if you have an image of size (m,n) and wish to extract patches of size (a,b) , then (m-a)+1 x (n-b+1) maximum possible patches can be extracted .
In your case that is 51x 51 = 2601 patches..
If you want to limit the number of patches to be extracted, you can do so by the optional parameter by the max_ patches parameter.

Body:
I was looking for a way to divide a numpy image into grid like patches.

This task has been answered a couple times.
Extracting patches of a certain size from the image in python efficiently

skleans extract_patches_2d looks exactly right.

http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html

However, I feel that i'm not understanding the docs.

I have a image, its not particularly large, a few Mb on disk. OpenCV has no trouble with it.

Its dimensions are

self.original_image.shape
(1536, 2048, 3)

So let's extract it into blocks each 100 X 100. Back of the envelope calculation the number of patches should be something like

(1536 * 2048) / (100*100) = 314

patches=extract_patches_2d(self.original_image,(100,100))
Traceback (most recent call last):
  Debug Probe, prompt 46, line 1
  File "c:\Python27\Lib\site-packages\sklearn\feature_extraction\image.py", line 374, in extract_patches_2d
    extraction_step=1)
  File "c:\Python27\Lib\site-packages\sklearn\feature_extraction\image.py", line 296, in extract_patches
    patches = as_strided(arr, shape=shape, strides=strides)
  File "c:\Python27\Lib\site-packages\numpy\lib\stride_tricks.py", line 48, in as_strided
    array = np.asarray(DummyArray(interface, base=x))
  File "c:\Python27\Lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.

This is a numpy memory error. What is causing that?

I get the feeling I don't follow entirely, lets make a tiny image and split that into pretty large sections

patches=extract_patches_2d(self.original_image[0:100,0:100],(50,50))

That works, but yields thousands of patches

len(patches)
2601

Not the ~ 4 I'd expect. What am I not understanding about this function? How do people go about getting patches, it seems like a common thing in computer vision.

Python 2.7 on Windows, packages recently installed and up to date

Ben@Laptop MINGW64 ~/Desktop
$ pip install -U scikit-learn

Requirement already up-to-date: scikit-learn in c:\python27\lib\site-packages


问:
OSX Server: apache2 running but “Problem loading page”
I have setup OSX Server 10.6, all updates installed, started apache2, which is running:

```<code>sudo apachectl graceful
</code>```

I see in /var/log/apache2/errorlog

```<code>[Fri Dec 17 10:11:49 2010] [notice] Apache/2.2.15 (Unix) configured -- resuming normal operations
</code>```

Also

```<code>ps -ef | grep httpd
</code>```

shows several processes:

```<code>    0 49388     1   0   0:00.05 ??         0:00.07 /usr/sbin/httpd -D FOREGROUND
   70 49389 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49390 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49391 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49392 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
...
</code>```

In httpd.conf I edited DocumentRoot:

```<code>ServerName bioinfo.mni.fh-giessen.de:80
DocumentRoot "/Volumes/ServerHD2/Web_Documents"
ErrorLog "/var/log/apache2/error_log"
<Directory "/Volumes/ServerHD2/Web_Documents">
   Order Allow,Deny
   Allow from All
</Directory>
</code>```

Syntax is OK:

```<code>apachectl configtest
Syntax OK
</code>```

Yet, I get timeouts at http://bioinfo.mni.fh-giessen.de :

```<code>Problem loading page
</code>```

Any clue ?

答:
Are you sure you edited the right file?  OS X Server has a way of not keeping to standards.  The actual configuration entries are not in /etc/httpd/httpd.conf, but in subdirectories of /etc/apache2/sites. Check out this FAQ.

I would recommend using the Server Admin utility to set up the server.  It will be a lot easier and quicker than trying to get the configuration right manually.  You can always add or change rules later, once the site is up and running.

ContentLicense: CC BY-SA 2.5

Body:
I have setup OSX Server 10.6, all updates installed, started apache2, which is running:

sudo apachectl graceful

I see in /var/log/apache2/errorlog

[Fri Dec 17 10:11:49 2010] [notice] Apache/2.2.15 (Unix) configured -- resuming normal operations

Also

ps -ef | grep httpd

shows several processes:

    0 49388     1   0   0:00.05 ??         0:00.07 /usr/sbin/httpd -D FOREGROUND
   70 49389 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49390 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49391 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49392 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
...

In httpd.conf I edited DocumentRoot:

ServerName bioinfo.mni.fh-giessen.de:80
DocumentRoot "/Volumes/ServerHD2/Web_Documents"
ErrorLog "/var/log/apache2/error_log"
<Directory "/Volumes/ServerHD2/Web_Documents">
   Order Allow,Deny
   Allow from All
</Directory>

Syntax is OK:

apachectl configtest
Syntax OK

Yet, I get timeouts at http://bioinfo.mni.fh-giessen.de :

Problem loading page

Any clue ?


问:
Notification bar icon turns white in Android 5 Lollipop
I have an app showing custom notifications. The problem is that when running in Android 5 the small icon in the Notification bar is shown in white. How can I fix this?</p>

答:
FYI: If the Icon doesn't appear, ensure your local or remote notification configuration contains the correct icon name  i.e  </p>

```<code>'largeIcon' => 'ic_launcher',
'smallIcon' => 'ic_launcher' // defaults to ic_launcher,
</code>```

Body:
FYI: If the Icon doesn't appear, ensure your local or remote notification configuration contains the correct icon name  i.e

'largeIcon' => 'ic_launcher',
'smallIcon' => 'ic_launcher' // defaults to ic_launcher,


问:
brush extents not working as expected
For some reason my chart is not getting brushed as I was hoping it would. The domain of brush.extent() seems to be working, but the bars are all flying off the page. Can someone tell me what's wrong here?

```<code>function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.select("rect").attr("x",  function(d) { return x(d.from); });
    focus.select("rect").attr("width",  function(d) {return x(d.to) - x(d.from);});
    focus.select(".x.axis").call(xAxis);
}
</code>```

https://jsbin.com/layecehidu/edit?js,console,output

答:
The problem in your code is that you're using select where you should use selectAll instead.

The obvious difference between select and selectAll, as the very name of the methods imply, is that select...

selects the first descendant element that matches the specified selector string.

... while selectAll:

Selects all elements that match the specified selector string.

That's not the only difference, though. Grouping and data propagation are less well known differences. Look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

That being said, your code should be:

```<code>function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.selectAll("rect").attr("x", function(d) {
        return x(d.from);
    })
    focus.selectAll("rect").attr("width", function(d) {
        return x(d.to) - x(d.from);
    });
    focus.select(".x.axis").call(xAxis);
}
</code>```

Here is the code with that change only:

var parseDate = d3.time.format("%d-%b-%y").parse;

var data=[
 {"category": "Task 1", "from": "1-Jan-17", "to": "15-Jan-17", "progress":100, "synched": ["5-Jan-17", "7-Jan-17"]},
 {"category": "Task 2", "from": "13-Jan-17", "to": "1-Feb-17", "progress":60, "synched": ["15-Jan-17"]},
 {"category": "Task 1", "from": "1-Feb-17", "to": "11-Mar-17", "progress":90, "synched": ["2-Feb-17", "4-Feb-17"]}
]

data.forEach(function(d) {
    d.from = parseDate(d.from);
    d.to = parseDate(d.to);
});

var margin = {top: 10, right: 10, bottom: 100, left: 100},
    margin2 = {top: 330, right: 10, bottom: 30, left: 100},
    width = 900 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom,
    height2 = 400 - margin2.top - margin2.bottom;

var x = d3.time.scale().range([0, width]);
var x2 = d3.time.scale().range([0, width]);
var y = d3.scale.ordinal().rangeRoundBands([0, height], 0.2);
var y2 = d3.scale.ordinal().rangeRoundBands([0, height2], 0.2);

y.domain(data.map(function(d) { return d.category; }));
x.domain([d3.min(data,function(d){return d.from;}), d3.max(data,function(d){return d.to;})]);
x2.domain(x.domain());
y2.domain(y.domain());

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(15)
    .tickFormat(d3.time.format("%d%b"));

var xAxis2 = d3.svg.axis()
    .scale(x2)
    .orient("bottom")
    .ticks(15)
    .tickFormat(d3.time.format("%d%b"));

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var brush = d3.svg.brush()
    .x(x2)
    .on("brush", doBrush);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("defs")
    .append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("fill", "red")
    .attr("width", width)
    .attr("height", height);

var focus = svg.append("g")
var context = svg.append("g")
    .attr("transform", "translate(0," + margin2.top + ")");

var focusRectangleGroups = focus.selectAll("g")
    .data(data)
    .enter()
    .append("g");

focusRectangleGroups.append("rect")
    .attr("class", "bar")
    .attr("clip-path", "url(#clip)")
    .attr("y", function(d) { return y(d.category); })
    .attr("height", y.rangeBand())
    .attr("x", function(d) { return x(d.from); })
    .attr("width", function(d) { return x(d.to) - x(d.from); });

focus.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .append("text")
    .attr("x", width-margin.right)
    .attr("dx", ".71em")
    .attr("dy", "-0.2em")
    .text("Date");

focus.append("g")
    .attr("class", "y axis")
    .call(yAxis);

var contextRectangleGroups = context.selectAll("g")
    .data(data)
    .enter()
    .append("g");

contextRectangleGroups.append("rect")
    .attr("class", "bar")
    .attr("y", function(d) { return y2(d.category); })
    .attr("height", y2.rangeBand())
    .attr("x", function(d) { return x2(d.from); })
    .attr("width", function(d) { return x2(d.to) - x2(d.from); })
    .attr("clip-path", "url(#clip)");

context.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height2 + ")")
    .call(xAxis2);

context.append("g")
    .attr("class", "x brush")
    .call(brush)
    .selectAll("rect")
    .attr("y", -6)
    .attr("height", height2 + 7);

function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.selectAll("rect").attr("x", function(d) { return x(d.from); })
    focus.selectAll("rect").attr("width", function(d) { return x(d.to) - x(d.from); });
    focus.select(".x.axis").call(xAxis);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pending {
        fill: #e74c3c;
    }

    .bar {
        fill: #2ecc71;
    }

/*     .bar:hover, .pending:hover {
      fill: #3498db;
    } */

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }

    .legend {
        padding: 5px;
        font: 16px sans-serif;
        background: yellow;
        box-shadow: 2px 2px 1px #888;
    }

    .tooltip {
        background: #eee;
        box-shadow: 0 0 5px #999999;
        color: #333;
        font-size: 12px;
        left: 130px;
        padding: 10px;
        position: absolute;
        text-align: center;
        top: 95px;
        z-index: 10;
        display: block;
        opacity: 0;
    }
.axis,
.frame {
    shape-rendering: crispEdges;
}

    .axis path {
        fill: none;
        stroke: grey;
        shape-rendering: crispEdges;
    }

    .axis text {
        font-family: Arial;
        font-size: 10px;
    }

    .axis line {
        fill: none;
        stroke: grey;
        stroke-width: 1;
        shape-rendering: crispEdges;
    }

.brush .extent {
    stroke: #fff;
    fill-opacity: .125;
    shape-rendering: crispEdges;
}</code>```

```

Title: brush extents not working as expected

Body:
For some reason my chart is not getting brushed as I was hoping it would. The domain of brush.extent() seems to be working, but the bars are all flying off the page. Can someone tell me what's wrong here?

function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.select("rect").attr("x",  function(d) { return x(d.from); });
    focus.select("rect").attr("width",  function(d) {return x(d.to) - x(d.from);});
    focus.select(".x.axis").call(xAxis);
}

https://jsbin.com/layecehidu/edit?js,console,output

Body:
The problem in your code is that you're using select where you should use selectAll instead.

The obvious difference between select and selectAll, as the very name of the methods imply, is that select...

selects the first descendant element that matches the specified selector string.

... while selectAll:

Selects all elements that match the specified selector string.

That's not the only difference, though. Grouping and data propagation are less well known differences. Look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

That being said, your code should be:

function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.selectAll("rect").attr("x", function(d) {
        return x(d.from);
    })
    focus.selectAll("rect").attr("width", function(d) {
        return x(d.to) - x(d.from);
    });
    focus.select(".x.axis").call(xAxis);
}

Here is the code with that change only:

var parseDate = d3.time.format("%d-%b-%y").parse;

var data=[
 {"category": "Task 1", "from": "1-Jan-17", "to": "15-Jan-17", "progress":100, "synched": ["5-Jan-17", "7-Jan-17"]},
 {"category": "Task 2", "from": "13-Jan-17", "to": "1-Feb-17", "progress":60, "synched": ["15-Jan-17"]},
 {"category": "Task 1", "from": "1-Feb-17", "to": "11-Mar-17", "progress":90, "synched": ["2-Feb-17", "4-Feb-17"]}
]

data.forEach(function(d) {
    d.from = parseDate(d.from);
    d.to = parseDate(d.to);
});

var margin = {top: 10, right: 10, bottom: 100, left: 100},
    margin2 = {top: 330, right: 10, bottom: 30, left: 100},
    width = 900 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom,
    height2 = 400 - margin2.top - margin2.bottom;

var x = d3.time.scale().range([0, width]);
var x2 = d3.time.scale().range([0, width]);
var y = d3.scale.ordinal().rangeRoundBands([0, height], 0.2);
var y2 = d3.scale.ordinal().rangeRoundBands([0, height2], 0.2);

y.domain(data.map(function(d) { return d.category; }));
x.domain([d3.min(data,function(d){return d.from;}), d3.max(data,function(d){return d.to;})]);
x2.domain(x.domain());
y2.domain(y.domain());

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(15)
    .tickFormat(d3.time.format("%d%b"));

var xAxis2 = d3.svg.axis()
    .scale(x2)
    .orient("bottom")
    .ticks(15)
    .tickFormat(d3.time.format("%d%b"));

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var brush = d3.svg.brush()
    .x(x2)
    .on("brush", doBrush);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("defs")
    .append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("fill", "red")
    .attr("width", width)
    .attr("height", height);

var focus = svg.append("g")
var context = svg.append("g")
    .attr("transform", "translate(0," + margin2.top + ")");

var focusRectangleGroups = focus.selectAll("g")
    .data(data)
    .enter()
    .append("g");

focusRectangleGroups.append("rect")
    .attr("class", "bar")
    .attr("clip-path", "url(#clip)")
    .attr("y", function(d) { return y(d.category); })
    .attr("height", y.rangeBand())
    .attr("x", function(d) { return x(d.from); })
    .attr("width", function(d) { return x(d.to) - x(d.from); });

focus.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .append("text")
    .attr("x", width-margin.right)
    .attr("dx", ".71em")
    .attr("dy", "-0.2em")
    .text("Date");

focus.append("g")
    .attr("class", "y axis")
    .call(yAxis);

var contextRectangleGroups = context.selectAll("g")
    .data(data)
    .enter()
    .append("g");

contextRectangleGroups.append("rect")
    .attr("class", "bar")
    .attr("y", function(d) { return y2(d.category); })
    .attr("height", y2.rangeBand())
    .attr("x", function(d) { return x2(d.from); })
    .attr("width", function(d) { return x2(d.to) - x2(d.from); })
    .attr("clip-path", "url(#clip)");

context.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height2 + ")")
    .call(xAxis2);

context.append("g")
    .attr("class", "x brush")
    .call(brush)
    .selectAll("rect")
    .attr("y", -6)
    .attr("height", height2 + 7);

function doBrush() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
    focus.selectAll("rect").attr("x", function(d) { return x(d.from); })
    focus.selectAll("rect").attr("width", function(d) { return x(d.to) - x(d.from); });
    focus.select(".x.axis").call(xAxis);
}

.pending {
        fill: #e74c3c;
    }

    .bar {
        fill: #2ecc71;
    }

/*     .bar:hover, .pending:hover {
      fill: #3498db;
    } */

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }

    .legend {
        padding: 5px;
        font: 16px sans-serif;
        background: yellow;
        box-shadow: 2px 2px 1px #888;
    }

    .tooltip {
        background: #eee;
        box-shadow: 0 0 5px #999999;
        color: #333;
        font-size: 12px;
        left: 130px;
        padding: 10px;
        position: absolute;
        text-align: center;
        top: 95px;
        z-index: 10;
        display: block;
        opacity: 0;
    }
.axis,
.frame {
    shape-rendering: crispEdges;
}

    .axis path {
        fill: none;
        stroke: grey;
        shape-rendering: crispEdges;
    }

    .axis text {
        font-family: Arial;
        font-size: 10px;
    }

    .axis line {
        fill: none;
        stroke: grey;
        stroke-width: 1;
        shape-rendering: crispEdges;
    }

.brush .extent {
    stroke: #fff;
    fill-opacity: .125;
    shape-rendering: crispEdges;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

ContentLicense: CC BY-SA 4.0


问:
Using abstract class in C++ for dependency injection
With the reference of this Stackoverflow question, I'm not able to figure out the same problem of implementing DI using interface in c++ style, i.e. abstract class. Instead of bumping up old thread I created this one. Compiler throws error for the last line.</p>

```<code>class IService {
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : IService {
    void DoWork() {
        std::cout << "Work in progress inside A";
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : IService {
    void DoWork() {
        std::cout << "Work in progress inside B";
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
    Server(IService* service) : _service(service)
    { }

    // Error: this declaration has no storage class or type specifier
    // Compiler: MSVC 2017
    _service->DoWork();
};
</code>```

答:
In C++ class members are private by default.
You should specify public: before virtual void DoWork() = 0;.

C++ inheritance is private by default (when using class keyword). Instead of : IService, try : public IService. See differences between private, protected, public inheritance here.

Where is the function body of _service->DoWork();?

Body:
With the reference of this Stackoverflow question, I'm not able to figure out the same problem of implementing DI using interface in c++ style, i.e. abstract class. Instead of bumping up old thread I created this one. Compiler throws error for the last line.

class IService {
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : IService {
    void DoWork() {
        std::cout << "Work in progress inside A";
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : IService {
    void DoWork() {
        std::cout << "Work in progress inside B";
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
    Server(IService* service) : _service(service)
    { }

    // Error: this declaration has no storage class or type specifier
    // Compiler: MSVC 2017
    _service->DoWork();
};


问:
Node / Express: EADDRINUSE, Address already in use - Kill server
I have a simple server running in node.js using connect:

```<code>var server = require('connect').createServer();
//actions...
server.listen(3000);
</code>```

In my code I have actual handlers, but thats the basic idea. The problem I keep getting is

```<code>EADDRINUSE, Address already in use
</code>```

I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z.

I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.

答:
I wonder, why nobody yet mentioned this possibility:

If you provide ::listen(port) with string (intentionally or not), which wouldn't be a valid port number representation, it then can be internally converted to port number -1, ant then engine will try to connect to that -1 port, which then yields the same EADDRINUSE error, which in turn might be slightly confusing and turn you in the wrong direction for error fix search (hi, me xD).

So, debug your code and check what exactly you pass to functions, before starting to check for the processes, that are using your port.

Body:
I have a simple server running in node.js using connect:

var server = require('connect').createServer();
//actions...
server.listen(3000);

In my code I have actual handlers, but thats the basic idea. The problem I keep getting is

EADDRINUSE, Address already in use

I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z.

I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.


问:
How can I best parse this comma delimited text file?
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

```<code>bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...
</code>```

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

```<code>string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();
</code>```

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

答:
An object db is better for your solution. You can use db4o, very good open- source one.

But if you insist on using comma delimited file, take a look at this CsvReader, you can use it to read the file.

OwnerDisplayName: johnny

Body:
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

OwnerDisplayName: Sunny


问:
processing large table - how do i select the records page by page?
I need to do a process on all the records in a table. The table could be very big so I rather process the records page by page. I need to remember the records that have already been processed so there are not included in my second SELECT result.

Like this:

For first run,
 [SELECT 100 records FROM MyTable]

For second run,
 [SELECT another 100 records FROM MyTable]

and so on..

I hope you get the picture. My question is how do I write such select statement?

I'm using oracle btw, but would be nice if I can run on any other db too.
I also don't want to use store procedure.

Thank you very much!

答:
Any solution you come up with to break the table into smaller chunks, will end up taking more time than just processing everything in one go. Unless the table is partitioned and you can process exactly one partition at a time.

If a full table scan takes 1 minute, it will take you 10 minutes to break up the table into 10 pieces. If the table rows are physically ordered by the values of an indexed column that you can use, this will change a bit due to clustering factor. But it will anyway take longer than just processing it in one go.

This all depends on how long it takes to process one row from the table of course. You could chose to reduce the load on the server by processing chunks of data, but from a performance perspective, you cannot beat a full table scan.


问:
How to render a page to pdf after a redirection?
QUESTION

I am trying to get a pdf of a report from a website which needs login. So I am first logging in to the website which then redirects to the page I want access to. I need to hook the onLoadFinished function to the     page.render function. Here is the code I am using:

```<code>page.open(BASE_URL + Report_URL).then(function(status) {
        console.log(status);
        try{
            page.evaluate(function(){
                setTimeout(function(){
                document.getElementById("username").value = "admin";
                document.getElementById("password").value = "admin";
                document.getElementById("submit").click();
                },100)
            })

        page.property('onLoadFinished', function(status,page) {
            console.log('==== onLoadFinished()');
            try{
                console.log('  status: ' + status );
                page.render("report.pdf")
            }catch(ex){
                var fullMessage = "\nJAVASCRIPT EXCEPTION";
                console.log(fullMessage);
            }
        },page);
        }catch(ex){
            var fullMessage = "\nJAVASCRIPT EXCEPTION";

            console.log(fullMessage);
        }

    });
</code>```

BUT,
Nothing happens, even exception does not come.
How can this be achieved? I want to chain the onloadFinished function to another function which can render the page as pdf...pls help!!

Environment

OS: Ubuntu 14

Node version (node -v): v6.2.2

package version: npm - 3.9.5

答:
I solved it by using this.render instead of page.render.

Details here:- https://github.com/amir20/phantomjs-node/issues/675#issuecomment-312733078

Body:
QUESTION

I am trying to get a pdf of a report from a website which needs login. So I am first logging in to the website which then redirects to the page I want access to. I need to hook the onLoadFinished function to the     page.render function. Here is the code I am using:

page.open(BASE_URL + Report_URL).then(function(status) {
        console.log(status);
        try{
            page.evaluate(function(){
                setTimeout(function(){
                document.getElementById("username").value = "admin";
                document.getElementById("password").value = "admin";
                document.getElementById("submit").click();
                },100)
            })

        page.property('onLoadFinished', function(status,page) {
            console.log('==== onLoadFinished()');
            try{
                console.log('  status: ' + status );
                page.render("report.pdf")
            }catch(ex){
                var fullMessage = "\nJAVASCRIPT EXCEPTION";
                console.log(fullMessage);
            }
        },page);
        }catch(ex){
            var fullMessage = "\nJAVASCRIPT EXCEPTION";

            console.log(fullMessage);
        }

    });

BUT,
Nothing happens, even exception does not come.
How can this be achieved? I want to chain the onloadFinished function to another function which can render the page as pdf...pls help!!

Environment

OS: Ubuntu 14

Node version (node -v): v6.2.2

package version: npm - 3.9.5


问:
qt : QSqlQuery returns vector of QVariant
I am querying a sqlite db using QSqlQuery class like this :

```<code> QSqlQuery query("SELECT country FROM artist");
 while (query.next()) {
     QString country = query.value(0).toString();
     doSomething(country);
 }
</code>```

Is there a way to get vector of QVariants directly from QSqlLite class? Something like this :

```<code> QSqlQuery query("SELECT country FROM artist");
 while (query.next()) {
     std::vector< QVariant > allFields;
     allFields.push_back( query.value(0) );
     allFields.push_back( query.value(1) );
     allFields.push_back( query.value(2) );
     doSomething(allFields);
 }
</code>```

答:
Use boundValues:

```<code>QList<QVariant> allFields = query.boundValues().values();
</code>```

P.S: I wouldn't use std-containers in Qt. Qt-containers have a major advantage - implicit sharing. I would suggest using QList instead of std::vector

Body:
I am querying a sqlite db using QSqlQuery class like this :

 QSqlQuery query("SELECT country FROM artist");
 while (query.next()) {
     QString country = query.value(0).toString();
     doSomething(country);
 }

Is there a way to get vector of QVariants directly from QSqlLite class? Something like this :

 QSqlQuery query("SELECT country FROM artist");
 while (query.next()) {
     std::vector< QVariant > allFields;
     allFields.push_back( query.value(0) );
     allFields.push_back( query.value(1) );
     allFields.push_back( query.value(2) );
     doSomething(allFields);
 }

Body:
Use boundValues:

QList<QVariant> allFields = query.boundValues().values();

P.S: I wouldn't use std-containers in Qt. Qt-containers have a major advantage - implicit sharing. I would suggest using QList instead of std::vector


问:
Android Emulator blank screen after launching

I have my SDK in a separate folder in D:/Drive.

I have the already downloaded SDK, and system image for android 25

I am able to create the emulator and launch the emulator, but after launching it just gives nothing but a blank screen.

I am using Windows 10, emulator specification is very normal (x86,512Mb RAM).
Tried by enabling and disabling "Use HOST GPU".

I am getting a warning in the launch window.
1. Failed to process emu-update-last-check.ini file

答:
The issue was with the display driver. I had the default microsoft driver.
once i installed "Intel HD graphics Driver" it worked perfectly</p>


问:
singleton object in react native
I'm new in react native.I want store multiple small small strings to common singleton object class and want to access it from singleton object for all component. Can anyone help me singleton object implementation for react native.

Ex

Component 1 -- Login button -- >> success --> need to store userID into singleton object.

Component 2 --> get stored userID from singleton object. How can i implement it.

答:
Here is a simple way of doing it...

export default class CommonDataManager {

    static myInstance = null;

    _userID = "";

    /**
     * @returns {CommonDataManager}
     */
    static getInstance() {
        if (CommonDataManager.myInstance == null) {
            CommonDataManager.myInstance = new CommonDataManager();
        }

        return this.myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}
```

<p>And here is how to use it...</p>

<pre class="lang-js prettyprint-override"><code>import CommonDataManager from './CommonDataManager';

// When storing data.
let commonData = CommonDataManager.getInstance();
commonData.setUserID("User1");

// When retrieving stored data.
let commonData = CommonDataManager.getInstance();
let userId = commonData.getUserID();
console.log(userId);
</code>```

Hope this works out for you :)

Title: singleton object in react native

Body:
Here is a simple way of doing it...

export default class CommonDataManager {

    static myInstance = null;

    _userID = "";

    /**
     * @returns {CommonDataManager}
     */
    static getInstance() {
        if (CommonDataManager.myInstance == null) {
            CommonDataManager.myInstance = new CommonDataManager();
        }

        return this.myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}

And here is how to use it...

import CommonDataManager from './CommonDataManager';

// When storing data.
let commonData = CommonDataManager.getInstance();
commonData.setUserID("User1");

// When retrieving stored data.
let commonData = CommonDataManager.getInstance();
let userId = commonData.getUserID();
console.log(userId);

Hope this works out for you :)


问:
How to add onfocus function to js instead of add it in textarea tag
Hello every one i have below code and i need to to add onfocus function in javascript instead of adding it in textarea tag because it is not secure if i add it in textarea tag

Also make js code work by class of textarea (class="limittext")

```<code><html>
<head>
<title>Limit Textarea</title>
<style type="text/css">

textarea{
width:400px;
height:200px
}

</style>
<script type="text/javascript">

var alert_title='Input Restriction';

function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}

function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}

Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}

</script>
<script language="vbscript" type="text/vbs">

set_ie_alert()

Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function

</script>
</head>
<body>
<textarea class="limittext" onfocus="limitTextarea(this,2,0)" wrap="off">some text</textarea>
</body>
</html>
</code>```

答:
I don't know if this the best solution or not. I failed to make it work by class but i enabled to make that code work by using ID and do some editions on js code

Thank you for all try to help me

https://jsfiddle.net/zf155z9y/3/

```<code><html>
<head>
<title>Limit Textarea</title>
<style type="text/css">

textarea{
width:400px;
height:200px
}

</style>
<script language="vbscript" type="text/vbs">

set_ie_alert()

Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function

</script>
</head>
<body>
<textarea id="myForm" wrap="off">some text</textarea>
<script type="text/javascript">

var alert_title='Input Restriction';
var x = document.getElementById('myForm');
x.addEventListener("focusin", limitTextarea);

function limitTextarea(){
var el = this;
var maxLines = 5;
var maxChar = 0;
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}

function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}

Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}

</script>
</body>
</html>
</code>```

Body:
Hello every one i have below code and i need to to add onfocus function in javascript instead of adding it in textarea tag because it is not secure if i add it in textarea tag

Also make js code work by class of textarea (class="limittext")

<title>Limit Textarea</title>

<textarea class="limittext" onfocus="limitTextarea(this,2,0)" wrap="off">some text</textarea>

Body:
I don't know if this the best solution or not. I failed to make it work by class but i enabled to make that code work by using ID and do some editions on js code

Thank you for all try to help me

https://jsfiddle.net/zf155z9y/3/

<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">

textarea{
width:400px;
height:200px
}

</style>
<script language="vbscript" type="text/vbs">

set_ie_alert()

Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function

</script>
</head>
<body>
<textarea id="myForm" wrap="off">some text</textarea>
<script type="text/javascript">

var alert_title='Input Restriction';
var x = document.getElementById('myForm');
x.addEventListener("focusin", limitTextarea);

function limitTextarea(){
var el = this;
var maxLines = 5;
var maxChar = 0;
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}

function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}

Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}

</script>
</body>
</html>


问:
iterate on scala list and treating last iteration differently
I have a list of objects that I am calling toString on, and would like to treat the last object differently as follows:

```<code>o1 = Array(...)
o2 = Array(...) // same length as o1
sb = new StringBuilder()
for (i <- 0 to o1.size() - 1)
  sb.append(o1.get(i).toString() + " & " o2.get(i).toString())
  // if not last iteration then append ", "
</code>```

is there a simple way to write this in scala rather than checking value of i etc?

答:
@jwvh's anwser is good.

just give another pattern-matching version.

```<code>o1.zip(o2).map{case (item1, item2) => s"$item1 & $item2"}.mkString(", ")
</code>```

Body:
I have a list of objects that I am calling toString on, and would like to treat the last object differently as follows:

o1 = Array(...)
o2 = Array(...) // same length as o1
sb = new StringBuilder()
for (i <- 0 to o1.size() - 1)
  sb.append(o1.get(i).toString() + " & " o2.get(i).toString())
  // if not last iteration then append ", "

is there a simple way to write this in scala rather than checking value of i etc?

Body:
@jwvh's anwser is good.

just give another pattern-matching version.

o1.zip(o2).map{case (item1, item2) => s"$item1 & $item2"}.mkString(", ")


问:
Symfony json_login not working
I wanted to try the new json_login with Symfony 3.3..followed the docs with a clean project..but the firewall totally ignores the json_login section. I am receiving an error saying the controller did not return a response.

I am pasting my security.yml bellow ..

```<code>security:
providers:
    db_provider:
        entity:
            class: IgsemAuthBundle:User
            property: email
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_USER:        IS_AUTHENTICATED_ANONYMOUSLY
encoders:
    Igsem\AuthBundle\Entity\User:
        algorithm: bcrypt
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: ~
        provider: db_provider
        json_login:
            check_path: check
access_control:
    - { path: ^/secure, roles: ROLE_ADMIN }
</code>```

I also have a controller with with the check route annotated:

```<code> /**
 * @Route("/check", name="check")
 */
public function checkAction(Request $request, AuthenticationUtils $authUtils)
{
}
</code>```

I tried to play around with the path, used name but also relative path login or /login and some other combinations..al with the same

thanks for the help

答: Until the Symfony docs are not updated, the json_login option requires a success_handler and a failure_handler..otherwise it will throw an error..it is not enough to just define a target route..I already raised a PR it should be fixed soon</p>

Title: Symfony json_login not working

Body:
I wanted to try the new json_login with Symfony 3.3..followed the docs with a clean project..but the firewall totally ignores the json_login section. I am receiving an error saying the controller did not return a response.

I am pasting my security.yml bellow ..

security:
providers:
    db_provider:
        entity:
            class: IgsemAuthBundle:User
            property: email
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_USER:        IS_AUTHENTICATED_ANONYMOUSLY
encoders:
    Igsem\AuthBundle\Entity\User:
        algorithm: bcrypt
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: ~
        provider: db_provider
        json_login:
            check_path: check
access_control:
    - { path: ^/secure, roles: ROLE_ADMIN }

I also have a controller with with the check route annotated:

 /**
 * @Route("/check", name="check")
 */
public function checkAction(Request $request, AuthenticationUtils $authUtils)
{
}

I tried to play around with the path, used name but also relative path login or /login and some other combinations..al with the same

thanks for the help


问:
Regex for phone number validation with min and max length check
I need a simple javascript regex to validate phone numbers.
Only digits, "+" at the beginning and "-"

Max and min length of digits should be 10 - 12

The next phones should be allowed:

1. +380631505624

2. 0631505624

3. 063-15-05-624

The next phones should be NOT allowed:

1. +38063+1505624

2. asd0631505624

3. -063-15-05-624-

4. +0---3-1--24

答:
In above code there has no any lenght validation, so I am just correcting the above answer

http://jsfiddle.net/KRwHQ/4/

```<code> if (/^\+?((\d\-|\d)+\d){4,}$/ig.test("+43595-995-995")){
     alert("GOOD");
 }
</code>```

Body:
In above code there has no any lenght validation, so I am just correcting the above answer

http://jsfiddle.net/KRwHQ/4/

 if (/^\+?((\d\-|\d)+\d){4,}$/ig.test("+43595-995-995")){
     alert("GOOD");
 }


问:
Asp MVC 2: Obfusicate Entity-IDs
Project type: Asp MVC 2/NHibernate/C#

Problem

If you have an edit page in an web application you will come to the problem that you have to send and then receive the id of the entity you're editing, the IDs of sub-entities, entities that can be selected by dropdownmenus,...

As it is possible to modify a form-post, an evil user could try to send back another ID which maybe would grant him more rights (if i.e. that ID was related to a security entity).

My approach

Create a GUID and associate it with the ID

Save the association in the http session

Wait for the response and extract the real ID out of the received GUID.

Question:

What techniques do you use to obfusicate an entity-ID?

答: Your controllers should be immune to modified POST data. Before displaying or modifying records belonging to a user, you should always check whether the records in question belong to the authenticated user.</p>

Title: Asp MVC 2: Obfusicate Entity-IDs


问:
How to fetch images from firebase storage and show as a thumbnail?
I want to develop an application in which recycler listview fetch data from firebase database shows details to user like name, age, city and profile picture.

How to get profile picture from firebase storage and show in recycler list view and show as thumbnail.

```<code>     @Override
     public void onBindViewHolder(final UserViewHolder holder, final int position, Context context) {

    this.context = context;

    final BusinessDetailModel businessDetailModel = list.get(position);

    Picasso.with(context).load(list.get(position).getImageUrl()).resize(80, 80).into(holder.thumbnail);
    holder.businessName.setText(businessDetailModel.businessName);
    holder.businessCity.setText(businessDetailModel.city);
    holder.businessRating.setText(businessDetailModel.ratingValue + "");
</code>```

Solution,

You can add global variable:

```<code>   private Context context;
</code>```

then assign the context from here:

```<code>   @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);

ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}
</code>```

答:
You first need to get the download url and use a image loading library to fetch and display the image.

I would recommend using Picasso

Body:
I want to develop an application in which recycler listview fetch data from firebase database shows details to user like name, age, city and profile picture.

How to get profile picture from firebase storage and show in recycler list view and show as thumbnail.

     @Override
     public void onBindViewHolder(final UserViewHolder holder, final int position, Context context) {

    this.context = context;

    final BusinessDetailModel businessDetailModel = list.get(position);

    Picasso.with(context).load(list.get(position).getImageUrl()).resize(80, 80).into(holder.thumbnail);
    holder.businessName.setText(businessDetailModel.businessName);
    holder.businessCity.setText(businessDetailModel.city);
    holder.businessRating.setText(businessDetailModel.ratingValue + "");

Solution,

You can add global variable:

   private Context context;

then assign the context from here:

   @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);

ViewHolder vh = new ViewHolder(v);
// set the Context here
context = parent.getContext();
return vh;
}


问:
Can I redirect a request with code 302 to another port without using the HOST variable?
In the HTTP protocol, there are multiple status codes that can be used to redirect a request to another URL, such as 301 Moved Permanently or 302 Found. To my knowledge, the target URL can either contain a host (http://example.com/example.html) or let the host implicitly be the current host (/example.html).

When using the first form, one can redirect to a non-standard port (http://example.com:8080/example.html). How can this be done when not specifying the host?

Currently, I parse the HOST request header and build the new URL. But AFAIK, that header is not strictly required to be sent, so I want to avoid it.

答: You can't specify just the port in a redirect. And yes, the "Host" header field is strictly required in HTTP/1.1.


问:
SQL conditional that searches for substring and returns 'true' or 'false'
I need to do a mapping that is taxing my handle on SQL.

I need to know if a substring exists in a CSV contained in a table cell.  If so, I need it to return the string 'true' else 'false'

This query works in that it returns the CSV I need to check:

```<code>select table.value from table where table.user_id = 1 and table.keyname = 'email_list'
</code>```

I was attempting to include that SQL inside a conditional like this:

```<code>IF ( (select table.value from table where table.user_id = 1 and
table.keyname = 'email_list') LIKE '%substring%') THEN 'true' ELSE 'false'
</code>```

But no luck so far. This is actually one component of a much bigger query mapping different elements from one table to another so I really need it to just return a string of 'true' or 'false' for it to work appropriately.

Table structure looks something like this:

```<code>User   KEYNAME        value (in the form of CSV)
1       email_list   george@gmail.com, george@yahoo.com
2       email_list
3       email_list   kiley@yahoo.com
4       email_list   kim@gmail.com, kimmy@hotmail.com, wondergirl@yahoo.com
</code>```

答:
Using a CASE statement inside the select clause should solve your problem.

Something like the below

```<code>select case when table.value LIKE '%substring%'
        then 'TRUE' else 'FALSE' end as "Result"
from table where table.user_id = 1 and
table.keyname = 'email_list'
</code>```

Body:
I need to do a mapping that is taxing my handle on SQL.

I need to know if a substring exists in a CSV contained in a table cell.  If so, I need it to return the string 'true' else 'false'

This query works in that it returns the CSV I need to check:

select table.value from table where table.user_id = 1 and table.keyname = 'email_list'

I was attempting to include that SQL inside a conditional like this:

IF ( (select table.value from table where table.user_id = 1 and
table.keyname = 'email_list') LIKE '%substring%') THEN 'true' ELSE 'false'

But no luck so far. This is actually one component of a much bigger query mapping different elements from one table to another so I really need it to just return a string of 'true' or 'false' for it to work appropriately.

Table structure looks something like this:

User   KEYNAME        value (in the form of CSV)
1       email_list   george@gmail.com, george@yahoo.com
2       email_list
3       email_list   kiley@yahoo.com
4       email_list   kim@gmail.com, kimmy@hotmail.com, wondergirl@yahoo.com

Body:
Using a CASE statement inside the select clause should solve your problem.

Something like the below

select case when table.value LIKE '%substring%'
        then 'TRUE' else 'FALSE' end as "Result"
from table where table.user_id = 1 and
table.keyname = 'email_list'


问:
TYPO3 Contact form plugin exists twice, also submitted twice
I have a submit form that is once displayed in a PopUp and once shown normal on the page. So I created it in a storage folder and used "insert record" for said plugin twice.

When I submit one of the shown forms, it will be executed twice. Anyone ever had this kind of problem?

The contact request form is selfmade.

答:
try to modify your plugin so you can configure it to only show the form.then you use two different CEs: one to show only the form, the second to show the form and to handle the submit.

Other possibility: while you are handling the form store the information about handling somewhere and avoid a second handling on the same call


问:
JavaScript Array `console.log` output behaviour
When we run a forEach() function on an array depending on the way the index & items are arranged dev tools returns different output. I'm wondering if anyone knows why this happens.

Please see the images below:

When I swap the variables over from item, index to index, item the output looks different.

I wonder what makes the variable output different and why.

答:
According to MDN documentation regarding console.log here

This explains that the first parameter is handled either as an object or a string. Subsequent parameters are handled as objects.

I assume this forces the strings, from the second parameter onward, to print with quotes.

To read more about the chrome-console, visit this page


问:
Combining date based on four different tables in SQL environment
Master_table                           Table_A

```<code> ID   Problem    Date              ID   Problem     Date
101      123    01-02-1993        101       123   01-02-1993
101      124                      101       124
102      125                      102       125   07-02-1994
103      126    08-22-1999        103       126   08-22-1999
103      131                      103       131   08-09-1999
</code>```

Table_B                                Table_C

```<code> ID   Problem    Date              ID   Problem     Date
101      124                      101       124
102      125    06-30-1994        102       125
103      126    08-22-1999        103       131   08-08-1999
103      131    08-09-1999        106       137   02-02-1987
106      137    01-02-1987        110       145   12-22-1995
</code>```

I need to create a new table named ‘final_table’ such that all observations in Master_table have a date. Rule for achieving this: Date from Master_table will be used as the date when Date exists. Otherwise, the minimum Date from Table_A, Table_B and Table_C will be used. If Date is missing in all the tables then drop the observation.

Desired Output

```<code>ID   Problem    Date
101      123    01-02-1993
102      125    06-30-1994
103      126    08-22-1999
103      131    08-08-1999
</code>```

What I've tried

```<code>SELECT ID, Problem, MIN(Date) as Date
FROM
(   SELECT ID, Problem, Date
    FROM Table_A
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_B
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_C
) as subQuery
Delete From table Where Date IS NULL
</code>```

答:
Seeme you need  a union between the 3 tables this way</p>

```<code>    select id, problem, data
    from Table_A
    where date is not null
    union
    select id, problem, min(data)
    from Table_B
    group by id, problem
    where date is not null
    union
    select id, problem, min(data)
    from Table_B
    group by id, problem
    where date is not null
</code>```

Body:
Master_table                           Table_A

 ID   Problem    Date              ID   Problem     Date
101      123    01-02-1993        101       123   01-02-1993
101      124                      101       124
102      125                      102       125   07-02-1994
103      126    08-22-1999        103       126   08-22-1999
103      131                      103       131   08-09-1999

Table_B                                Table_C

 ID   Problem    Date              ID   Problem     Date
101      124                      101       124
102      125    06-30-1994        102       125
103      126    08-22-1999        103       131   08-08-1999
103      131    08-09-1999        106       137   02-02-1987
106      137    01-02-1987        110       145   12-22-1995

I need to create a new table named ‘final_table’ such that all observations in Master_table have a date. Rule for achieving this: Date from Master_table will be used as the date when Date exists. Otherwise, the minimum Date from Table_A, Table_B and Table_C will be used. If Date is missing in all the tables then drop the observation.

Desired Output

ID   Problem    Date
101      123    01-02-1993
102      125    06-30-1994
103      126    08-22-1999
103      131    08-08-1999

What I've tried

SELECT ID, Problem, MIN(Date) as Date
FROM
(   SELECT ID, Problem, Date
    FROM Table_A
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_B
    UNION ALL
    SELECT ID, Problem, Date
    FROM Table_C
) as subQuery
Delete From table Where Date IS NULL

Body:
Seeme you need  a union between the 3 tables this way

    select id, problem, data
    from Table_A
    where date is not null
    union
    select id, problem, min(data)
    from Table_B
    group by id, problem
    where date is not null
    union
    select id, problem, min(data)
    from Table_B
    group by id, problem
    where date is not null


问:
Multithreaded C++ Program Not Running In Parallel Using vector<thread> and .join()
Note: This is the first post I have made on this site, but I have searched extensively and was not able to find a solution to my problem.
I have written a program which essentially tests all permutations of a vector of numbers to find an optimal sequence as defined by me. Of course, computing permutations of numbers is very time consuming even for small inputs, so I am trying to speed things up by using multithreading.

Here is a small sample which replicates the problem:

```<code>class TaskObject {
public:
    void operator()() {
        recursiveFunc();
    }
private:
    Solution *bestSolution; //Shared by every TaskObject, but can only be accessed by one at a time
    void recursiveFunc() {
        if (base_case) {
            //Only part where shared object is accessed
            //base_case is rarely reached
            return;
        }
        recursiveFunc();
    }
};

void runSolutionWithThreads() {
    vector<thread> threads(std::thread::hardware_concurrency());
    vector<TaskObject> tasks_vector(std::thread::hardware_concurrency());
    updateTasks(); //Sets parameters that intialize the first call to recursiveFunc
    for (int q = 0; q < (int)tasks_vector.size(); ++q) {
        threads[q] = std::thread(tasks_vector[q]);
    }
    for (int i = 0; i < (int)threads.size(); ++i) {
        threads[i].join();
    }
}
</code>```

I imagined that this would enable all threads to run in parallel, but I can see using the performance profiler in visual studio and in the advanced settings of windows task manager that only 1 thread is running at a time. On a system with access to 4 threads, the CPU gets bounded at 25%. I get correct output every time I run, so there are no issues with the algorithm logic. Work is spread out as evenly as possible among all task objects. Collisions with shared data rarely occur. Program implementation with thread pool always ran at nearly 100%.

The objects submitted to the threads don't print to cout and all have their own copies of the data required to perform their work except for one shared object they all reference by pointer.

```<code>private:
    Solution* bestSolution;
</code>```

This shared data is not susceptible to a data race condition since I used lock_guard from mutex to make it so only one thread can update bestSolution at a time.

In other words, why isn't my CPU running at nearly 100% for my multithreaded program which uses as many threads as there are available in the system?

I can readily update this post with more information if needed.

答:
In debugging your application, use the debugger to "break all" threads.   Then examine each thread with the debug thread window to see where each thread is executing.   Likely you will find that only one thread is executing code, while the rest are all blocked on the mutex that the one running thread is holding.

If you show a more complete example of the code it can greatly assist.

Body:
Note: This is the first post I have made on this site, but I have searched extensively and was not able to find a solution to my problem.
I have written a program which essentially tests all permutations of a vector of numbers to find an optimal sequence as defined by me. Of course, computing permutations of numbers is very time consuming even for small inputs, so I am trying to speed things up by using multithreading.

Here is a small sample which replicates the problem:

class TaskObject {
public:
    void operator()() {
        recursiveFunc();
    }
private:
    Solution *bestSolution; //Shared by every TaskObject, but can only be accessed by one at a time
    void recursiveFunc() {
        if (base_case) {
            //Only part where shared object is accessed
            //base_case is rarely reached
            return;
        }
        recursiveFunc();
    }
};

void runSolutionWithThreads() {
    vector<thread> threads(std::thread::hardware_concurrency());
    vector<TaskObject> tasks_vector(std::thread::hardware_concurrency());
    updateTasks(); //Sets parameters that intialize the first call to recursiveFunc
    for (int q = 0; q < (int)tasks_vector.size(); ++q) {
        threads[q] = std::thread(tasks_vector[q]);
    }
    for (int i = 0; i < (int)threads.size(); ++i) {
        threads[i].join();
    }
}

I imagined that this would enable all threads to run in parallel, but I can see using the performance profiler in visual studio and in the advanced settings of windows task manager that only 1 thread is running at a time. On a system with access to 4 threads, the CPU gets bounded at 25%. I get correct output every time I run, so there are no issues with the algorithm logic. Work is spread out as evenly as possible among all task objects. Collisions with shared data rarely occur. Program implementation with thread pool always ran at nearly 100%.

The objects submitted to the threads don't print to cout and all have their own copies of the data required to perform their work except for one shared object they all reference by pointer.

private:
    Solution* bestSolution;

This shared data is not susceptible to a data race condition since I used lock_guard from mutex to make it so only one thread can update bestSolution at a time.

In other words, why isn't my CPU running at nearly 100% for my multithreaded program which uses as many threads as there are available in the system?

I can readily update this post with more information if needed.


问:
Using same javascript function to change preview of multiple image upload
I have written code which allows user to upload multiple file upload :

```<code><asp:Image ID="image01" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image01_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image02" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image02_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image03" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image03_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image04" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image04_update" runat="server" onchange="showPreview(this);"/>
</code>```

The javascript function which shows preview for uploaded image is as follows :

```<code>function showPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image01').css('visibility', 'visible');
                $('#image01').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</code>```

currently preview is working for first image upload only, as i am passing ID- #image01.

I want to use same javascript function to show preview for all four image uploaders.
i.e. when i upload first image from #image01, it must show it's preview, for 2nd it must show 2nd image's preview.. and so on....

NOTE : i am using image upload in form editing mode, if there is no image uploaded ,

```<code>onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"
</code>```

this code will show an alternate image.

答:
```<code>function showPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $(input).prev().css('visibility', 'visible');
                $(input).prev().attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</code>```

Body:
I have written code which allows user to upload multiple file upload :

<asp:Image ID="image01" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image01_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image02" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image02_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image03" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image03_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image04" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image04_update" runat="server" onchange="showPreview(this);"/>

The javascript function which shows preview for uploaded image is as follows :

function showPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image01').css('visibility', 'visible');
                $('#image01').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

currently preview is working for first image upload only, as i am passing ID- #image01.

I want to use same javascript function to show preview for all four image uploaders.
i.e. when i upload first image from #image01, it must show it's preview, for 2nd it must show 2nd image's preview.. and so on....

NOTE : i am using image upload in form editing mode, if there is no image uploaded ,

onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"

this code will show an alternate image.


问:
connecting to flask app over VPN
I am new to Flask and please do not mind if the problem sounds trivial.
I have a Flask app (not written by me) which works fine from the local machine as well as remote machines as well when I am directly connected to the network.

But when I connect to the app over VPN it doesn't work. I am able to ssh on that machine as well as access other servers running on the same machine. It is a physical machine and not a VM

```<code>app = Flask(__name__)

def loadAppVariables():
      mc = pylibmc.Client(["127.0.0.1"], binary=True,
      behaviors={"tcp_nodelay": True,
      "ketama": True});
      app.mc=mc

def initApp():
    app.fNet= {some object }
    mc = pylibmc.Client(["127.0.0.1"], binary=True,
    behaviors={"tcp_nodelay": True,
    "ketama": True});
    app.mc=mc;

@app.route('/classify', methods=['POST'])
def classify():
        # We will save the file to disk for possible data collection.
        imagefile = request.files['imagefile']
        processImageFile(imagefile)

@app.route('/')
def index():
    return render_template('cindex.html', has_result=False)

@app.before_request
def before_request():
    loadAppVariables()

@app.teardown_request
def teardown_request(exception):
    storeAppVariables()

if __name__ == '__main__':
    initApp();
    app.run(debug=False,host='0.0.0.0')
</code>```

I am running latest Flask version and python 2.7. Can anyone please suggest what may be wrong here ?

答:
It seems that you want to access to local enabled flask over another network.
0.0.0.0 ip is to connect to flask from different machines, but in the same network range. so if your IP isn't in the same range, this fails.

if you want to access your web page from the internet, you should consider to deploy your webapp.

Title: connecting to flask app over VPN

Body:
I am new to Flask and please do not mind if the problem sounds trivial.
I have a Flask app (not written by me) which works fine from the local machine as well as remote machines as well when I am directly connected to the network.

But when I connect to the app over VPN it doesn't work. I am able to ssh on that machine as well as access other servers running on the same machine. It is a physical machine and not a VM

app = Flask(__name__)

def loadAppVariables():
      mc = pylibmc.Client(["127.0.0.1"], binary=True,
      behaviors={"tcp_nodelay": True,
      "ketama": True});
      app.mc=mc

def initApp():
    app.fNet= {some object }
    mc = pylibmc.Client(["127.0.0.1"], binary=True,
    behaviors={"tcp_nodelay": True,
    "ketama": True});
    app.mc=mc;

@app.route('/classify', methods=['POST'])
def classify():
        # We will save the file to disk for possible data collection.
        imagefile = request.files['imagefile']
        processImageFile(imagefile)

@app.route('/')
def index():
    return render_template('cindex.html', has_result=False)

@app.before_request
def before_request():
    loadAppVariables()

@app.teardown_request
def teardown_request(exception):
    storeAppVariables()

if __name__ == '__main__':
    initApp();
    app.run(debug=False,host='0.0.0.0')

I am running latest Flask version and python 2.7. Can anyone please suggest what may be wrong here ?


问:
Yii2 relation between three table using ActiveRecord
I have three tables in mysql database like this picture below :

Now, with gii, I create those model like this :

For table BuktiPenerimaan

```<code>class BuktiPenerimaan extends \yii\db\ActiveRecord{
/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReports()
{
    return $this->hasMany(InvoiceReport::className(), ['bukti_penerimaan_id' => 'id']);
}
}
</code>```

And InvoiceReports:

```<code>class InvoiceReport extends \yii\db\ActiveRecord{

/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReportDetails()
{
    return $this->hasMany(InvoiceReportDetail::className(), ['invoice_id' => 'id']);
}
</code>```

My question is, how to access all record in table invoice_report_detail if I created an object that came from BuktiPenerimaan.

I use like this :

```<code>$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist
$dataInvoiceDetail = $model->invoiceReports->invoiceReportDetails // failed, always null.
</code>```

Please advixe

答:
$dataInvoice  = $model->invoiceReports; is  Array of InvoiceReport object.

You need to loop over each InvoiceReport to get related InvoiceReportDetail.

```<code>$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist , but array of objects
$dataInvoiceDetail = [];
foreach($dataInvoice as $dInvoice):
   $dataInvoiceDetail[] = array_merge($dataInvoiceDetail,$dInvoice->invoiceReportDetails );
endforeach;
// $dataInvoiceDetail contains all invoice_report_detail
</code>```

Body:
I have three tables in mysql database like this picture below :

Now, with gii, I create those model like this :

For table BuktiPenerimaan

class BuktiPenerimaan extends \yii\db\ActiveRecord{
/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReports()
{
    return $this->hasMany(InvoiceReport::className(), ['bukti_penerimaan_id' => 'id']);
}
}

And InvoiceReports:

class InvoiceReport extends \yii\db\ActiveRecord{

/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReportDetails()
{
    return $this->hasMany(InvoiceReportDetail::className(), ['invoice_id' => 'id']);
}

My question is, how to access all record in table invoice_report_detail if I created an object that came from BuktiPenerimaan.

I use like this :

$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist
$dataInvoiceDetail = $model->invoiceReports->invoiceReportDetails // failed, always null.

Please advixe

Body:
$dataInvoice  = $model->invoiceReports; is  Array of InvoiceReport object.

You need to loop over each InvoiceReport to get related InvoiceReportDetail.

$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist , but array of objects
$dataInvoiceDetail = [];
foreach($dataInvoice as $dInvoice):
   $dataInvoiceDetail[] = array_merge($dataInvoiceDetail,$dInvoice->invoiceReportDetails );
endforeach;
// $dataInvoiceDetail contains all invoice_report_detail