问:
method of getting valid fullscreen resolutions on OS X in Objective-C or C++?
I'm making a game and I'd like to get a list of valid fullscreen resolutions for the launcher. I can't find any way of doing this for Mac OS X;

Like in the system preferences Displays pane.

Is it possible?

答:
In C++ http://specialmeaning.blogspot.com/2016/07/yes-apple-i-did-it.html</p>

```<code>#include <iostream>
#include <CoreGraphics/CoreGraphics.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    auto mainDisplayId = CGMainDisplayID();

    std::cout << "Current resolution was "
    << CGDisplayPixelsWide(mainDisplayId) << 'x'
    << CGDisplayPixelsHigh(mainDisplayId) << std::endl
    << "Supported resolution modes:";

    auto modes = CGDisplayCopyAllDisplayModes(mainDisplayId, nullptr);
    auto count = CFArrayGetCount(modes);
    CGDisplayModeRef mode;
    for(auto c=count;c--;){
        mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, c);
        auto w = CGDisplayModeGetWidth(mode);
        auto h = CGDisplayModeGetHeight(mode);
        std::cout << std::endl << w << 'x' << h;
    }
    CGDisplaySetDisplayMode(mainDisplayId, mode, nullptr);
    std::cout << " is the selected top one." << std::endl;
    std::cin.get();
    return 0;

}
</code>```

Body:
In C++ http://specialmeaning.blogspot.com/2016/07/yes-apple-i-did-it.html

#include <iostream>
#include <CoreGraphics/CoreGraphics.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    auto mainDisplayId = CGMainDisplayID();

    std::cout << "Current resolution was "
    << CGDisplayPixelsWide(mainDisplayId) << 'x'
    << CGDisplayPixelsHigh(mainDisplayId) << std::endl
    << "Supported resolution modes:";

    auto modes = CGDisplayCopyAllDisplayModes(mainDisplayId, nullptr);
    auto count = CFArrayGetCount(modes);
    CGDisplayModeRef mode;
    for(auto c=count;c--;){
        mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, c);
        auto w = CGDisplayModeGetWidth(mode);
        auto h = CGDisplayModeGetHeight(mode);
        std::cout << std::endl << w << 'x' << h;
    }
    CGDisplaySetDisplayMode(mainDisplayId, mode, nullptr);
    std::cout << " is the selected top one." << std::endl;
    std::cin.get();
    return 0;

}


来源: stackexchange

问:
requests to HTTPS work while requests to HTTP do not work
I have a web application running on Apache/Tomcat on a cloud with Linux (Digital Ocean). It had a domain name - example.com. I've encrypted both example.com and www.example.com using Let's Encrypt and now requests to https://example.com and to https://www.example.com work.

Then I wanted to redirect HTTP requests to HTTPS. But noticed that for some reason requests to http://example.com and to http://www.example.com do not work, and I'm not getting any response from my server. I tried to play with Apache configuration files of VirtualHost, but nothing worked for me so far.

Using tcpdump I see that I am receiving requests on port 80 on the server, but nothing happens except that.

What might be the reason for requests to HTTPS to work while requests to HTTP not to work?

Thanks.

答: Well, if someone else encounters this behavior - the reason for it was the firewall - port 443 (used by HTTPS) was open but port 80 (used for HTTP) was simply closed. Opening it solved it.</p>

ContentLicense: CC BY-SA 3.0


问:
Trying to connect JS and HTML. Receiving ERR_FILE NOT_FOUND
I'm a relative beginner so apologies if this is a dumb question. I have no idea if I'm using the wrong path while trying to link my JS to HTML. I've tried absolute paths, adding the files to a JS folder in the root folder. I can't even get jQuery to link. Here's a snippet:</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Guessing Game</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-theme.css">
    <!-- Bootstrap and CSS here-->

  </head>
  <body>

      <div id='app' class='center' class='container'>

        <div id='headers'>
          <!-- Title and subtitles! -->
          <h1 id='title'> Rav's Cheesy Guessing Game! </h1>
          <h2 id='subtitle'> Guess A Number Between 1-100, You Won't </h2>
        </div>

        <div id='main'>
          <div id='input-parent'>
            <!-- Player's guess input, and submit button -->
            <input id='player-input' class='center' placeholder="#" autofocus maxlength=2></input>
            <button id='submit-button' type=submit>Go!</button>
          </div>

          <div id='guesses'>
            <ul id='guess-list'>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
              <li class='guess'>_</li>
            </ul>
            <!-- unordered list of guesses -->
          </div>

          <div id="menu-btns">
            <!-- reset and hint buttons -->
            <button id='reset' class='btn btn-warning btn-sm'>Reset</button>
            <button id='hint' class='btn btn-primary btn-sm'>Hint</button>
          </div>
        </div>
      </div>

    <div id='footer' class='center' class="container">
        <div class="row">
          <div class='col-md-4 col-sm-4'>
            <img src='fa-logo@2x.png'>
          </div>

          <div class='col-md-4 col-sm-4'>
            <h4>Project by Ravish Rawal</h4>
          </div>

          <div class='col-md-4 col-sm-4'>
            <img src='grace_hopper_academy.png'>
          </div>

        </div>
    </div>
    <script type='text/javascript' src='js/jquery.min.js'></script>
    <script type='text/javascript' src='js/GuessingGame.js'></script>
  </body>
</html>
</code>```

答: If your using IIS (a localhost), there could be any number of things wrong. For now, just check the paths. You can use literally copy the path of it in file explorer (if on windows).</p>

Body:
I'm a relative beginner so apologies if this is a dumb question. I have no idea if I'm using the wrong path while trying to link my JS to HTML. I've tried absolute paths, adding the files to a JS folder in the root folder. I can't even get jQuery to link. Here's a snippet:

<!DOCTYPE html>

    <title>Guessing Game</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-theme.css">

 Rav's Cheesy Guessing Game!

 Guess A Number Between 1-100, You Won't

            <input id='player-input' class='center' placeholder="#" autofocus maxlength=2></input>
            <button id='submit-button' type=submit>Go!</button>

_

_

_

_

_

            <button id='reset' class='btn btn-warning btn-sm'>Reset</button>
            <button id='hint' class='btn btn-primary btn-sm'>Hint</button>

Project by Ravish Rawal


问:
How to count records with only a specific number of keys
I have a user model in MongoDB looks like such:

```<code>{ _id: <some_id>,
  name: <some_name>,
  preferences: <this is an object with 1-20 key values pair>
}
</code>```

I would like to get the count of the users with all preferences keys present (# of users with 20 keys in the preferences.)
how would I go about querying that?

答:
If you have the latest MongoDB 3.4 then you can do this in an aggregation statement with $objectToArray:

Model.aggregate([
  { "$group": {
    "_id": null,
    "count": {
      "$sum": {
        "$cond": {
          "if": { "$eq": [
             { "$size": {
               "$objectToArray": { "$ifNull": [ "$preferences", { } ] }
             }},
             20
          ]},
          "then": 1,
          "else": 0
        }
      }
    }
  }}
])
```

<p>The new operator <code>$objectToArray</code> will take an object of "key/value" pairs and turn this into an array. So this:</p>

<pre class="lang-js prettyprint-override"><code> { "a": 1, "b": 2 }
</code>```

Becomes this:

 [ { "k": "a", "v": 1 }, { "k": "b", "v": 2 } ]
```

<p>As an array, you can use operators like <code>$size</code> to count the number of "keys", which is now equal to the entries in the array.</p>

<p>For earlier versions you can use a <code>$where</code> condition in JavaScript evaluation:</p>

<pre class="lang-js prettyprint-override"><code>Model.find(function() {
  return (this.hasOwnProperty("preferences")) ?
    Object.keys(this.preferences).length == 20 : false;
}).count()
</code>```

The latter not really being an "aggregation", but the cursor count is really all you can get from a JavaScript evaluation.

Body:
I have a user model in MongoDB looks like such:

{ _id: <some_id>,
  name: <some_name>,
  preferences: <this is an object with 1-20 key values pair>
}

I would like to get the count of the users with all preferences keys present (# of users with 20 keys in the preferences.)
how would I go about querying that?

Body:
If you have the latest MongoDB 3.4 then you can do this in an aggregation statement with $objectToArray:

Model.aggregate([
  { "$group": {
    "_id": null,
    "count": {
      "$sum": {
        "$cond": {
          "if": { "$eq": [
             { "$size": {
               "$objectToArray": { "$ifNull": [ "$preferences", { } ] }
             }},
             20
          ]},
          "then": 1,
          "else": 0
        }
      }
    }
  }}
])

The new operator $objectToArray will take an object of "key/value" pairs and turn this into an array. So this:

 { "a": 1, "b": 2 }

Becomes this:

 [ { "k": "a", "v": 1 }, { "k": "b", "v": 2 } ]

As an array, you can use operators like $size to count the number of "keys", which is now equal to the entries in the array.

For earlier versions you can use a $where condition in JavaScript evaluation:

Model.find(function() {
  return (this.hasOwnProperty("preferences")) ?
    Object.keys(this.preferences).length == 20 : false;
}).count()

The latter not really being an "aggregation", but the cursor count is really all you can get from a JavaScript evaluation.


问:
unable to connect to Genymotion server. please check your internet connection
When I am trying to open Genymotion, this dialogue appear:

How can I solve this?

答: For me the problem resolved after confirming my email address. Search your mail for a letter with activation link and then restart genymotion.</p>


问:
Java - Window Image
Does anyone know how to capture a screen shot in Java (not it's own screen, but any other window on the desktop and they don't necessarily have to be the active window) in Windows? There are a number of threads here on this similar subject, but I have yet to find an answer.

I've tried using JNA, but became stuck after a few attempts. For example...

```<code>public class Main {

    public static void main(String[] args) {
        Main m = new Main();

        List<WindowInfo> list = m.getWindows();

        for (int i=0;i<list.size();i++)
        {
            WindowInfo info = list.get(i);
            System.out.println(info.getTitle());
        }

        WindowInfo wi = list.get(0);

        W32API.HDC hdcSrc = User32.instance.GetWindowDC(wi.getHwnd());

        W32API.HDC hdcMemory = Gdi32.instance.CreateCompatibleDC(hdcSrc);

        //W32API.HBITMAP hBitmapMemory = Gdi32.instance.CreateCompatibleBitmap(hdcSrc, int width, int height);
        int width = wi.getRect().right - wi.getRect().left;
        int height = wi.getRect().bottom - wi.getRect().top;

        W32API.HBITMAP hBitmapMemory  = Gdi32.instance.CreateCompatibleBitmap(hdcSrc, width, height);

        W32API.HANDLE hOld  = Gdi32.instance.SelectObject(hdcMemory, hBitmapMemory);

        Gdi32.instance.BitBlt(hdcMemory, 0, 0, width, height, hdcSrc, width+2, height+2, 0x00CC0020);

        /* # now how do we convert to a BufferedImage???  */

        // clean up
        Gdi32.instance.SelectObject(hdcMemory, hOld);
        Gdi32.instance.DeleteDC(hdcMemory);
        Gdi32.instance.DeleteObject(hBitmapMemory);
        User32.instance.ReleaseDC(wi.getHwnd(), hdcSrc);

    }

    /**
     *
     * @return
     */
    private List<WindowInfo> getWindows() {

        final List<WindowInfo> list = new ArrayList<WindowInfo>();

        User32.instance.EnumWindows(new WndEnumProc() {
            public boolean callback(int hWnd, int lParam) {
                if (User32.instance.IsWindowVisible(hWnd)) {
                    RECT r = new RECT();
                    User32.instance.GetWindowRect(hWnd, r);
                    byte[] buffer = new byte[1024];
                    User32.instance.GetWindowTextA(hWnd, buffer, buffer.length);
                    String title = Native.toString(buffer);
                    if (title!=null&&title.length()>0) {
                        list.add(new WindowInfo(hWnd, r, title));
                    }
                }
                return true;
            }
        }, 0);

        Collections.sort(list, new Comparator<WindowInfo>() {
            public int compare(WindowInfo o1, WindowInfo o2) {
                int i1 = (o1.getTitle()!=null&&o1.getTitle().length()>0?o1.getTitle():" ").charAt(0);
                int i2 = (o2.getTitle()!=null&&o2.getTitle().length()>0?o2.getTitle():" ").charAt(0);
                return i1 - i2;
            }
        });

        return list;
    }
}
</code>```

I've also tried the equivalent of "PrintWindow()" API...

```<code>Graphics g = form.CreateGraphics();
Bitmap bmp = new Bitmap(form.Size.Width, form.Size.Height, g);
Graphics memoryGraphics = Graphics.FromImage(bmp);
IntPtr dc = memoryGraphics.GetHdc();
bool success = PrintWindow(form.Handle, dc, 0);
memoryGraphics.ReleaseHdc(dc);
// bmp now contains the screenshot
</code>```

Or do I have to use JNI, or any other tool?

答:
Use java.awt.Robot.createScreenCapture().

Here's an example:

```<code>    try {
        Robot robot = new Robot();
        Rectangle size = new Rectangle(Toolkit.getDefaultToolkit()
                .getScreenSize());
        BufferedImage buf = robot.createScreenCapture(size);
        ImageIO.write(buf, "png", new File("d:/test.png"));
    } catch (AWTException ae) {
        throw new RuntimeException("something went wrong");
    }
</code>```

Code originally stolen from here.

Title: Java - Window Image

Body:
Does anyone know how to capture a screen shot in Java (not it's own screen, but any other window on the desktop and they don't necessarily have to be the active window) in Windows? There are a number of threads here on this similar subject, but I have yet to find an answer.

I've tried using JNA, but became stuck after a few attempts. For example...

public class Main {

    public static void main(String[] args) {
        Main m = new Main();

        List<WindowInfo> list = m.getWindows();

        for (int i=0;i<list.size();i++)
        {
            WindowInfo info = list.get(i);
            System.out.println(info.getTitle());
        }

        WindowInfo wi = list.get(0);

        W32API.HDC hdcSrc = User32.instance.GetWindowDC(wi.getHwnd());

        W32API.HDC hdcMemory = Gdi32.instance.CreateCompatibleDC(hdcSrc);

        //W32API.HBITMAP hBitmapMemory = Gdi32.instance.CreateCompatibleBitmap(hdcSrc, int width, int height);
        int width = wi.getRect().right - wi.getRect().left;
        int height = wi.getRect().bottom - wi.getRect().top;

        W32API.HBITMAP hBitmapMemory  = Gdi32.instance.CreateCompatibleBitmap(hdcSrc, width, height);

        W32API.HANDLE hOld  = Gdi32.instance.SelectObject(hdcMemory, hBitmapMemory);

        Gdi32.instance.BitBlt(hdcMemory, 0, 0, width, height, hdcSrc, width+2, height+2, 0x00CC0020);

        /* # now how do we convert to a BufferedImage???  */

        // clean up
        Gdi32.instance.SelectObject(hdcMemory, hOld);
        Gdi32.instance.DeleteDC(hdcMemory);
        Gdi32.instance.DeleteObject(hBitmapMemory);
        User32.instance.ReleaseDC(wi.getHwnd(), hdcSrc);

    }

    /**
     *
     * @return
     */
    private List<WindowInfo> getWindows() {

        final List<WindowInfo> list = new ArrayList<WindowInfo>();

        User32.instance.EnumWindows(new WndEnumProc() {
            public boolean callback(int hWnd, int lParam) {
                if (User32.instance.IsWindowVisible(hWnd)) {
                    RECT r = new RECT();
                    User32.instance.GetWindowRect(hWnd, r);
                    byte[] buffer = new byte[1024];
                    User32.instance.GetWindowTextA(hWnd, buffer, buffer.length);
                    String title = Native.toString(buffer);
                    if (title!=null&&title.length()>0) {
                        list.add(new WindowInfo(hWnd, r, title));
                    }
                }
                return true;
            }
        }, 0);

        Collections.sort(list, new Comparator<WindowInfo>() {
            public int compare(WindowInfo o1, WindowInfo o2) {
                int i1 = (o1.getTitle()!=null&&o1.getTitle().length()>0?o1.getTitle():" ").charAt(0);
                int i2 = (o2.getTitle()!=null&&o2.getTitle().length()>0?o2.getTitle():" ").charAt(0);
                return i1 - i2;
            }
        });

        return list;
    }
}

I've also tried the equivalent of "PrintWindow()" API...

Graphics g = form.CreateGraphics();
Bitmap bmp = new Bitmap(form.Size.Width, form.Size.Height, g);
Graphics memoryGraphics = Graphics.FromImage(bmp);
IntPtr dc = memoryGraphics.GetHdc();
bool success = PrintWindow(form.Handle, dc, 0);
memoryGraphics.ReleaseHdc(dc);
// bmp now contains the screenshot

Or do I have to use JNI, or any other tool?

Body:
Use java.awt.Robot.createScreenCapture().

Here's an example:

    try {
        Robot robot = new Robot();
        Rectangle size = new Rectangle(Toolkit.getDefaultToolkit()
                .getScreenSize());
        BufferedImage buf = robot.createScreenCapture(size);
        ImageIO.write(buf, "png", new File("d:/test.png"));
    } catch (AWTException ae) {
        throw new RuntimeException("something went wrong");
    }

Code originally stolen from here.

ContentLicense: CC BY-SA 2.5


答:
Here is all you need to know about relative file paths:

Starting with "/" returns to the root directory and starts there

Starting with "../" moves one directory backwards and starts there

Starting with "../../" moves two directories backwards and starts there (and so on...)

To move forward, just start with the first subdirectory and keep moving forward

Here is the reference

Title: Trying to connect JS and HTML. Receiving ERR_FILE NOT_FOUND


问:
Passing value from Google Login to JSF login
I'm kinda new to all of this, but I have a JSF Web Application (which works) which also has a Google Authentication (google authentication works by itself);

I'm trying to pass the response from the google Auth to the JSF login (the email address & google Id) which will then authenticate via a JdbcRealm;

So just to clarify, the JSF authentication via a JdbcRealm works by itself, and the google login by itself works - i just want to pass the response from google (of the email address & google id) to be used as the JSF authentication, & automate the click action of the JSF auth form.

My issue is, that after i log into google, i get the error

TypeError: document.getElementById(...) is null

Here's my JSF login page with all the Javascript;

```<code><?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:h="http://xmlns.jcp.org/jsf/html">

    <h:head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="NDIS Management System"/>
        <meta name="author" content="Danielle Walker"/>
        <meta name="google-signin-client_id" content="270287108664-3g7l6e6ah3gr5am9onokua84t3bvdbvf.apps.googleusercontent.com" />

        <title>NDIS Home</title>
        <!-- Bootstrap core CSS -->
        <h:outputStylesheet name="bootstrap/css/bootstrap.min.css"/>
        <h:outputStylesheet name="bootstrap/css/the-big-picture.css"  />
        <h:outputStylesheet name="css/google-button.css" />
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <f:verbatim>
            <!--[if lt IE 9]>
              <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
              <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
            <![endif]-->
        </f:verbatim>

        <!-- Google API Javascript needs to be loaded in the page before the actual Javascript -->
        <script src="https://apis.google.com/js/api:client.js" />

        <ui:insert name="head"/>
    </h:head>

    <h:body class="full">

        <nav class="navbar navbar-inverse navbar-fixed-bottom" role="navigation">
            <div class="container">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#"></a>
                </div>
                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li>
                            <a href="#">About</a>
                        </li>
                        <li>
                            <a href="#">Contact</a>
                        </li>
                    </ul>
                    <ul class="navbar-right">
                        <li>
                            <div id="gSignInWrapper" style="padding-top:5px;">
                                <div id="customBtn" class="customGPlusSignIn" style="float: right;">
                                    <span class="icon"></span><span class="buttonText">Sign In</span>
                                </div>
                            </div>
                            <span style="color:#f9f9f9"><div id="name"></div></span>
                        </li>
                    </ul>
                </div>
                <!-- /.navbar-collapse -->
            </div>
            <!-- /.container -->
        </nav>

        <h:form id="login" onsubmit="document.getElementById('login').action = 'j_security_check';" prependId="false">
            <!--<h:panelGrid columns="2">-->
            <h:outputLabel for="j_username" value="Username" />
            <h:inputText id="j_username" />
            <h:outputLabel for="j_password" value="Password" />
            <h:inputText id="j_password" size="8"/>
            <h:commandButton id="submit" value="Login" />
            <!--</h:panelGrid>-->
        </h:form>

        <f:verbatim>
            <script>
                var googleUser = {};
                var startApp = function () {
                    gapi.load('auth2', function () {
                        // Retrieve the singleton for the GoogleAuth library and set up the client.
                        auth2 = gapi.auth2.init({
                            client_id: '270287108664-3g7l6e6ah3gr5am9onokua84t3bvdbvf.apps.googleusercontent.com',
                            cookiepolicy: 'single_host_origin'
                                    // Request scopes in addition to 'profile' and 'email'
                                    //scope: 'additional_scope'
                        });
                        attachSignin(document.getElementById('customBtn'));
                    });
                };
            </script>
        </f:verbatim>

        <script>startApp();</script>
        <f:verbatim>
            <script>
                function attachSignin(element) {
                    console.log(element.id);
                    auth2.attachClickHandler(element, {},
                            function (googleUser) {
                                //document.getElementById('name').text = "Signed in: " +
                                //        googleUser.getBasicProfile().getId();
                                document.getElementById("login.j_username").value = googleUser.getBasicProfile().getEmail();
                                document.getElementById("login.j_password").value = googleUser.getBasicProfile().getId();
                            }, function (error) {
                        alert(JSON.stringify(error, undefined, 2));
                        //alert("Opps... an error Occured");
                    });
                }
                function signOut() {
                    var auth2 = gapi.auth2.getAuthInstance();
                    auth2.signOut().then(function () {
                        console.log('User signed out.');
                    });
                }
            </script>
        </f:verbatim>
        <ui:insert name="body"/>

        <!-- Bootstrap core JavaScript
        ================================================== -->
        <!-- Placed at the end of the document so the pages load faster -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <h:outputScript name="bootstrap/js/bootstrap.min.js"/>
        <script src="https://apis.google.com/js/api:client.js" />

    </h:body>
</html>
</code>```

答:
I found the answer to my own problem;

With my error message, the problem was obviously in the way i was trying to access the "j_username" & "j_password elements:

TypeError: document.getElementById(...) is null

Anyway, by changing the code i had:

```<code>document.getElementById("login.j_username").value = googleUser.getBasicProfile().getEmail();
</code>```

To instead look like this:

```<code>document.getElementById("login").elements[1].value = googleUser.getBasicProfile().getEmail();
</code>```

In short, the problem was the way i was trying to address the elements of the form, and by addressing the form itself, and then the elements of the form (being in a 0 based array), then it works

Body:
I'm kinda new to all of this, but I have a JSF Web Application (which works) which also has a Google Authentication (google authentication works by itself);

I'm trying to pass the response from the google Auth to the JSF login (the email address & google Id) which will then authenticate via a JdbcRealm;

So just to clarify, the JSF authentication via a JdbcRealm works by itself, and the google login by itself works - i just want to pass the response from google (of the email address & google id) to be used as the JSF authentication, & automate the click action of the JSF auth form.

My issue is, that after i log into google, i get the error

TypeError: document.getElementById(...) is null

Here's my JSF login page with all the Javascript;

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <meta name="description" content="NDIS Management System"/>
        <meta name="author" content="Danielle Walker"/>
        <meta name="google-signin-client_id" content="270287108664-3g7l6e6ah3gr5am9onokua84t3bvdbvf.apps.googleusercontent.com" />

        <title>NDIS Home</title>

        <h:outputStylesheet name="bootstrap/css/bootstrap.min.css"/>
        <h:outputStylesheet name="bootstrap/css/the-big-picture.css"  />
        <h:outputStylesheet name="css/google-button.css" />

        <f:verbatim>

        </f:verbatim>

        </f:verbatim>

        <f:verbatim>

        </f:verbatim>
        <ui:insert name="body"/>

        <h:outputScript name="bootstrap/js/bootstrap.min.js"/>

Body:
I found the answer to my own problem;

With my error message, the problem was obviously in the way i was trying to access the "j_username" & "j_password elements:

TypeError: document.getElementById(...) is null

Anyway, by changing the code i had:

document.getElementById("login.j_username").value = googleUser.getBasicProfile().getEmail();

To instead look like this:

document.getElementById("login").elements[1].value = googleUser.getBasicProfile().getEmail();

In short, the problem was the way i was trying to address the elements of the form, and by addressing the form itself, and then the elements of the form (being in a 0 based array), then it works


问:
Objective C pods in Swift Project - right bridging headers?
I am trying to add SocketClusteriOS (https://github.com/abpopov/SocketCluster-ios-client) pod written in Objective C to Swift project. I've tested the this pod in Objective C project, url seems working fine, but when I am trying to add it to Swift project I have strange errors:

```<code>NewSocketTestApp[1641:29629] {"event":"#disconnect","data":
{"code":4005}}
#disconnect
</code>```

I might think the problem in bridging header. I attached the link to my repository of test app. https://github.com/davigr/SocketClusterSwift. SocketCluster-ios-client uses SocketRocket pod, I mentioned this pod in my bridging header as well. Unfortunately, when I am trying connect it couldn't. I did the same code in Objective C project, everything was fine. Could anyone help me to fix this issue? Maybe problem in Project settings or bridging headers
My bridging header:

```<code>#ifndef Bridging_Header_h
#define Bridging_Header_h
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCChannel.h"
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCSocket.h"
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCMessage.h"
#import "Pods/SocketRocket/SocketRocket/SocketRocket.h"
#import <Foundation/Foundation.h>
#import <CFNetwork/CFNetwork.h>
#import <Security/Security.h>
</code>```

答: Solved, the link with socket cluster will be soon</p>

Body:
I am trying to add SocketClusteriOS (https://github.com/abpopov/SocketCluster-ios-client) pod written in Objective C to Swift project. I've tested the this pod in Objective C project, url seems working fine, but when I am trying to add it to Swift project I have strange errors:

NewSocketTestApp[1641:29629] {"event":"#disconnect","data":
{"code":4005}}
#disconnect

I might think the problem in bridging header. I attached the link to my repository of test app. https://github.com/davigr/SocketClusterSwift. SocketCluster-ios-client uses SocketRocket pod, I mentioned this pod in my bridging header as well. Unfortunately, when I am trying connect it couldn't. I did the same code in Objective C project, everything was fine. Could anyone help me to fix this issue? Maybe problem in Project settings or bridging headers
My bridging header:

#ifndef Bridging_Header_h
#define Bridging_Header_h
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCChannel.h"
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCSocket.h"
#import "Pods/SocketCluster-ios-client/Pod/Classes/SCMessage.h"
#import "Pods/SocketRocket/SocketRocket/SocketRocket.h"
#import <Foundation/Foundation.h>
#import <CFNetwork/CFNetwork.h>
#import <Security/Security.h>


问:
React - ES6 - Unexpected token
I'm getting this error

```<code>ERROR in ./src/components/Header/index.js
Module build failed: SyntaxError: C:/Users/Gil/Documents/Projects/ecommerce/src/components/Header/index.js: Unexpected token (16:7)

  14 |   }
  15 |
> 16 |   test = () => {
     |        ^
  17 |     console.log('pass!');
  18 |   };
  19 |
</code>```

i think its something with ES6, but i dont know, anyway here's my config

webpack.config.js

```<code>loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      },...
</code>```

package.json

```<code>"devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react-scripts": "1.0.7"
</code>```

so my problem is, when i try to use arrow function i get this error, do i need an extra config or i'm doing something wrong?

答:
You need https://babeljs.io/docs/plugins/transform-class-properties/

```<code>npm install --save-dev babel-plugin-transform-class-properties
</code>```

and inside .babelrc:

```<code>"plugins": ["transform-class-properties"]
</code>```

Title: React - ES6 - Unexpected token

Body:
I'm getting this error

ERROR in ./src/components/Header/index.js
Module build failed: SyntaxError: C:/Users/Gil/Documents/Projects/ecommerce/src/components/Header/index.js: Unexpected token (16:7)

  14 |   }
  15 |
> 16 |   test = () => {
     |        ^
  17 |     console.log('pass!');
  18 |   };
  19 |

i think its something with ES6, but i dont know, anyway here's my config

webpack.config.js

loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      },...

package.json

"devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react-scripts": "1.0.7"

so my problem is, when i try to use arrow function i get this error, do i need an extra config or i'm doing something wrong?

Body:
You need https://babeljs.io/docs/plugins/transform-class-properties/

npm install --save-dev babel-plugin-transform-class-properties

and inside .babelrc:

"plugins": ["transform-class-properties"]


问:
passwd command in shell script
I am making a shell script that automatically create users, but I cannot think of how to use passwd command within my shell script, how should I use it with shell script? --stdin option doesn't work for me</p>

答:
Some implementations of passwd have the --stdin flag which you can use like so:

```<code>passwd --stdin user <<<"SoMePasSw0rd"
</code>```

Title: passwd command in shell script

Body:
Some implementations of passwd have the --stdin flag which you can use like so:

passwd --stdin user <<<"SoMePasSw0rd"


问:
How can I increase the capacity of PostgreSQL text indexing?
I want to do indexing on Django text field which has more than 60000 characters in some rows. Right now I am having the following error (for a much smaller row):

```<code>django.db.utils.OperationalError: index row requires 8368 bytes, maximum size is 8191
</code>```

Is there a limit on the size for indexing in PostgreSQL?

答: If you really need to index large TEXT fields then you’ll have to look at full text indexing with Tsearch2. Also recommend to find another approach to the problem you're trying to solve.</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to do indexing on Django text field which has more than 60000 characters in some rows. Right now I am having the following error (for a much smaller row):

django.db.utils.OperationalError: index row requires 8368 bytes, maximum size is 8191

Is there a limit on the size for indexing in PostgreSQL?


问:
Editing a wiki on a github repo
I am trying to edit and make changes on another persons wiki for their repo. I cloned it locally with the following:

```<code>git clone https://github.com/***/***.wiki.git
</code>```

I then edited it and completed the desired changes. Now, how do I go about pushing said changes? Do I need to open a pull request for this and how would I go about it? Any help would be greatly appreciated. I tried to push changes on the same remote origin branch but I get the Permission denied (publickey) error.

答:
There are two problems here.  The first is that you actually seemed to have cloned at ssh linked git repository such as

git@github.com:/***/**.wiki.git

And thus why it is saying Permission denied (publickey).  If you'd cloned a https git repo then you would type username / password.

As to how to edit a github wiki locally - By default the branch is master.  If you choose to work on sub-branches to separate the work, then you'll need to merge to your local master branch and push.  There doesn't seem to be a way to have pull requests for wiki pages.

In summary:

If not done, setup your public/private ssh key in github - https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/

Checkout your repo locally - git clone git@github.com:/***/**.wiki.git

Optionally branch so as to separate the work(s) - git checkout -b some_branch

Edit your wiki pages with a markdown editor (I used IntelliJ with a Markdown plugin - it can display the markdown on one page and the rendered page next to it, which is nice.)

Add and commit your work:
git add page.md
git commit -m "Added blah blah instructions"

Optionally merge back to master:
git checkout master
git merge some_branch

Push it back to the github repo - git push

Remember, you can't seem to be able to do pull requests with github wiki pages (since the only branch available through Github is master).

Title: Editing a wiki on a github repo

Body:
I am trying to edit and make changes on another persons wiki for their repo. I cloned it locally with the following:

git clone https://github.com/***/***.wiki.git

I then edited it and completed the desired changes. Now, how do I go about pushing said changes? Do I need to open a pull request for this and how would I go about it? Any help would be greatly appreciated. I tried to push changes on the same remote origin branch but I get the Permission denied (publickey) error.


问:
R Create stacked bar chart from non-numerical data using ggplot2
I want to create a stacked bar chart using non numerical data that would look like the ggplot one below

My data looks like this, read in as a CSV and contains 500+ obs. All rows for "Name" are unique.

```<code>Name      Group      Category
Philippe Cochet      NPA      Farmer
Jacques Kossowski      NPA      Farmer
Lionel Tardy      USD      Executive
Dominique Tian      USD      Executive
Dom Terril      ABC      Executive
</code>```

I'd like the x axis to be the Category, and the y axis to be the count of Category. The bars would then be coloured by Group count. I imagine it might work something like this:

```<code>ggplot(z, aes("Category")) + geom_bar(aes(fill = "Group"))
</code>```

I've also tried using a native barplot, but this won't stack the bars

```<code>z <- table(z$"Group",z$"Category")
barplot(z, beside = TRUE, legend = TRUE)
</code>```

答:
The fill = Group needs to be inside the aes without quotation marks.  Try:

```<code>ggplot(z, aes(Category, fill = Group)) + geom_bar()
</code>```

or, in keeping with the geom_bar help page:

```<code>ggplot(z, aes(Category)) + geom_bar(aes(fill = Group))
</code>```

These will both give the desired result:

Body:
I want to create a stacked bar chart using non numerical data that would look like the ggplot one below

My data looks like this, read in as a CSV and contains 500+ obs. All rows for "Name" are unique.

Name      Group      Category
Philippe Cochet      NPA      Farmer
Jacques Kossowski      NPA      Farmer
Lionel Tardy      USD      Executive
Dominique Tian      USD      Executive
Dom Terril      ABC      Executive

I'd like the x axis to be the Category, and the y axis to be the count of Category. The bars would then be coloured by Group count. I imagine it might work something like this:

ggplot(z, aes("Category")) + geom_bar(aes(fill = "Group"))

I've also tried using a native barplot, but this won't stack the bars

z <- table(z$"Group",z$"Category")
barplot(z, beside = TRUE, legend = TRUE)

Body:
The fill = Group needs to be inside the aes without quotation marks.  Try:

ggplot(z, aes(Category, fill = Group)) + geom_bar()

or, in keeping with the geom_bar help page:

ggplot(z, aes(Category)) + geom_bar(aes(fill = Group))

These will both give the desired result:


问:
Centralizing RecyclerView with LinearLayoutManager
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

答:
Replace constraint layout with Relative layout

Then, make the image be central, use this

```<code>    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:clickable="true"
        android:scaleType="centerCrop" />
</code>```

Then also make each of those texts be central

```<code>android:textAlignment="center"
</code>```

Body:
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

Body:
Replace constraint layout with Relative layout

Then, make the image be central, use this

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:clickable="true"
        android:scaleType="centerCrop" />

Then also make each of those texts be central

android:textAlignment="center"


问:
Why won't the cells in my table view display any text?
I've been working through an online tutorial about creating a To Do list app for iOS, but it's come to my attention that the tutorial uses an outdated version of Swift (link: https://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1).  I tried to correct the code according to the new standards, but when I build and run the app it only displays an empty table: no text is visible.

I pasted my code below.  It includes a couple of print statements that I used for debugging, but only the first one ("hello world") appears to run.  Any input would be greatly appreciated.  Thank you!

```<code>import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
var toDoItems = [ToDoItem]()

override func viewDidLoad() {
    toDoItems.append(ToDoItem(text: "First text"))
    print("hello world")
    super.viewDidLoad()
    tableView = UITableView()
    tableView.dataSource = self
    tableView.delegate = self
    //self.view.addSubview(self.tableView)
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

    if toDoItems.count > 0 {
        return
    }

    toDoItems.append(ToDoItem(text: "text 1"))
    toDoItems.append(ToDoItem(text: "text 2"))
    toDoItems.append(ToDoItem(text: "text 3"))
    toDoItems.append(ToDoItem(text: "text 4"))
    toDoItems.append(ToDoItem(text: "text 5"))
    toDoItems.append(ToDoItem(text: "text 6"))
    toDoItems.append(ToDoItem(text: "text 7"))
    toDoItems.append(ToDoItem(text: "text 8"))
    toDoItems.append(ToDoItem(text: "text 9"))
    toDoItems.append(ToDoItem(text: "text 10"))
    toDoItems.append(ToDoItem(text: "text 11"))
    toDoItems.append(ToDoItem(text: "text 12"))

}

// MARK: - Table view data source

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return toDoItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    print("should assign text here")
    let item = toDoItems[indexPath.row]
    cell.textLabel!.text = item.text
    return cell
 }
}
</code>```

答:
Get rid of this line in viewDidLoad():

```<code>tableView = UITableView()
</code>```

The tableView @IBOutlet should be connected in your Storyboard.  By assigning UITableView() you are creating a second UITableView which isn't the one that is on screen.

To connect the tableView outlet in the Storyboard, click on the circle to the left of the outlet and drag to the tableView in the ViewController:

Body:
I've been working through an online tutorial about creating a To Do list app for iOS, but it's come to my attention that the tutorial uses an outdated version of Swift (link: https://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1).  I tried to correct the code according to the new standards, but when I build and run the app it only displays an empty table: no text is visible.

I pasted my code below.  It includes a couple of print statements that I used for debugging, but only the first one ("hello world") appears to run.  Any input would be greatly appreciated.  Thank you!

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
var toDoItems = [ToDoItem]()

override func viewDidLoad() {
    toDoItems.append(ToDoItem(text: "First text"))
    print("hello world")
    super.viewDidLoad()
    tableView = UITableView()
    tableView.dataSource = self
    tableView.delegate = self
    //self.view.addSubview(self.tableView)
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

    if toDoItems.count > 0 {
        return
    }

    toDoItems.append(ToDoItem(text: "text 1"))
    toDoItems.append(ToDoItem(text: "text 2"))
    toDoItems.append(ToDoItem(text: "text 3"))
    toDoItems.append(ToDoItem(text: "text 4"))
    toDoItems.append(ToDoItem(text: "text 5"))
    toDoItems.append(ToDoItem(text: "text 6"))
    toDoItems.append(ToDoItem(text: "text 7"))
    toDoItems.append(ToDoItem(text: "text 8"))
    toDoItems.append(ToDoItem(text: "text 9"))
    toDoItems.append(ToDoItem(text: "text 10"))
    toDoItems.append(ToDoItem(text: "text 11"))
    toDoItems.append(ToDoItem(text: "text 12"))

}

// MARK: - Table view data source

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return toDoItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    print("should assign text here")
    let item = toDoItems[indexPath.row]
    cell.textLabel!.text = item.text
    return cell
 }
}

Body:
Get rid of this line in viewDidLoad():

tableView = UITableView()

The tableView @IBOutlet should be connected in your Storyboard.  By assigning UITableView() you are creating a second UITableView which isn't the one that is on screen.

To connect the tableView outlet in the Storyboard, click on the circle to the left of the outlet and drag to the tableView in the ViewController:


问:
Need help to change file format after the users download it from Database
Did I miss something in this code?  cuz when I test it I get the file type as "File" not as PDF.

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString);
    conn.Open();
    string pdffile = "select pdf from users where ID='" + TextBoxLic.Text + "'";
    SqlCommand pdfcom = new SqlCommand(pdffile, conn);
    SqlDataReader reader = pdfcom.ExecuteReader();
    if (reader.Read())
    {
        Byte[] pdfData = (byte[])reader.GetValue(0);
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("content-disposition", "attachment; filename=" + TextBoxLic.Text);
        Response.BinaryWrite(pdfData);
        Response.End();
        conn.Close();
    }
}
</code>```

https://i.gyazo.com/8eb75d4e55bed17155690531841d80c7.png

答:
Maybe try adding a

Response.Flush();
 Response.Close();

after Response.BinaryWrite(pdfData);

More importantly it should be
while (reader.Read())
rather than
if (reader.Read())

I'd suggest you read up on here: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read(v=vs.110).aspx

Body:
Did I miss something in this code?  cuz when I test it I get the file type as "File" not as PDF.

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString);
    conn.Open();
    string pdffile = "select pdf from users where ID='" + TextBoxLic.Text + "'";
    SqlCommand pdfcom = new SqlCommand(pdffile, conn);
    SqlDataReader reader = pdfcom.ExecuteReader();
    if (reader.Read())
    {
        Byte[] pdfData = (byte[])reader.GetValue(0);
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("content-disposition", "attachment; filename=" + TextBoxLic.Text);
        Response.BinaryWrite(pdfData);
        Response.End();
        conn.Close();
    }
}

https://i.gyazo.com/8eb75d4e55bed17155690531841d80c7.png


问:
Allow multiple headers with CORS in Suave
I'm trying to get my Suave API to accept CORS requests. I've followed this snippet here:

http://www.fssnip.net/mL/title/CORS-response-with-Suave

Which I will recreate here:

```<code>let setCORSHeaders =
    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "content-type"

let allow_cors : WebPart =
    choose [
        OPTIONS >=>
            fun context ->
                context |> (
                    setCORSHeaders
                    >=> OK "CORS approved" )
    ]

let webSite =
    choose [
        allow_cors
        GET >=> OK "URLs are for wimps. GETting something? This is what you get."
    ]
</code>```

But now I have endpoints that require a token to be passed in, and those endpoints are giving errors due to missing allowed headers in CORS. My token header is simply "token", so I've tried two things, and both have not resolved the issue.

Attempt #1

```<code>    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "content-type"
    >=> setHeader "Access-Control-Allow-Headers" "token"
</code>```

This returned an error saying content-type was no longer accepted - this seems to imply that the last setHeader overwrote the first one, which when you view the source code here : https://github.com/SuaveIO/suave/blob/master/src/Suave.Tests/HttpWriters.fs , at line 113, there is a test that to me implies this is the desired behavior.

Attempt #2

Based on the response on this question: How to set a Json response in suave webpart, I attempted to set both headers via a comma-separated list:

```<code>    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "Content-Type,token"
</code>```

But this then gave an error indicating that CORS was failing entirely:

```<code>No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.
</code>```

Also based on this same question, I tried the following:

```<code>    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers:content-type" "Accept"
    >=> setHeader "Access-Control-Allow-Headers:token" "Accept"
</code>```

Which gave this response: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

So, how do I allow any amount of headers in a CORS request in Suave?

Edit

Attempt #3

I used addHeader instead of setHeader:

```<code>let setCORSHeaders =
    setHeader  "Access-Control-Allow-Origin" "*"
    >=> addHeader "Access-Control-Allow-Headers" "content-type"
    >=> addHeader "Access-Control-Allow-Headers" "token"
</code>```

Which is now saying... No 'Access-Control-Allow-Origin' header is present on the requested resource.

If I change that first setHeader to addHeader, I still get the same response.

Fix

```<code>    addHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "token"
    >=> addHeader "Access-Control-Allow-Headers" "content-type"
    >=> addHeader "Access-Control-Allow-Methods" "GET,POST,PUT"
</code>```

Did the job - after this, there were issues with what was being sent, but nothing more with CORS itself.

答:
Try using addHeader instead of setHeader. Just a few lines further down in the unit tests that you found, there's a test for addHeader that shows that it has the semantics you're looking for, and its documentation says:

Adds the header key with the given value to the list of returned headers, even if that header already exists. This means that Suave will serve a a response with the header denoted by key with possibly different values.

This looks like the behavior you're wanting.

Body:
I'm trying to get my Suave API to accept CORS requests. I've followed this snippet here:

http://www.fssnip.net/mL/title/CORS-response-with-Suave

Which I will recreate here:

let setCORSHeaders =
    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "content-type"

let allow_cors : WebPart =
    choose [
        OPTIONS >=>
            fun context ->
                context |> (
                    setCORSHeaders
                    >=> OK "CORS approved" )
    ]

let webSite =
    choose [
        allow_cors
        GET >=> OK "URLs are for wimps. GETting something? This is what you get."
    ]

But now I have endpoints that require a token to be passed in, and those endpoints are giving errors due to missing allowed headers in CORS. My token header is simply "token", so I've tried two things, and both have not resolved the issue.

Attempt #1

    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "content-type"
    >=> setHeader "Access-Control-Allow-Headers" "token"

This returned an error saying content-type was no longer accepted - this seems to imply that the last setHeader overwrote the first one, which when you view the source code here : https://github.com/SuaveIO/suave/blob/master/src/Suave.Tests/HttpWriters.fs , at line 113, there is a test that to me implies this is the desired behavior.

Attempt #2

Based on the response on this question: How to set a Json response in suave webpart, I attempted to set both headers via a comma-separated list:

    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "Content-Type,token"

But this then gave an error indicating that CORS was failing entirely:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

Also based on this same question, I tried the following:

    setHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers:content-type" "Accept"
    >=> setHeader "Access-Control-Allow-Headers:token" "Accept"

Which gave this response: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

So, how do I allow any amount of headers in a CORS request in Suave?

Edit

Attempt #3

I used addHeader instead of setHeader:

let setCORSHeaders =
    setHeader  "Access-Control-Allow-Origin" "*"
    >=> addHeader "Access-Control-Allow-Headers" "content-type"
    >=> addHeader "Access-Control-Allow-Headers" "token"

Which is now saying... No 'Access-Control-Allow-Origin' header is present on the requested resource.

If I change that first setHeader to addHeader, I still get the same response.

Fix

    addHeader  "Access-Control-Allow-Origin" "*"
    >=> setHeader "Access-Control-Allow-Headers" "token"
    >=> addHeader "Access-Control-Allow-Headers" "content-type"
    >=> addHeader "Access-Control-Allow-Methods" "GET,POST,PUT"

Did the job - after this, there were issues with what was being sent, but nothing more with CORS itself.


问:
testability considerations while creating controllers
I am writing controllers in Web API 2, against which odata queries will be executed:

```<code>[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; //this query variable will be something "filter=name eq 'alex'"
    var response = _accountService.Get(query);

    if (!response.Result.IsSuccessStatusCode)
    {
        return NotFound();
    }

    var readAsAsync = response.Result.Content.ReadAsAsync<object>();
    if (readAsAsync == null)
    {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}
</code>```

How do I inject the Request, specifically as it relates to: var query = Request.RequestUri.PathAndQuery.Split('/')[2]; ?

Here's a very basic test that I've written for this controller:

```<code>[TestMethod]
public void GetAccount_Returns_IHttpActionResultTask()
{
    var accountsService = new Mock<IAccountService>();
    var sut = new AccountsController(accountsService.Object);

    Assert.IsInstanceOfType(sut.GetAccount(), typeof(Task<IHttpActionResult>));
}
</code>```

In order to test with different values for Request.RequestUri...., how do I rewrite my controller to be more testable?

答:
Set the Request property on the ApiCntroller.

```<code>[TestMethod]
public async Task GetAccount_Returns_IHttpActionResult() {
    //Arrange
    var accountsService = new Mock<IAccountService>();
    var sut = new AccountsController(accountsService.Object);
    sut.Request = new HttpRequestMessage {
        RequestUri = new Uri("http://localhost/api/accounts?filter=name")
    };

    //Act
    var result = await sut.GetAccount();

    //Assert
    Assert.IsInstanceOfType(result, typeof(IHttpActionResult));
}
</code>```

Also there or some potential blocking issues with the method under test. Mixing async/await with .Result blocking calls can cause deadlocks.

Refactor:

```<code>[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount() {
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; //this query variable will be something "filter=name eq 'alex'"
    var response = await _accountService.Get(query);

    if (!response.IsSuccessStatusCode) {
        return NotFound();
    }

    var readAsAsync = response.Content.ReadAsAsync<object>();
    if (readAsAsync == null) {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}
</code>```

Body:
I am writing controllers in Web API 2, against which odata queries will be executed:

[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; //this query variable will be something "filter=name eq 'alex'"
    var response = _accountService.Get(query);

    if (!response.Result.IsSuccessStatusCode)
    {
        return NotFound();
    }

    var readAsAsync = response.Result.Content.ReadAsAsync<object>();
    if (readAsAsync == null)
    {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}

How do I inject the Request, specifically as it relates to: var query = Request.RequestUri.PathAndQuery.Split('/')[2]; ?

Here's a very basic test that I've written for this controller:

[TestMethod]
public void GetAccount_Returns_IHttpActionResultTask()
{
    var accountsService = new Mock<IAccountService>();
    var sut = new AccountsController(accountsService.Object);

    Assert.IsInstanceOfType(sut.GetAccount(), typeof(Task<IHttpActionResult>));
}

In order to test with different values for Request.RequestUri...., how do I rewrite my controller to be more testable?

Body:
Set the Request property on the ApiCntroller.

[TestMethod]
public async Task GetAccount_Returns_IHttpActionResult() {
    //Arrange
    var accountsService = new Mock<IAccountService>();
    var sut = new AccountsController(accountsService.Object);
    sut.Request = new HttpRequestMessage {
        RequestUri = new Uri("http://localhost/api/accounts?filter=name")
    };

    //Act
    var result = await sut.GetAccount();

    //Assert
    Assert.IsInstanceOfType(result, typeof(IHttpActionResult));
}

Also there or some potential blocking issues with the method under test. Mixing async/await with .Result blocking calls can cause deadlocks.

Refactor:

[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount() {
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; //this query variable will be something "filter=name eq 'alex'"
    var response = await _accountService.Get(query);

    if (!response.IsSuccessStatusCode) {
        return NotFound();
    }

    var readAsAsync = response.Content.ReadAsAsync<object>();
    if (readAsAsync == null) {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}


问:
MongoDB: Unique Key in Embedded Document
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

```<code> {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },
</code>```

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

```<code>> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }
</code>```

Any suggestions? Thank you!

答:
The index will be across all Users and since you asked it for 'unique', no user will be able to have two of the same named item AND no two users will be able to have the same named Item.

Is that what you want?

Furthermore, it appears that it's objecting to two Users having a 'null' value for Items.Name, clearly Jim does, is there another record like that?

It would be unusual to require uniqueness on an indexed collection like this.

MongoDB does allow unique indexes where it indexes only the first of each value, see
http://www.mongodb.org/display/DOCS/Indexes#Indexes-DuplicateValues, but I suspect the real solution is to not require uniqueness in this case.

If you want to ensure uniqueness only within the Items for a single user you might want to try the $addToSet option.  See http://www.mongodb.org/display/DOCS/Updating#Updating-%24addToSet

Body:
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

 {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }

Any suggestions? Thank you!


问:
Angular2 Async Validator not Pending
I'm following an online course in Angular2 and during a lesson that I was coding along with, I came across an error, but cannot figure out where I went wrong.

I tried to look at similar question around the web but couldn't find any valid solution. The closest I came was this answer, angular2 async form validation, but either the suggestions were irrelevant or it didn't work.

Here is my code:

Component

```<code>export class SignUpFormComponent {
   form: ControlGroup;

constructor(fb: FormBuilder){
    this.form = fb.group({
        username: ['', Validators.compose([
            Validators.required,
            UsernameValidators.cannotContainSpace
        ]), UsernameValidators.shouldBeUnique],
        password: ['', Validators.required]
    });
}

signup(){
    console.log(this.form.value);
}
}
</code>```

Validators

```<code>export class UsernameValidators{
static shouldBeUnique(control: Control){
    console.log("taken");
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            if(control.value == "example")
                resolve({ shouldBeUnique: true });
            else
                resolve(null);
        }, 1000);
    });
}
static cannotContainSpace(control: Control){
    if(control.value.indexOf(" ") >= 0){
        return { cannotContainSpace: true };
    }
    return null;
}
}
</code>```

Relevant parts of the form

```<code>    <input
        ngControl="username"
        id="username"
        type="text"
        class="form-control"
        #username="ngForm">

    <div *ngIf="username.control.pending">Checking for uniqueness...</div>

   <div
        *ngIf="username.errors.shouldBeUnique"
        class="alert alert-danger">
        Username is already taken.
    </div>
</code>```

When I run a server locally and start typing into the form the div with the pending message does not appear, and if I type "example" into the input field the error message does not pop up. What am I missing? Thanks.

答: Because I had to change the tsconfig.json file from "target" : "es5" to "target" : "es6", I ran npm install in the terminal again, then ran npm start, which fixed the problem.

Title: Angular2 Async Validator not Pending

Body:
I'm following an online course in Angular2 and during a lesson that I was coding along with, I came across an error, but cannot figure out where I went wrong.

I tried to look at similar question around the web but couldn't find any valid solution. The closest I came was this answer, angular2 async form validation, but either the suggestions were irrelevant or it didn't work.

Here is my code:

Component

export class SignUpFormComponent {
   form: ControlGroup;

constructor(fb: FormBuilder){
    this.form = fb.group({
        username: ['', Validators.compose([
            Validators.required,
            UsernameValidators.cannotContainSpace
        ]), UsernameValidators.shouldBeUnique],
        password: ['', Validators.required]
    });
}

signup(){
    console.log(this.form.value);
}
}

Validators

export class UsernameValidators{
static shouldBeUnique(control: Control){
    console.log("taken");
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            if(control.value == "example")
                resolve({ shouldBeUnique: true });
            else
                resolve(null);
        }, 1000);
    });
}
static cannotContainSpace(control: Control){
    if(control.value.indexOf(" ") >= 0){
        return { cannotContainSpace: true };
    }
    return null;
}
}

Relevant parts of the form

    <input
        ngControl="username"
        id="username"
        type="text"
        class="form-control"
        #username="ngForm">

Checking for uniqueness...

        Username is already taken.

When I run a server locally and start typing into the form the div with the pending message does not appear, and if I type "example" into the input field the error message does not pop up. What am I missing? Thanks.


问:
How come javascript is recognizing that my control is now holding an array?
I'm working on small MVC application that is "sending emails", and at the begining I used dropdown to choose only 1 receiver, but after that I added multiple class to my dropdownList and when I choose 2-3 receivers and when I tried to debug this code which I used with only one receiver :

```<code>$("#SubmitEmail").click(function () {
    var Receiver = $('#ReceiverID').val();
    var Subject = $('#subject').val();
    var Body = $('#content').val();
    var obj = { 'Receiver': Receiver, 'Subject': Subject, 'Body': Body };

    SendEmail(obj);
});
</code>```

I realized that var Receiver which I used to store receiverId, become an array acctually, and I'm wondering how come javascript adapted soo cooooool so it recognized that I've selected few items there, and it become an array so I simply looped it (modified my code):

```<code>$("#SubmitEmail").click(function () {
    var Receivers = $('#ReceiverID').val();
    for (var i = 0; i < Receivers.length; i++) {
        var Receiver = Receivers[i];
        var Subject = $('#subject').val();
        var Body = $('#content').val();
        var obj = { 'Receiver': Receiver, 'Subject': Subject, 'Body': Body };
    }
    SendEmail(obj);
});
</code>```

And everything was cooool, so I'm simply wondering how come js knows it all?

答: Javascript is cool as you state, but in this example it, in fact, is a Jquery implementation flexibility which returns array of objects for dropdown. see http://api.jquery.com/val/ for details.</p>

Body:
I'm working on small MVC application that is "sending emails", and at the begining I used dropdown to choose only 1 receiver, but after that I added multiple class to my dropdownList and when I choose 2-3 receivers and when I tried to debug this code which I used with only one receiver :

$("#SubmitEmail").click(function () {
    var Receiver = $('#ReceiverID').val();
    var Subject = $('#subject').val();
    var Body = $('#content').val();
    var obj = { 'Receiver': Receiver, 'Subject': Subject, 'Body': Body };

    SendEmail(obj);
});

I realized that var Receiver which I used to store receiverId, become an array acctually, and I'm wondering how come javascript adapted soo cooooool so it recognized that I've selected few items there, and it become an array so I simply looped it (modified my code):

$("#SubmitEmail").click(function () {
    var Receivers = $('#ReceiverID').val();
    for (var i = 0; i < Receivers.length; i++) {
        var Receiver = Receivers[i];
        var Subject = $('#subject').val();
        var Body = $('#content').val();
        var obj = { 'Receiver': Receiver, 'Subject': Subject, 'Body': Body };
    }
    SendEmail(obj);
});

And everything was cooool, so I'm simply wondering how come js knows it all?


问:
I don't understand why these two elements are not aligning side by side?
I want to get these two elements to align perfectly vertical side by side using a position value of relative. I'm having trouble as to understanding why these two elements don't want to align.

Can someone explain what I'm doing wrong? and if possible find a solution?

https://jsfiddle.net/kerberonix/qcq68gfg/

HTML

```<code><html>
  <body>
    <footer>
      <div class="test">
        <p>Footer Text</p>
      </div>
      <ul class="social-links">
        <li>Link 1</li>
        <li>Link 2</li>
      </ul>
    </footer>
  </body>
</code>```

CSS

```<code>footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
    display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

.social-links li {
    display: inline-block;
    margin-right: 35px;
    text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}
</code>```

答:
I would remove all of the positioning on the text and social elements, and use display: flex; align-items: center; on the parent.

footer {
  position: absolute;
  bottom: 0;
  height: 70px;
  padding: 0 20px;
  background-color: #262626;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  left: 0; right: 0;
}

.test {
  position: relative;
}

footer p {
  font-size: 100%;
  color: #888;
}

/*--------------------------------------------------------------------------------------------
SOCIAL LINKS
--------------------------------------------------------------------------------------------*/

.social-links {
  position: relative;
  color: white;
  text-align: right;
  padding: 0;
}

.test, .social-links {
  flex: 1 0 0;
}

.social-links li {
  display: inline-block;
  margin-left: 35px;
  text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

  <body>
    <footer>
      <div class="test">
        <p>Footer Text</p>
      </div>
      <ul class="social-links">
        <li>Link 1</li>
        <li>Link 2</li>
      </ul>
    </footer>
  </body>

</html></code>```

Body:
I want to get these two elements to align perfectly vertical side by side using a position value of relative. I'm having trouble as to understanding why these two elements don't want to align.

Can someone explain what I'm doing wrong? and if possible find a solution?

https://jsfiddle.net/kerberonix/qcq68gfg/

HTML

Footer Text

Link 1

Link 2

CSS

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
    display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

.social-links li {
    display: inline-block;
    margin-right: 35px;
    text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}

Body:
I would remove all of the positioning on the text and social elements, and use display: flex; align-items: center; on the parent.

footer {
  position: absolute;
  bottom: 0;
  height: 70px;
  padding: 0 20px;
  background-color: #262626;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  left: 0; right: 0;
}

.test {
  position: relative;
}

footer p {
  font-size: 100%;
  color: #888;
}

/*--------------------------------------------------------------------------------------------
SOCIAL LINKS
--------------------------------------------------------------------------------------------*/

.social-links {
  position: relative;
  color: white;
  text-align: right;
  padding: 0;
}

.test, .social-links {
  flex: 1 0 0;
}

.social-links li {
  display: inline-block;
  margin-left: 35px;
  text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}

<html>

  <body>
    <footer>
      <div class="test">
        <p>Footer Text</p>
      </div>
      <ul class="social-links">
        <li>Link 1</li>
        <li>Link 2</li>
      </ul>
    </footer>
  </body>

</html>


答:
This is how jQuery works. See .val() function:

http://api.jquery.com/val/

Scroll down for this example:

Get the single value from a single select and an array of values from a multiple select and display their values.

Title: How come javascript is recognizing that my control is now holding an array?


问:
Flutter Test MissingPluginException
Running tests which rely on the SharedPreferences Plugin always result in

```<code>MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
</code>```

My pubspec.yaml

```<code>dev_dependencies:
  flutter_test:
     sdk: flutter

dependencies:
  flutter:
     sdk: flutter
  shared_preferences: 0.2.3
</code>```

The code for works fine in the application itself.
Am i missing something i need to do in order to run tests which make use of a plugin?

答:
If you're using shared_preferences 0.2.4 and above, use setMockInitialValues:

```<code>SharedPreferences.setMockInitialValues({}); // set initial values here if desired
</code>```

For earlier versions you can do it manually:

```<code>const MethodChannel('plugins.flutter.io/shared_preferences')
  .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{}; // set initial values here if desired
    }
    return null;
  });
</code>```

Title: Flutter Test MissingPluginException

Body:
Running tests which rely on the SharedPreferences Plugin always result in

MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)

My pubspec.yaml

dev_dependencies:
  flutter_test:
     sdk: flutter

dependencies:
  flutter:
     sdk: flutter
  shared_preferences: 0.2.3

The code for works fine in the application itself.
Am i missing something i need to do in order to run tests which make use of a plugin?

Body:
If you're using shared_preferences 0.2.4 and above, use setMockInitialValues:

SharedPreferences.setMockInitialValues({}); // set initial values here if desired

For earlier versions you can do it manually:

const MethodChannel('plugins.flutter.io/shared_preferences')
  .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{}; // set initial values here if desired
    }
    return null;
  });


问:
Conditionally chaining promises - how to avoid code duplication?
I have the following:

```<code>if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseMakerB(someLongListOfArguments);
     });
}
else
    return promiseMakerB(someLongListOfArguments);
</code>```

How can I eliminate that code repetition (promiseMakerB)?

答:
Assuming arguments are the same in each condition for promiseB store it in a variable first ... then return that variable where applicable</p>

```<code>let promiseB = promiseMakerB(someLongListOfArguments);

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseB;
     });
}
else
    return promiseB;
</code>```

Body:
I have the following:

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseMakerB(someLongListOfArguments);
     });
}
else
    return promiseMakerB(someLongListOfArguments);

How can I eliminate that code repetition (promiseMakerB)?

Body:
Assuming arguments are the same in each condition for promiseB store it in a variable first ... then return that variable where applicable

let promiseB = promiseMakerB(someLongListOfArguments);

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseB;
     });
}
else
    return promiseB;


答:
From the jQuery docs on val():

When the first element in the collection is a select-multiple (i.e., a
  select element with the multiple attribute set), .val() returns an
  array containing the value of each selected option.

So it's actually jQuery magic, not JavaScript magic.

You can see the actual source code for val() here. It's a function that calls the get hook of the select element, which actually does a loop over the selected options.


问:
Dynamically generate an SQL `WHERE` query, from a `View` in Laravel
I am working on a back-up application with Laravel 5 and I have an issue.

I have to use the entered information from a View, so I can generate a SELECT *  query. The problem is that, WHERE, should be dynamic.

https://i.stack.imgur.com/tfV3z.png

Like, in the link above, where I show my query, the query I tried using is this:

SELECT * FROM table WHERE ch1 < 1 AND ch2 = 2;

答:
Why you are building the sql query by yourself?

It is better to use the Query builder of Laravel Illuminate\Database\Query\Builder:

Ex.:

```<code>$query = \DB::query();
$query->from($table);

foreach ($details as $detail)
{
    $query->where($detail->field_name, $detail->operand, $detail->value);
}
</code>```

you can read mor about the query builder here

Body:
Why you are building the sql query by yourself?

It is better to use the Query builder of Laravel Illuminate\Database\Query\Builder:

Ex.:

$query = \DB::query();
$query->from($table);

foreach ($details as $detail)
{
    $query->where($detail->field_name, $detail->operand, $detail->value);
}

you can read mor about the query builder here


问:
Silverlight 4 NumericUpDown buttons are too wide and non-functional
I placed this control in a test app, and it works fine.
But in my business app, which has a Silverlight 4 implicit theme applied (AccentColor theme), the up/down buttons are too wide and non-functional. I know for sure this is not what the theme calls for - I found a site showing off the theme on various controls, and the NumericUpDown control looks normal and is functional in every way:

http://www.silverlight.net/content/samples/sl4/themes/accent.html#/Toolkit

I've also placed this NumericUpDown control in various areas within my app. Still same thing. I've also tried to apply an explicit style of targettype NumericUpDown (the style being an empty style). But still the same thing.

Anybody seen something like?

答:
Turns out i had an implicit Button style that was setting the width to be really big.
This solved the width problem.

Now for the non-functional up/down problem, i just removed a reference in the style template that was referring to a spinner button, or something to that effect. Now it works just fine.


问:
Xamarin android import library
In java can add:

```<code>import com.runjva.sourceforge.jsocks.protocol.ProxyServer;
import com.runjva.sourceforge.jsocks.server.ServerAuthenticatorNone;
</code>```

but how I can do it in my xamarin android app?

答:
First thing, check nuget if what you look is already there.

If it is not there, use this VS extension:
https://github.com/EgorBo/Xamarin.GradleBindings

Download the extension from here:

https://marketplace.visualstudio.com/items?itemName=EgorBogatov.XamarinGradleBindings

Then after adding the extension to Visual Studio, right click on your reference and then you will see

Add Dependency via gradle

Put the dependency id.

Choose the dependencies you need and download them.

DONT FORGET to put the dependency into your Jar folder (because you might the produced member in your reference dll).

You might need to fix the problems by adding some lines in the metadata.xml*.

If you still don't get any members, you can extract the classes.jar file from the .aar file then rename it to the package file and follow the .jar binding instructions:

https://developer.xamarin.com/guides/android/advanced_topics/binding-a-java-library/binding-a-jar/

*Refer to binding troubleshooting to fix any issue you face (most of the binding needs that step of fixing the metadata.xml): https://developer.xamarin.com/guides/android/advanced_topics/binding-a-java-library/troubleshooting-bindings/ )

Title: Xamarin android import library

Body:
In java can add:

import com.runjva.sourceforge.jsocks.protocol.ProxyServer;
import com.runjva.sourceforge.jsocks.server.ServerAuthenticatorNone;

but how I can do it in my xamarin android app?


问:
How to display markers on amCharts world map using angular routing?
I am trying to include a world map chart in my web site. My problem is when the page is loaded in the first time everything is working, but when I am switching between views on the page, world map is loaded without markers, it looks like the map can't be fully loaded in angular routing.
What should I do in order to reload it?
Thanks in advance.</p>

```<code>  <!DOCTYPE html>
  <html lang="en-US">
  <head>
 <title>Online Trading Data</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
  href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-
  awesome/4.0.0/css/font-awesome.css" />

    <style>[ng:\:cloak],[ng-cloak],.ng-cloak { display:none;}</style>
    <style>
     html,
     body {
     width: 100%;
     height: 100%;
     margin: 0px;
    }

   #chartdiv {
    width: 100%;
    height: 50%;
   }

  #selector {
   position: absolute;
   top: 20px;
   right: 20px;
   background: rgba(255, 255, 255, 0.7);
   padding: 10px;
   font-size: 16px;
 }

 #selector input,
 #selector select {
   padding: 5px;
 }

 .ammapDescriptionTitle {
   font-size: 15px;
  font-weight: bold;
  color:#000;
}
.ammapDescriptionText {
  max-height: 200px;
  overflow: auto;
  border:1px solid;
  background-color:#dedede;
  color:#000;
}
.ammapDescriptionText img, .ammapDescriptionText p {
  max-width: 95%;
}

    </style>
    </head>

    <body>

    <div ng-app="scotchApp">
    <ul class="nav navbar-nav navbar-right">
                        <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
                        <li><a href="#about"><i class="fa fa-shield"></i> About</a></li>
                        <li><a href="#contact"><i class="fa fa-comment"></i> Contact</a></li>
                    </ul>
    <div ng-view></div>

    </div>

    <!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> -->
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
    <script src="https://www.amcharts.com/lib/3/ammap.js"></script>
    <script src="https://www.amcharts.com/lib/3/maps/js/worldLow.js"></script>
    <script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
    <script>
     var scotchApp = angular.module('scotchApp', ['ngRoute']);

        // configure our routes
        scotchApp.config(function($routeProvider) {
            $routeProvider

                // route for the home page
                .when('/', {
                    template : '<div id="chartdiv" style="height:500px !important; width:980px!important;">sdsd</div>',
                    controller  : 'mainController'
                })

                .when('/about', {
                    template : '<div>Second page</div>',
                    controller  : 'aboutController'
                })

                .when('/contact', {
                    template : '<div>Third page</div>',
                    controller  : 'contactController'
                });
        });

        scotchApp.controller('mainController', function($scope) {
        var relevantcities = [
        {
          "title": "Berlin",
          "latitude": 52.5235,
          "longitude": 13.4115
        },{
          "title": "Monaco",
          "latitude": 43.7325,
          "longitude": 7.4189
        },{
          "title": "Moscow",
          "latitude": 55.7558,
          "longitude": 37.6176
        },{
          "title": "Madrid",
          "latitude": 40.4167,
          "longitude": -3.7033
        },{
          "title": "London",
          "latitude": 51.5002,
          "longitude": -0.1262
        },{
          "title": "New Delhi",
          "latitude": 28.6353,
          "longitude": 77.2250
        },{
          "title": "Jerusalem",
          "latitude": 31.7857,
          "longitude": 35.2007
        },{
          "title": "Tokyo",
          "latitude": 35.6785,
          "longitude": 139.6823
        },{
          "title": "Bangkok",
          "latitude": 13.7573,
          "longitude": 100.5020
        }, {
          "title": "Abu Dhabi",
          "latitude": 24.4764,
          "longitude": 54.3705
        },{
          "title": "Washington",
          "latitude": 38.8921,
          "longitude": -77.0241,
          "color":"#000"
        }

        ];
            var targetSVG = "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z";

            var map = AmCharts.makeChart( "chartdiv", {
              "type": "map",
              "theme": "light",

              "imagesSettings": {
                "rollOverColor": "#000",
                "rollOverScale": 1,
                "selectedScale": 1,
                "selectedColor": "red",
                "color": "#13564e"
              },

              "areasSettings": {
                "unlistedAreasColor": "#000"
              },

              "dataProvider": {
                "map": "worldLow",
                "images": []
              }
            } );

            // populate the city dropdown when the page loads
            AmCharts.ready( function() {
            relevantcities.forEach( function (arrayItem)
            {
                    var city = arrayItem;
                    city.svgPath = targetSVG;
                    city.zoomLevel = 3;
                    city.scale = 1.2;
                    city.label = city.title + " +25%";
                    city.color = "green";
                    //city.description ="<img src='http://upload.wikimedia.org/wikipedia/commons/9/97/Palace_of_Westminster%2C_London_-_Feb_2007.jpg' /><p>London is the capital and most populous city of England and the United Kingdom. Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium. London's ancient core, the City of London, largely retains its 1.12-square-mile (2.9 km2) medieval boundaries and in 2011 had a resident population of 7,375, making it the smallest city in England. Since at least the 19th century, the term London has also referred to the metropolis developed around this core The bulk of this conurbation forms the Greater London administrative area (coterminous with the London region), governed by the Mayor of London and the London Assembly.</p>";

                  // add city object to map
                  map.dataProvider.images.push( city );
                  map.validateData();
            });

            } );

        });

        scotchApp.controller('aboutController', function($scope) {
            $scope.message = 'Look! I am an about page.';
        });

        scotchApp.controller('contactController', function($scope) {
            $scope.message = 'Contact us! JK. This is just a demo.';
        });

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

答:
AmCharts.ready is the equivalent of window.onload, so it's useless in this scenario as your code will only run once. Getting rid of that ready call and having your forEach code run on its own will make it work. You also don't want to call validateData after each image is added as it will slow down the process - just call it once after your forEach is done.

I'm not really sure why you have your forEach code running after makeChart when you can just create the images upfront and assign it to the images array in the makeChart call itself. If you must have the image setup code run only when the map is initialized, put it in the map's init event:

```<code>  var map = AmCharts.makeChart("chartdiv", {
    // ..
    listeners: [
      {
        event: "init",
        method: function(e) {
          var map = e.chart;
          // populate the city dropdown when the page loads
          relevantcities.forEach(function(arrayItem) {
            var city = arrayItem;
            city.svgPath = targetSVG;
            city.zoomLevel = 3;
            city.scale = 1.2;
            city.label = city.title + " +25%";
            city.color = "green";

            // add city object to map
            map.dataProvider.images.push(city);
          });
          map.validateData();
        }
      }
    ]
  });
</code>```

Body:
I am trying to include a world map chart in my web site. My problem is when the page is loaded in the first time everything is working, but when I am switching between views on the page, world map is loaded without markers, it looks like the map can't be fully loaded in angular routing.
What should I do in order to reload it?
Thanks in advance.

  <!DOCTYPE html>

 <title>Online Trading Data</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
  href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-
  awesome/4.0.0/css/font-awesome.css" />

 Home

 About

 Contact

Body:
AmCharts.ready is the equivalent of window.onload, so it's useless in this scenario as your code will only run once. Getting rid of that ready call and having your forEach code run on its own will make it work. You also don't want to call validateData after each image is added as it will slow down the process - just call it once after your forEach is done.

I'm not really sure why you have your forEach code running after makeChart when you can just create the images upfront and assign it to the images array in the makeChart call itself. If you must have the image setup code run only when the map is initialized, put it in the map's init event:

  var map = AmCharts.makeChart("chartdiv", {
    // ..
    listeners: [
      {
        event: "init",
        method: function(e) {
          var map = e.chart;
          // populate the city dropdown when the page loads
          relevantcities.forEach(function(arrayItem) {
            var city = arrayItem;
            city.svgPath = targetSVG;
            city.zoomLevel = 3;
            city.scale = 1.2;
            city.label = city.title + " +25%";
            city.color = "green";

            // add city object to map
            map.dataProvider.images.push(city);
          });
          map.validateData();
        }
      }
    ]
  });