问:
CMake <PROJECT-NAME>_SOURCE_DIR Variable Scope
Based on the thread "cmake variable scope, add_subdirectory", the CMake set command will set the variable in the current scope only, unless the PARENT_SCOPE parameter is specified.

Recently when I was looking at the project command, per CMake doc, variables <PROJECT-NAME>_SOURCE_DIR and <PROJECT-NAME>_BINARY_DIR will be set. But it didn't mention what is the scope of these variables. Can these variable be used in other subdirectory? For example:

|- root
| |- CMakeLists.txt  // add_subdirectory(proj1); add_subdirectory(proj2)
| |
| |- proj1
| |  |- CMakeLists.txt  // project(proj1)
| |
| |- proj2
| |  |- CMakeLists.txt  // Does this have access to proj1_SOURCE_DIR or
                        // poj1_BINARY_DIR?

What about variables for other command like Find_Package? What is the scope of the <Module>_FOUND variable? Thanks!

答:
From the documentation of project:

The top-level CMakeLists.txt file for a project must contain a
  literal, direct call to the project() command; loading one through the
  include() command is not sufficient. If no such call exists CMake will
  implicitly add one to the top that enables the default languages (C
  and CXX).

So, those variables are already there and propagate scopes down the layout.

Now, the project command should normally be used once in project, since it sets up various flags. If your other sub-projects are also required to be built by themselves as standalone, then a common idiom is to have a check like this:

```<code>if(CURRENT_CMAKE_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
  project(foo CXX)

  # other stuff here
endif()
</code>```

Please note that the PARENT_SCOPE is useful in the context of functions and their call sites.

Body:
From the documentation of project:

The top-level CMakeLists.txt file for a project must contain a
  literal, direct call to the project() command; loading one through the
  include() command is not sufficient. If no such call exists CMake will
  implicitly add one to the top that enables the default languages (C
  and CXX).

So, those variables are already there and propagate scopes down the layout.

Now, the project command should normally be used once in project, since it sets up various flags. If your other sub-projects are also required to be built by themselves as standalone, then a common idiom is to have a check like this:

if(CURRENT_CMAKE_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
  project(foo CXX)

  # other stuff here
endif()

Please note that the PARENT_SCOPE is useful in the context of functions and their call sites.


来源: stackexchange

问:
Inserting byte file inside html  tag
I'm using Angular 2 to retrieve image from backend. My response looks like that

```<code>{ AcceptRanges: 'bytes',
LastModified: 'Sat, 09 Dec 2017 17:06:46 GMT',
ContentLength: '462882',
ETag: '"c0ff5b060c2da69deff97065d43e3645"',
ContentType: 'application/octet-stream',
Metadata: {},
Body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 64 00 64 00 00 ff ec 00 11 4475 63 6b 79 00 01 00 04 00 00 00 3c 00 00 ff ee 00 0e 41 64 6f 62 65 00 64 ... > }
</code>```

Is there any chance I can insert that thing directly inside html img tag, or should I start off by converting it to say base64? Thank you in advance.

答: I would suggest you to use responseType: ResponseContentType.Blob in your GET-Request settings and convert it later to base64 encoded source. Hope this helps</p>

ContentLicense: CC BY-SA 3.0

Title: Inserting byte file inside html <img> tag

Body:
I'm using Angular 2 to retrieve image from backend. My response looks like that

{ AcceptRanges: 'bytes',
LastModified: 'Sat, 09 Dec 2017 17:06:46 GMT',
ContentLength: '462882',
ETag: '"c0ff5b060c2da69deff97065d43e3645"',
ContentType: 'application/octet-stream',
Metadata: {},
Body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 64 00 64 00 00 ff ec 00 11 4475 63 6b 79 00 01 00 04 00 00 00 3c 00 00 ff ee 00 0e 41 64 6f 62 65 00 64 ... > }

Is there any chance I can insert that thing directly inside html img tag, or should I start off by converting it to say base64? Thank you in advance.


问:
Google map doesn't appear and markers don't generate from xml file
The initMap function worked until I added the downloadurl function, and now nothing's appearing on the screen. Everthing else on the page works normally. How can I generate the map and also the coordinates with their respective markers?

```<code>function initMap() {
 map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.75372, lng: 21.22571},
zoom: 15
});

function downloadUrl(url,callback) {
  var request = window.ActiveXObject ?
   new ActiveXObject('Microsoft.XMLHTTP') :
   new XMLHttpRequest;

request.onreadystatechange = function() {
 if (request.readyState == 4) {
   request.onreadystatechange = doNothing;
   callback(request, request.status);
 }
 };

request.open('GET', url, true);
request.send(null);
}

downloadUrl('map.php', function(data) {
  var xml = data.responseXML;
  var markers = xml.documentElement.getElementsByTagName('marker');
  Array.prototype.forEach.call(markers, function(markerElem) {
    var id = markerElem.getAttribute('id');
    var name = markerElem.getAttribute('name');
    var address = markerElem.getAttribute('address');
    var type = markerElem.getAttribute('type');
    var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

    var infowincontent = document.createElement('div');
    var strong = document.createElement('strong');
    strong.textContent = name
    infowincontent.appendChild(strong);
    infowincontent.appendChild(document.createElement('br'));

    var text = document.createElement('text');
    text.textContent = address
    infowincontent.appendChild(text);
    var icon = customLabel[type] || {};
    var marker = new google.maps.Marker({
      map: map,
      position: point,
      label: icon.label
    });
</code>```

Below is the php that generates the xml. This works as expected.

```<code>    <?php
     include('includes/functions.php');
     function parseToXML($htmlStr)
     {
              $xmlStr=str_replace('<','<',$htmlStr);
              $xmlStr=str_replace('>','>',$xmlStr);
              $xmlStr=str_replace('"','"',$xmlStr);
              $xmlStr=str_replace("'",''',$xmlStr);
              $xmlStr=str_replace("&",'&',$xmlStr);
              return $xmlStr;
          }
          $res = getMarkers();
          header("Content-type: text/xml");
          echo '<markers>';
          while ($row = $res->fetch_assoc()) {
              echo '<marker ';
            echo 'id="' . $row['id'] . '" ';
            echo 'name="' . parseToXML($row['name']) . '" ';
            echo 'address="' . parseToXML($row['address']) . '" ';
            echo 'lat="' . $row['lat'] . '" ';
            echo 'lng="' . $row['lng'] . '" ';
            echo 'type="' . $row['type'] . '" ';
            echo '/>';
          }
          echo '</markers>';

          ?>
</code>```

答:
I started off formatting your original code and found that there are bits missing and ended up with what you see below which, for the record, has not been tested at all. If the code you originally posted was "as is" ( ie: complete ) then there would have been numerous errors in the console I suspect. I interpreted the above code almost as written - in that the initMap function itself defines the methods that it uses as opposed to them being separate - whether or not the original code was written in that manner is not clear due to the formatting of the question.

```<code>function initMap() {
    var mkrs=evts=[];

    var map = new google.maps.Map( document.getElementById('map'), {
        center: {
            lat: 45.75372,
            lng: 21.22571
        },
        zoom: 15
    });
    var iWin=new google.maps.InfoWindow( { maxWidth:400 } );

    var downloadUrl=function(url, callback) {
        var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
        request.onreadystatechange = function() {
            if( request.status==200 && request.readyState == 4 ) {
                request.onreadystatechange = doNothing;
                callback.call( this, request, request.getResponseHeader('Content-Type') );
            }
        };
        request.open( 'GET', url, true );
        request.send( null );
    }

    var callback=function( data, ctype ) {
        /* inspect response - if there is none then panic! */
        console.log( 'Response: %o, Content-Type: %s', data, ctype );
        /*
            I'd be tempted to fork the logic in the php code
            so that if there is an error/exception of some type
            then send a non xml content type response and use the
            ctype here to stop processing client side...
        */
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');

        Array.prototype.forEach.call( markers, function( node ) {

            var id = node.getAttribute('id');
            var name = node.getAttribute('name');
            var address = node.getAttribute('address');
            var type = node.getAttribute('type');

            var point = new google.maps.LatLng(
                parseFloat( node.getAttribute('lat') ),
                parseFloat( node.getAttribute('lng') )
            );

            /* prepare infowindow content */
            var div = document.createElement('div');
            var strong = document.createElement('strong');
                strong.textdiv = name;
            var text = document.createElement('p');
                text.textdiv = address;

            div.appendChild( strong );
            div.appendChild( document.createElement('br') );
            div.appendChild( text );

            var icon = customLabel[ type ] || {};   /* ? where is customLabel defined ? */
            var marker = new google.maps.Marker({
                id:id,
                map: map,
                position: point,
                label: icon.label
            });
            mkrs.push( marker );

            var evt = google.maps.event.addListener( marker, 'click', function( event ){
                iWin.setdiv( div );
                iWin.open( map, marker );
                iWin.setPosition( event.latLng );
            });
            evts.push( evt );
        });
    }

    downloadUrl.call( this, 'map.php', callback );
}
</code>```

Body:
The initMap function worked until I added the downloadurl function, and now nothing's appearing on the screen. Everthing else on the page works normally. How can I generate the map and also the coordinates with their respective markers?

function initMap() {
 map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.75372, lng: 21.22571},
zoom: 15
});

function downloadUrl(url,callback) {
  var request = window.ActiveXObject ?
   new ActiveXObject('Microsoft.XMLHTTP') :
   new XMLHttpRequest;

request.onreadystatechange = function() {
 if (request.readyState == 4) {
   request.onreadystatechange = doNothing;
   callback(request, request.status);
 }
 };

request.open('GET', url, true);
request.send(null);
}

downloadUrl('map.php', function(data) {
  var xml = data.responseXML;
  var markers = xml.documentElement.getElementsByTagName('marker');
  Array.prototype.forEach.call(markers, function(markerElem) {
    var id = markerElem.getAttribute('id');
    var name = markerElem.getAttribute('name');
    var address = markerElem.getAttribute('address');
    var type = markerElem.getAttribute('type');
    var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

    var infowincontent = document.createElement('div');
    var strong = document.createElement('strong');
    strong.textContent = name
    infowincontent.appendChild(strong);
    infowincontent.appendChild(document.createElement('br'));

    var text = document.createElement('text');
    text.textContent = address
    infowincontent.appendChild(text);
    var icon = customLabel[type] || {};
    var marker = new google.maps.Marker({
      map: map,
      position: point,
      label: icon.label
    });

Below is the php that generates the xml. This works as expected.

    <?php
     include('includes/functions.php');
     function parseToXML($htmlStr)
     {
              $xmlStr=str_replace('<','<',$htmlStr);
              $xmlStr=str_replace('>','>',$xmlStr);
              $xmlStr=str_replace('"','"',$xmlStr);
              $xmlStr=str_replace("'",''',$xmlStr);
              $xmlStr=str_replace("&",'&',$xmlStr);
              return $xmlStr;
          }
          $res = getMarkers();
          header("Content-type: text/xml");
          echo '<markers>';
          while ($row = $res->fetch_assoc()) {
              echo '<marker ';
            echo 'id="' . $row['id'] . '" ';
            echo 'name="' . parseToXML($row['name']) . '" ';
            echo 'address="' . parseToXML($row['address']) . '" ';
            echo 'lat="' . $row['lat'] . '" ';
            echo 'lng="' . $row['lng'] . '" ';
            echo 'type="' . $row['type'] . '" ';
            echo '/>';
          }
          echo '</markers>';

          ?>

Body:
I started off formatting your original code and found that there are bits missing and ended up with what you see below which, for the record, has not been tested at all. If the code you originally posted was "as is" ( ie: complete ) then there would have been numerous errors in the console I suspect. I interpreted the above code almost as written - in that the initMap function itself defines the methods that it uses as opposed to them being separate - whether or not the original code was written in that manner is not clear due to the formatting of the question.

function initMap() {
    var mkrs=evts=[];

    var map = new google.maps.Map( document.getElementById('map'), {
        center: {
            lat: 45.75372,
            lng: 21.22571
        },
        zoom: 15
    });
    var iWin=new google.maps.InfoWindow( { maxWidth:400 } );

    var downloadUrl=function(url, callback) {
        var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
        request.onreadystatechange = function() {
            if( request.status==200 && request.readyState == 4 ) {
                request.onreadystatechange = doNothing;
                callback.call( this, request, request.getResponseHeader('Content-Type') );
            }
        };
        request.open( 'GET', url, true );
        request.send( null );
    }

    var callback=function( data, ctype ) {
        /* inspect response - if there is none then panic! */
        console.log( 'Response: %o, Content-Type: %s', data, ctype );
        /*
            I'd be tempted to fork the logic in the php code
            so that if there is an error/exception of some type
            then send a non xml content type response and use the
            ctype here to stop processing client side...
        */
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');

        Array.prototype.forEach.call( markers, function( node ) {

            var id = node.getAttribute('id');
            var name = node.getAttribute('name');
            var address = node.getAttribute('address');
            var type = node.getAttribute('type');

            var point = new google.maps.LatLng(
                parseFloat( node.getAttribute('lat') ),
                parseFloat( node.getAttribute('lng') )
            );

            /* prepare infowindow content */
            var div = document.createElement('div');
            var strong = document.createElement('strong');
                strong.textdiv = name;
            var text = document.createElement('p');
                text.textdiv = address;

            div.appendChild( strong );
            div.appendChild( document.createElement('br') );
            div.appendChild( text );

            var icon = customLabel[ type ] || {};   /* ? where is customLabel defined ? */
            var marker = new google.maps.Marker({
                id:id,
                map: map,
                position: point,
                label: icon.label
            });
            mkrs.push( marker );

            var evt = google.maps.event.addListener( marker, 'click', function( event ){
                iWin.setdiv( div );
                iWin.open( map, marker );
                iWin.setPosition( event.latLng );
            });
            evts.push( evt );
        });
    }

    downloadUrl.call( this, 'map.php', callback );
}


问:
bat command - eliminate the strings from right to left
im trying to split the strings. please find the details below,

Scenario:

```<code>set test1=“C:A\B\C\D\X\Y\Z”
set test2=“D:A\B\X\Y\Z”

echo %test1%
echo %test2%
</code>```

i have to eliminate “\X\Y\Z” and i need the remaining string.
expectation is it should print like below output

```<code>echo C:A\B\C\D
echo D:A\B
</code>```

Thanks for reading this

答:
In case you don't want to remove a known string, but want the folder name "three up":</p>

```<code>set "test1=C:\A\B\C\D\X\Y\Z"
for %%a in ("%test1%\..\..\..") do echo %%~fa
</code>```

Body:
im trying to split the strings. please find the details below,

Scenario:

set test1=“C:A\B\C\D\X\Y\Z”
set test2=“D:A\B\X\Y\Z”

echo %test1%
echo %test2%

i have to eliminate “\X\Y\Z” and i need the remaining string.
expectation is it should print like below output

echo C:A\B\C\D
echo D:A\B

Thanks for reading this

Body:
In case you don't want to remove a known string, but want the folder name "three up":

set "test1=C:\A\B\C\D\X\Y\Z"
for %%a in ("%test1%\..\..\..") do echo %%~fa


问:
Add a column to a multiple SELECT SQL query string
The below code works, but I want to add the column "segvalue1" to my query result:

```<code>SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod between 1 AND 10
AND Company = 'NVV' AND FiscalYear = 2017),

(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017)
</code>```

So I modified the code to look like the below but it gives me 2 "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" errors :

```<code>SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod
between 1 AND 10 AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1),

(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1)
</code>```

Does anyone know how to modify the code to get my desired result? Again, I am just trying to pull in the segvalue1 column. Once I figure this out, I will also pull in a couple more columns. Thanks for your help!

答:
Consider conditional aggregation:</p>

```<code>SELECT segvalue1,
       SUM(CASE WHEN FiscalPeriod BETWEEN 1 AND 10
                THEN DebitAmount-CreditAmount
                ELSE NULL
           END) as BalanceAmtCYTD,
       SUM(CASE WHEN FiscalPeriod = 10
                THEN DebitAmount-CreditAmount
                ELSE NULL
           END) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK)
WHERE Company = 'NVV' AND FiscalYear = 2017             -- SHARED CONDITION
GROUP BY segvalue1
</code>```

Body:
The below code works, but I want to add the column "segvalue1" to my query result:

SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod between 1 AND 10
AND Company = 'NVV' AND FiscalYear = 2017),

(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017)

So I modified the code to look like the below but it gives me 2 "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" errors :

SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod
between 1 AND 10 AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1),

(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1)

Does anyone know how to modify the code to get my desired result? Again, I am just trying to pull in the segvalue1 column. Once I figure this out, I will also pull in a couple more columns. Thanks for your help!

Body:
Consider conditional aggregation:

SELECT segvalue1,
       SUM(CASE WHEN FiscalPeriod BETWEEN 1 AND 10
                THEN DebitAmount-CreditAmount
                ELSE NULL
           END) as BalanceAmtCYTD,
       SUM(CASE WHEN FiscalPeriod = 10
                THEN DebitAmount-CreditAmount
                ELSE NULL
           END) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK)
WHERE Company = 'NVV' AND FiscalYear = 2017             -- SHARED CONDITION
GROUP BY segvalue1


问:
Does swift have a "C Type" protocol?
I would like to constrain a generic to a type that can be represented in C.  Is there a protocol or type in the Swift standard library that all C types conform to?

```<code>func doWithCType<T:CRepresentable>(cValue: T) {
    // do thing with C type
}
</code>```

If not a CRepresentable, maybe a CStruct type?

Clues:

Using this C type:

```<code>typedef struct {
    int hodor;
} Hodor;
</code>```

I force casted a struct to an incompatible type (causing a crash). This was the error message: Could not cast value of type '__C.Hodor' (0x1035c0700) to 'Swift.CVarArg' (0x107196240).

I can't find "__C" anywhere, but I'm hopeful that there's a distinction for the C types.

答:
Is Swift.CVarArg what you need?  It is for types that can be passed through C's va_list mechanism for varargs.

There is also CVaListPointer, which is equivalent to va_list *.  That appears in the arguments to String(format:).

https://developer.apple.com/documentation/swift/cvararg
https://developer.apple.com/documentation/swift/cvalistpointer

Title: Does swift have a "C Type" protocol?

Body:
I would like to constrain a generic to a type that can be represented in C.  Is there a protocol or type in the Swift standard library that all C types conform to?

func doWithCType<T:CRepresentable>(cValue: T) {
    // do thing with C type
}

If not a CRepresentable, maybe a CStruct type?

Clues:

Using this C type:

typedef struct {
    int hodor;
} Hodor;

I force casted a struct to an incompatible type (causing a crash). This was the error message: Could not cast value of type '__C.Hodor' (0x1035c0700) to 'Swift.CVarArg' (0x107196240).

I can't find "__C" anywhere, but I'm hopeful that there's a distinction for the C types.


问:
Disable script outside of the scene Unity 3D
In my chess game, I have a scene of pieces choice - black or white. After the user clicks on one of the pawns he/she gets a popup message/ It looks like this:

On Ok button click, the scene changes to the one with the board:

When the user chose black pieces he/she should see them closer to him/her, while if the user chose white pieces, they should be at the front. By default, in my scene pieces which are closer are black. I tried to achieve this by adding a texture change script on each figure (they will differ for white and black pieces):

```<code>void Start () {
        GetComponent<Renderer>().material = Resources.Load<Material>)"Materials/Pieces/Marble/White Pawn");
    }
</code>```

However, how can I disable this script when I redirect to the scene if the user chose black pieces and the default view is needed.
Here is my code for popup window:

```<code>void OnGUI()
    {
        if (showPopUp)
        {
            GUI.Window(0, new Rect((Screen.width / 2) - 200, (Screen.height / 2) - 115
                   , 420, 180), ShowGUI, "Figures choice");

        }
    }

    void ShowGUI(int windowID)
    {
        RedirectToMenu redirect = new RedirectToMenu();
        guiStyle.fontSize = 22;
        guiStyle.normal.textColor = Color.white;
        GUI.Label(new Rect(80, 40, 200, 30), "You have chosen black pieces", guiStyle);

        if (GUI.Button(new Rect(180, 110, 75, 35), "OK")){
            showPopUp = false;
            redirect.LoadAsset("UpgradedRoom");
            SceneManager.LoadScene("UpgradedRoom");
        }
    }
</code>```

I suppose I should access this script before loading the scene and disable if needed. But how can I access it outside of the scene with table, chessboard, and pieces? Or can I change the textures of game objects on another scene?

答:
What I would do is use a static variable to remember whether the pieces are black or white.  So, you'd set the variable before the scene loads and then check it after it is loaded.  Therefore, if your class is called chess manager, your code for setting the variable might look like this:

```<code>public class ChessManager : Monobehavior {
    public enum ChessColor { Black, White }
    public static ChessColor playerColor

    public void OnGUI() {
        if(user chooses black) {
            playerColor = ChessColor.Black;
            //Load scene
        }
        else if(user chooses white) {
            playerColor = ChessColor.White;
            //Load scene
        }
    }
}
</code>```

...And your code for enabling/disabling the script might be something like this, where ColorChanger is the script that sets the color:

```<code>public class ColorChanger : Monobehavior {
    public void Start() {
        if(ChessManager.playerColor == ChessManager.ChessColor.White) {
            //Set texture
        }
    }
}
</code>```

This would set the texture to something else when the user chooses white once the new scene is loaded.  Don't forget to replace the if statements in ChessManager with the code that executes when a chess piece is selected (I'm assuming you're using legacy buttons for that, so you should replace if(user chooses color) with if(GUI.Button)).  Hope I could help!

Also, as previously noted by someone else in the comments, it would probably be best if you used UnityEngine.UI instead of Unity's outdated legacy GUI system, but depending upon the project it might not be worth the effort.

Body:
In my chess game, I have a scene of pieces choice - black or white. After the user clicks on one of the pawns he/she gets a popup message/ It looks like this:

On Ok button click, the scene changes to the one with the board:

When the user chose black pieces he/she should see them closer to him/her, while if the user chose white pieces, they should be at the front. By default, in my scene pieces which are closer are black. I tried to achieve this by adding a texture change script on each figure (they will differ for white and black pieces):

void Start () {
        GetComponent<Renderer>().material = Resources.Load<Material>)"Materials/Pieces/Marble/White Pawn");
    }

However, how can I disable this script when I redirect to the scene if the user chose black pieces and the default view is needed.
Here is my code for popup window:

void OnGUI()
    {
        if (showPopUp)
        {
            GUI.Window(0, new Rect((Screen.width / 2) - 200, (Screen.height / 2) - 115
                   , 420, 180), ShowGUI, "Figures choice");

        }
    }

    void ShowGUI(int windowID)
    {
        RedirectToMenu redirect = new RedirectToMenu();
        guiStyle.fontSize = 22;
        guiStyle.normal.textColor = Color.white;
        GUI.Label(new Rect(80, 40, 200, 30), "You have chosen black pieces", guiStyle);

        if (GUI.Button(new Rect(180, 110, 75, 35), "OK")){
            showPopUp = false;
            redirect.LoadAsset("UpgradedRoom");
            SceneManager.LoadScene("UpgradedRoom");
        }
    }

I suppose I should access this script before loading the scene and disable if needed. But how can I access it outside of the scene with table, chessboard, and pieces? Or can I change the textures of game objects on another scene?

Body:
What I would do is use a static variable to remember whether the pieces are black or white.  So, you'd set the variable before the scene loads and then check it after it is loaded.  Therefore, if your class is called chess manager, your code for setting the variable might look like this:

public class ChessManager : Monobehavior {
    public enum ChessColor { Black, White }
    public static ChessColor playerColor

    public void OnGUI() {
        if(user chooses black) {
            playerColor = ChessColor.Black;
            //Load scene
        }
        else if(user chooses white) {
            playerColor = ChessColor.White;
            //Load scene
        }
    }
}

...And your code for enabling/disabling the script might be something like this, where ColorChanger is the script that sets the color:

public class ColorChanger : Monobehavior {
    public void Start() {
        if(ChessManager.playerColor == ChessManager.ChessColor.White) {
            //Set texture
        }
    }
}

This would set the texture to something else when the user chooses white once the new scene is loaded.  Don't forget to replace the if statements in ChessManager with the code that executes when a chess piece is selected (I'm assuming you're using legacy buttons for that, so you should replace if(user chooses color) with if(GUI.Button)).  Hope I could help!

Also, as previously noted by someone else in the comments, it would probably be best if you used UnityEngine.UI instead of Unity's outdated legacy GUI system, but depending upon the project it might not be worth the effort.


问:
spss search for value in dataset
I'd like to find any cases of a value (e.g., 0) in any cell in an SPSS database. What syntax would accomplish this? </p>

<p>(I came across a python script but don't have that option.)</p>

答:
The following syntax will create a list of appearances of 0 within your data - In a separate file:

First creating some fake data to demonstrate on.

```<code>data list list/ID (a6) test1 to test6 (6f2).
begin data
ID_001 2 3 2 3 0 3
ID_002 3 4 0 4 3 4
ID_003 0 4 2 4 2 4
ID_004 7 0 1 2 8 3
ID_005 5 5 5 0 5 5
ID_006 4 5 4 5 4 0
end data.
dataset name origData.
</code>```

Now to create the list:

```<code>dataset copy ForList.
dataset activate ForList. /* the list will be created from a copy of the data.
varstocases /make vals from test1 to test6/index testNum(vals).
select if vals=0.
</code>```

You can use the list in the new file, or put it in the output window:

```<code>list ID testNum.
</code>```

Title: spss search for value in dataset

Body:
I'd like to find any cases of a value (e.g., 0) in any cell in an SPSS database. What syntax would accomplish this?

(I came across a python script but don't have that option.)

Body:
The following syntax will create a list of appearances of 0 within your data - In a separate file:

First creating some fake data to demonstrate on.

data list list/ID (a6) test1 to test6 (6f2).
begin data
ID_001 2 3 2 3 0 3
ID_002 3 4 0 4 3 4
ID_003 0 4 2 4 2 4
ID_004 7 0 1 2 8 3
ID_005 5 5 5 0 5 5
ID_006 4 5 4 5 4 0
end data.
dataset name origData.

Now to create the list:

dataset copy ForList.
dataset activate ForList. /* the list will be created from a copy of the data.
varstocases /make vals from test1 to test6/index testNum(vals).
select if vals=0.

You can use the list in the new file, or put it in the output window:

list ID testNum.


问:
Resulting all the indices while trying to get only those indices which are associated with specific alias
I have recently upgraded application from Elastic search 5.3.1 to 6.0.

My requirement was to get all the indices which were associated with specific alias.

I used below mentioned snippet to fetch all indices associated with specific alias . This snippet is working fine in 5.3.1 and giving only those indices which are associated with that specific alias.

```<code>GetAliasesResponse r = client.admin().indices().getAliases(new
GetAliasesRequest("givenalias")).actionGet();
</code>```

But after ES 6.0 , the same snippet giving all the indices which are created in system .

Ideally it should only return those indices which are associated with given alias .Not others. This was working in Elastic search 5.3.1.

答:
TL;DR: It is an intended breaking change in the Java API of Elasticsearch (though it is not explicitly mentioned in the "Breaking changes in 6.0 » Java API changes" page).

The following is the story of discovering this fact. (Note: the original answer was heavily edited, hence comments might be out of date.)

Breaking changes in the REST API in 6.0

First I noticed that this part of the REST API changed in Elasticsearch 6.0. There are two reported breaking changes concerning aliases:

GET /_aliases,_mappings syntax was removed in favor of GET /_aliases/GET /_mappings

Indices aliases api resolves indices expressions only against indices

Though there isn't mentioned anything concerning OP's case.

From what I have seen doing queries, this query works in Elasticsearch 5:

```<code>GET /alias1/_aliases
</code>```

And does not work in Elasticsearch 6, giving the following error:

```<code>{
  "error": "Incorrect HTTP method for uri [/alias1/_aliases] and method [GET], allowed: [PUT]",
  "status": 405
}
</code>```

Interestingly, GET /alias1/_alias works in both versions and returns same result.

Moreover, I didn't manage to find an example of GET /alias1/_aliases in the documentation of nor 5.6, neither 6.0.

Reproducing the bug

After having realised that OP is actually using the Java API, I managed to reproduce the exact same behavior.

The following code:

```<code>GetAliasesResponse alias1 = client.admin().indices()
    .getAliases(new GetAliasesRequest("alias1")).actionGet();
</code>```

In ES 5 produces this in the IntelliJ debugger:

And for ES 6 I've got the following:

As you can see, there are extra keys in the second output, which have empty values.

Diving into the source code

Quick search over the elasticsearch codebase gave me the final explanation. In ES 5 there was a test testIndicesGetAliases which was checking that list of indices returned for a test alias has exactly one element (IndexAliasesIT.java#L554):

```<code>    logger.info("--> getting alias1");
    GetAliasesResponse getResponse = admin().indices().prepareGetAliases("alias1").get();
    assertThat(getResponse, notNullValue());
    assertThat(getResponse.getAliases().size(), equalTo(1));
</code>```

And in 6.0 it checks that the size is 5! (IndexAliasesIT.java#L573)

```<code>    logger.info("--> getting alias1");
    GetAliasesResponse getResponse = admin().indices().prepareGetAliases("alias1").get();
    assertThat(getResponse, notNullValue());
    assertThat(getResponse.getAliases().size(), equalTo(5));
</code>```

This change was introduced in this commit, which is related to these issues:

Remove comma-separated feature parsing for GetIndicesAction #24723

_alias API no longer accepts index wildcards #25090

This is actually interesting, because one of the reported REST API breaking changes that we have see above also broke compatibility of some Java API calls.

What you can do

In short term, you need just to filter out those keys with empty values.

In longer term I think it makes sense to migrate to Java High Level REST Client since Elastic plan to deprecate the TransportClient in version 7.0:

We plan on deprecating the TransportClient in Elasticsearch 7.0 and
  removing it completely in 8.0. Instead, you should be using the Java
  High Level REST Client, which executes HTTP requests rather than
  serialized Java requests.

In general, Elasticsearch breaks compatibility quite often, so it's better to stay away from the dark corners of it like Java API.

Thanks for reading.

Hope that helps!

Body:
I have recently upgraded application from Elastic search 5.3.1 to 6.0.

My requirement was to get all the indices which were associated with specific alias.

I used below mentioned snippet to fetch all indices associated with specific alias . This snippet is working fine in 5.3.1 and giving only those indices which are associated with that specific alias.

GetAliasesResponse r = client.admin().indices().getAliases(new
GetAliasesRequest("givenalias")).actionGet();

But after ES 6.0 , the same snippet giving all the indices which are created in system .

Ideally it should only return those indices which are associated with given alias .Not others. This was working in Elastic search 5.3.1.

Body:
TL;DR: It is an intended breaking change in the Java API of Elasticsearch (though it is not explicitly mentioned in the "Breaking changes in 6.0 » Java API changes" page).

The following is the story of discovering this fact. (Note: the original answer was heavily edited, hence comments might be out of date.)

Breaking changes in the REST API in 6.0

First I noticed that this part of the REST API changed in Elasticsearch 6.0. There are two reported breaking changes concerning aliases:

GET /_aliases,_mappings syntax was removed in favor of GET /_aliases/GET /_mappings

Indices aliases api resolves indices expressions only against indices

Though there isn't mentioned anything concerning OP's case.

From what I have seen doing queries, this query works in Elasticsearch 5:

GET /alias1/_aliases

And does not work in Elasticsearch 6, giving the following error:

{
  "error": "Incorrect HTTP method for uri [/alias1/_aliases] and method [GET], allowed: [PUT]",
  "status": 405
}

Interestingly, GET /alias1/_alias works in both versions and returns same result.

Moreover, I didn't manage to find an example of GET /alias1/_aliases in the documentation of nor 5.6, neither 6.0.

Reproducing the bug

After having realised that OP is actually using the Java API, I managed to reproduce the exact same behavior.

The following code:

GetAliasesResponse alias1 = client.admin().indices()
    .getAliases(new GetAliasesRequest("alias1")).actionGet();

In ES 5 produces this in the IntelliJ debugger:

And for ES 6 I've got the following:

As you can see, there are extra keys in the second output, which have empty values.

Diving into the source code

Quick search over the elasticsearch codebase gave me the final explanation. In ES 5 there was a test testIndicesGetAliases which was checking that list of indices returned for a test alias has exactly one element (IndexAliasesIT.java#L554):

    logger.info("--> getting alias1");
    GetAliasesResponse getResponse = admin().indices().prepareGetAliases("alias1").get();
    assertThat(getResponse, notNullValue());
    assertThat(getResponse.getAliases().size(), equalTo(1));

And in 6.0 it checks that the size is 5! (IndexAliasesIT.java#L573)

    logger.info("--> getting alias1");
    GetAliasesResponse getResponse = admin().indices().prepareGetAliases("alias1").get();
    assertThat(getResponse, notNullValue());
    assertThat(getResponse.getAliases().size(), equalTo(5));

This change was introduced in this commit, which is related to these issues:

Remove comma-separated feature parsing for GetIndicesAction #24723

_alias API no longer accepts index wildcards #25090

This is actually interesting, because one of the reported REST API breaking changes that we have see above also broke compatibility of some Java API calls.

What you can do

In short term, you need just to filter out those keys with empty values.

In longer term I think it makes sense to migrate to Java High Level REST Client since Elastic plan to deprecate the TransportClient in version 7.0:

We plan on deprecating the TransportClient in Elasticsearch 7.0 and
  removing it completely in 8.0. Instead, you should be using the Java
  High Level REST Client, which executes HTTP requests rather than
  serialized Java requests.

In general, Elasticsearch breaks compatibility quite often, so it's better to stay away from the dark corners of it like Java API.

Thanks for reading.

Hope that helps!


问:
How to move to the next line when adding text using Apache PDFBox
I've just started using Apache PDFBox and been experimenting with various examples I've found.

However, I haven't been able to find an easy way to move to the next line when adding text.

E.g.

```<code>PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA;
content.beginText();
content.setFont(font, 12);
content.moveTextPositionByAmount(x, y);
content.drawString("Some text.");
content.endText();
</code>```

To add another line of text underneath I had to repeatedly experiment with the value of y in moveTextPositionByAmount until it wasn't overwriting the previous line.

Is there a more intuitive way to figure out what the coordinates of the next line are?

TIA

答:
add a new line with offset in y axis like this  </p>

```<code>PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA;
content.beginText();
content.setFont(font, 12);
// by default y = 0 pdf text start in the left bottom corner
//  so you may need to put y = 700 or something to see the new line below
content.moveTextPositionByAmount(x, y);
content.drawString("Some text.");
content.newLineAtOffset(0, -15);
content.drawString("some text ");
content.endText();
</code>```

Body:
I've just started using Apache PDFBox and been experimenting with various examples I've found.

However, I haven't been able to find an easy way to move to the next line when adding text.

E.g.

PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA;
content.beginText();
content.setFont(font, 12);
content.moveTextPositionByAmount(x, y);
content.drawString("Some text.");
content.endText();

To add another line of text underneath I had to repeatedly experiment with the value of y in moveTextPositionByAmount until it wasn't overwriting the previous line.

Is there a more intuitive way to figure out what the coordinates of the next line are?

TIA

Body:
add a new line with offset in y axis like this

PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA;
content.beginText();
content.setFont(font, 12);
// by default y = 0 pdf text start in the left bottom corner
//  so you may need to put y = 700 or something to see the new line below
content.moveTextPositionByAmount(x, y);
content.drawString("Some text.");
content.newLineAtOffset(0, -15);
content.drawString("some text ");
content.endText();


问:
Eclipse RCP vs Eclipse PDE
What is difference between a eclipse plugin environment and eclipse rcp plugin?

I am confussed that when you launch any eclipse plugin as eclipse application , it is nothing but you are running a rcp application.

Please help me in correcting both the context.

答:
Eclipse Applications follow the following formula

Eclipse App = Plugins + Platform
Eclipse App = PDE + RCP

Eclipse ide is an eclipse of an Eclipse Applications.

RCP is the bundling platform on top of which ur plugins r installed and executed.

I hope that helps.

Title: Eclipse RCP vs Eclipse PDE


问:
Ruby: how to count the frequencies of the letters
HELP: do a frequency method:  calculate the frequency each letter appears in “str” and assign the output to “letters”. The method should count lower and uppercase as the same letter. but I have the error about NoMethodError: undefined method
Thank you

here is my code

```<code>class MyString
  attr_accessor :str
  attr_reader :letters

  def initialize
    @str = "Hello World!"
    @letters = Hash.new()
  end
  def frequency
    @letters = @str.split(" ").reduce(@letters) { |h, c| h[c] += 1; h}
  end
  def histogram
    #@letters.each{|key,value| puts "#{key} + ':' + value.to_s + '*' * #{value}" }
  end
end
</code>```

The error shows :

```<code> irb(main):009:0> txt1.frequency
NoMethodError: undefined method `+' for nil:NilClass
    from assignment.rb:11:in `block in frequency'
    from assignment.rb:11:in `each'
    from assignment.rb:11:in `reduce'
    from assignment.rb:11:in `frequency'
    from (irb):9
    from /usr/bin/irb:12:in `<main>'
</code>```

答:
When you try to add 1 to a value in the hash that doesn't exist, it tries to add 1 to nil, which isn't allowed. You can change the hash so that the default value 0, not nil.

```<code>@letters = Hash.new(0)
</code>```

Now, your program right now is counting word frequencies, not letter frequencies (split(" ") splits on spaces, not on each character). To split on each character, use the appropriately named each_char method.

```<code>@letters = @str.each_char.reduce(@letters) { |h, c| h[c] += 1; h}
</code>```

Body:
HELP: do a frequency method:  calculate the frequency each letter appears in “str” and assign the output to “letters”. The method should count lower and uppercase as the same letter. but I have the error about NoMethodError: undefined method
Thank you

here is my code

class MyString
  attr_accessor :str
  attr_reader :letters

  def initialize
    @str = "Hello World!"
    @letters = Hash.new()
  end
  def frequency
    @letters = @str.split(" ").reduce(@letters) { |h, c| h[c] += 1; h}
  end
  def histogram
    #@letters.each{|key,value| puts "#{key} + ':' + value.to_s + '*' * #{value}" }
  end
end

The error shows :

 irb(main):009:0> txt1.frequency
NoMethodError: undefined method `+' for nil:NilClass
    from assignment.rb:11:in `block in frequency'
    from assignment.rb:11:in `each'
    from assignment.rb:11:in `reduce'
    from assignment.rb:11:in `frequency'
    from (irb):9
    from /usr/bin/irb:12:in `'

Body:
When you try to add 1 to a value in the hash that doesn't exist, it tries to add 1 to nil, which isn't allowed. You can change the hash so that the default value 0, not nil.

@letters = Hash.new(0)

Now, your program right now is counting word frequencies, not letter frequencies (split(" ") splits on spaces, not on each character). To split on each character, use the appropriately named each_char method.

@letters = @str.each_char.reduce(@letters) { |h, c| h[c] += 1; h}


问:
How to change options when searching in md-autocomplete
How to change options when i am typing in . It is not working properly when I type filter not working  its show all the list i want change list text according to search please help me this.

```<code><md-autocomplete
    ng-disabled="Ctrlmain.isDisabled"
    md-no-cache="Ctrlmain.noCache"
    md-selected-item="Ctrlmain.selectedItem"
    md-search-text="Ctrlmain.campaignname"
    md-selected-item-change="Ctrlmain.filltextbox(item)"
    md-items="item in Ctrlmain.getMatches(Ctrlmain.campaignname)  | unique:'campaign_name'"
    md-item-text="item.campaign_name"
    md-min-length="0"
    placeholder="Pick an Angular repository"
    md-menu-class="autocomplete-custom-template">
        <md-item-template>
            <span class="item-title">
                <span> {{item.campaign_name}} </span>
            </span>
        </md-item-template>
</md-autocomplete>
</code>```

Angular Method

```<code>complete(str){

    var output = [];
    angular.forEach(this.viewData,function(campaignname){
      if(campaignname.campaign_name.toLowerCase().indexOf(str.toLowerCase())>=0){
        output.push(campaignname.campaign_name);

      };
    });
  return output.campaign_name;
}

filltextbox(st){
   return st;
}
</code>```

答:
Returning matches on md-search-text-change doesn't work. Your md-autocomplete is bound to Ctrlmian.viewData. If that is to work, you have to modify the said array at the end of complete function. Besides your code is essentially wrong when you try to return output.campaign_name where output is an array. Or you can try it this way...

```<code><md-autocomplete
    ng-disabled="Ctrlmain.isDisabled"
    md-no-cache="Ctrlmain.noCache"
    md-selected-item="Ctrlmain.selectedItem"
    md-search-text="Ctrlmain.campaignname"
    md-selected-item-change="Ctrlmain.filltextbox(item)"
    md-items="item in Ctrlmain.getMatches(Ctrlmain.campaignname)  | unique:'campaign_name'"
    md-item-text="item.campaign_name"
    md-min-length="0"
    placeholder="Pick an Angular repository"
    md-menu-class="autocomplete-custom-template">
        <md-item-template>
            <span class="item-title">
                <span> {{item.campaign_name}} </span>
            </span>
        </md-item-template>
</md-autocomplete>
</code>```

Notice I've gotten rid of md-search-text-change. I'm using your filter function to dynamically render items for md-autocomplete as below.

```<code>getMatches(str) {
    var output = [];
    angular.forEach(this.viewData,function(campaignname) {
        if(campaignname.campaign_name.toLowerCase().indexOf(str.toLowerCase())>=0) {
            output.push(campaignname);
        };
    });
    return output;
}
</code>```

Body:
How to change options when i am typing in . It is not working properly when I type filter not working  its show all the list i want change list text according to search please help me this.

<md-autocomplete
    ng-disabled="Ctrlmain.isDisabled"
    md-no-cache="Ctrlmain.noCache"
    md-selected-item="Ctrlmain.selectedItem"
    md-search-text="Ctrlmain.campaignname"
    md-selected-item-change="Ctrlmain.filltextbox(item)"
    md-items="item in Ctrlmain.getMatches(Ctrlmain.campaignname)  | unique:'campaign_name'"
    md-item-text="item.campaign_name"
    md-min-length="0"
    placeholder="Pick an Angular repository"
    md-menu-class="autocomplete-custom-template">
        <md-item-template>

                 {{item.campaign_name}}

        </md-item-template>
</md-autocomplete>

Angular Method

complete(str){

    var output = [];
    angular.forEach(this.viewData,function(campaignname){
      if(campaignname.campaign_name.toLowerCase().indexOf(str.toLowerCase())>=0){
        output.push(campaignname.campaign_name);

      };
    });
  return output.campaign_name;
}

filltextbox(st){
   return st;
}

Body:
Returning matches on md-search-text-change doesn't work. Your md-autocomplete is bound to Ctrlmian.viewData. If that is to work, you have to modify the said array at the end of complete function. Besides your code is essentially wrong when you try to return output.campaign_name where output is an array. Or you can try it this way...

<md-autocomplete
    ng-disabled="Ctrlmain.isDisabled"
    md-no-cache="Ctrlmain.noCache"
    md-selected-item="Ctrlmain.selectedItem"
    md-search-text="Ctrlmain.campaignname"
    md-selected-item-change="Ctrlmain.filltextbox(item)"
    md-items="item in Ctrlmain.getMatches(Ctrlmain.campaignname)  | unique:'campaign_name'"
    md-item-text="item.campaign_name"
    md-min-length="0"
    placeholder="Pick an Angular repository"
    md-menu-class="autocomplete-custom-template">
        <md-item-template>
            <span class="item-title">
                <span> {{item.campaign_name}} </span>
            </span>
        </md-item-template>
</md-autocomplete>

Notice I've gotten rid of md-search-text-change. I'm using your filter function to dynamically render items for md-autocomplete as below.

getMatches(str) {
    var output = [];
    angular.forEach(this.viewData,function(campaignname) {
        if(campaignname.campaign_name.toLowerCase().indexOf(str.toLowerCase())>=0) {
            output.push(campaignname);
        };
    });
    return output;
}


问:
What are the steps to share a script with multiple worksheets through gsuite?
What I want to do within my gsuite account:

To (dynamically) associate a script with multiple sheets so I can maintain their common code in one file.  (e.g. populate a custom menu with options that display when that spreadsheet opens.)

What I've tried:

created a script using the script editor at https://script.google.com , but was unable to associate the script with a sheet

loading the externally created script through the script editor's "File > open" option

creating a script directly from a sheet using the script editor option from the sheet's menu but found no option to share it

publishing the script, but it seems like this makes the script accessible to the general public

I've read about container bound scripts, but I find the documentation unclear and am unsure how to proceed.

答:
your first idea was a good one:

created a script using the script editor at https://script.google.com , but was unable to associate the script with a sheet

From a script, you can edit multiple sheets using their IDs. For example:

```<code>// this function edits two sheets at once
function editBothCells() {

  // assigns a variable to a spreadsheet
  var ss1 = SpreadsheetApp.openById("1CMLVG3Wnk4C-Ck0j7YKY_vgZZNj58mip_VRNUdrjpy8");
  var ss2 = SpreadsheetApp.openById("1kxC_0AwCwapVWG5grRNBLSHYhKpcVOHbrXTZdG9fOc4");

  // runs a function on both spreadsheets
  boldenA4(ss1,ss2);
}

// this function takes cell A4 and makes it bold for all arguments
function boldenA4(spreadsheet1, spreadsheet2, and_so_on){

  for(var i = 0; i < arguments.length; i++){
    arguments[i].getSheets()[0]
    .getRange("A4")
    .setValue("hello stackoverflow") // could be any string
    .setFontWeight("bold");
  }
}
</code>```

Below are the links to both sheets and the script:

stackoverflow Test sheet 1  - feel free to edit it

stackoverflow Test sheet 2 - feel free to edit

the script that can edit them - feel free to run it.

Body:
your first idea was a good one:

created a script using the script editor at https://script.google.com , but was unable to associate the script with a sheet

From a script, you can edit multiple sheets using their IDs. For example:

// this function edits two sheets at once
function editBothCells() {

  // assigns a variable to a spreadsheet
  var ss1 = SpreadsheetApp.openById("1CMLVG3Wnk4C-Ck0j7YKY_vgZZNj58mip_VRNUdrjpy8");
  var ss2 = SpreadsheetApp.openById("1kxC_0AwCwapVWG5grRNBLSHYhKpcVOHbrXTZdG9fOc4");

  // runs a function on both spreadsheets
  boldenA4(ss1,ss2);
}

// this function takes cell A4 and makes it bold for all arguments
function boldenA4(spreadsheet1, spreadsheet2, and_so_on){

  for(var i = 0; i < arguments.length; i++){
    arguments[i].getSheets()[0]
    .getRange("A4")
    .setValue("hello stackoverflow") // could be any string
    .setFontWeight("bold");
  }
}

Below are the links to both sheets and the script:

stackoverflow Test sheet 1  - feel free to edit it

stackoverflow Test sheet 2 - feel free to edit

the script that can edit them - feel free to run it.


问:
How to update a child node that contains a specific value in the database
```<code>String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);

            databaseRef
                    .orderByChild("charID")
                    .equalTo(selectedCharacter.getCharID())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Translate the character to a map of its data
                            Map<String,Object> updates = editedCharacter.toMap();
                            // Update ONLY the node with charID = editedCharacter.getCharID()
                            databaseRef.updateChildren(updates);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });
</code>```

So I'm trying to update a character's stats in my firebase database. As you can see:

here

the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.

答:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So your code will need to handle the fact that the snapshot is a list. In the case of Android that means that you loop over snapshot.getChildren():

```<code>databaseRef
    .orderByChild("charID")
    .equalTo(selectedCharacter.getCharID())
    .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child: dataSnapshot.getChildren()) {
                // Translate the character to a map of its data
                Map<String,Object> updates = editedCharacter.toMap();
                // Update ONLY the node with charID = editedCharacter.getCharID()
                child.getRef().updateChildren(updates);
            }
        }
</code>```

Body:
String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);

            databaseRef
                    .orderByChild("charID")
                    .equalTo(selectedCharacter.getCharID())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Translate the character to a map of its data
                            Map<String,Object> updates = editedCharacter.toMap();
                            // Update ONLY the node with charID = editedCharacter.getCharID()
                            databaseRef.updateChildren(updates);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });

So I'm trying to update a character's stats in my firebase database. As you can see:

here

the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.

Body:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So your code will need to handle the fact that the snapshot is a list. In the case of Android that means that you loop over snapshot.getChildren():

databaseRef
    .orderByChild("charID")
    .equalTo(selectedCharacter.getCharID())
    .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child: dataSnapshot.getChildren()) {
                // Translate the character to a map of its data
                Map<String,Object> updates = editedCharacter.toMap();
                // Update ONLY the node with charID = editedCharacter.getCharID()
                child.getRef().updateChildren(updates);
            }
        }


问:
fluidrow layout not as expected
i am trying to build a  simple shiny application with the  following layout, 2X2 layout

Data1   Data2

 Stats1   stats2

```<code>tabBox(title = "Data Review",id= "ttabs", width = 20, height = "420px",
tabPanel("Data",
column(3, dataTableOutput("data1"))
, column(3, verbatimTextOutput("sum1")),
, column(3, offset = 1,dataTableOutput("data2"))
, column(3, offset = 1, verbatimTextOutput("sum2"))
)
</code>```

data 2 and stats2 appear as expected (one below the other), however data1 and stat1 appear side by side. Not sure how to update the code to get the expected result

答:
How about use fluidRow()?

```<code>ui <- fluidPage(
tabBox(title="Data Review", id="ttabs", width=20, height=420,
    tabPanel("Data",
        fluidRow(
            column(6, dataTableOutput("data1")),
            column(6, dataTableOutput("data2")) ),
        fluidRow(
            column(6, verbatimTextOutput("sum1")),
            column(6, verbatimTextOutput("sum2"))  )
    )
)
</code>```

)

I hope this code help you.

Title: fluidrow layout not as expected

Body:
i am trying to build a  simple shiny application with the  following layout, 2X2 layout

Data1   Data2

 Stats1   stats2

tabBox(title = "Data Review",id= "ttabs", width = 20, height = "420px",
tabPanel("Data",
column(3, dataTableOutput("data1"))
, column(3, verbatimTextOutput("sum1")),
, column(3, offset = 1,dataTableOutput("data2"))
, column(3, offset = 1, verbatimTextOutput("sum2"))
)

data 2 and stats2 appear as expected (one below the other), however data1 and stat1 appear side by side. Not sure how to update the code to get the expected result

Body:
How about use fluidRow()?

ui <- fluidPage(
tabBox(title="Data Review", id="ttabs", width=20, height=420,
    tabPanel("Data",
        fluidRow(
            column(6, dataTableOutput("data1")),
            column(6, dataTableOutput("data2")) ),
        fluidRow(
            column(6, verbatimTextOutput("sum1")),
            column(6, verbatimTextOutput("sum2"))  )
    )
)

)

I hope this code help you.


问:
time.sleep function within while loop keeps crashing program, solution or alternative method?
I am trying to make a space invaders game using turtle, and in order to move the bullet up the screen I am trying to update the y coordinate of the bullet every 0.5 seconds. I tried to do this with a while loop and the time.sleep() function, but everytime I try to fire a bullet, the program crashes. Is there any way I can stop it from doing this? Or why is it not working? Is there an equally effective method that will not crash my program? </p>

```<code>import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    bullet = turtle.Turtle()
    bullet.pu()
    bullet.ht()
    bullet.setpos(x, y)
    bullet.pd()
    bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx
    while y <= 300:
        time.sleep(0.5)
        y += 4
    else: y = 0
    bullets += (x,y)

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        frame()
        turtle.update()
        time.sleep(0.05)

main()
</code>```

答:
I would:

```<code>def key_space():
    # simply spawn a new bullet and put it into your bullets list

def advance_bullet(): # call this after paintnig all bullets in frame
    # iterate over all bullets inside bullets, advance the Y position by 3

def frame():
    # add code to paint all bullets inside bullets - and call advance_bullets()
</code>```

In the code that checks for collision with enemies:

```<code># remove a bullet from bullets when its outside your screen (or passed all enemies max y coord) - no need to track that bullet anymore
</code>```

if you ned to advance the bullets slower then your main loops intervall, make a "framespassed" counter and see if framespassed % something == 0 and only then advance your bullets.

Adapted to what you already have

You need to change these parts:

```<code>def frame():
    global bullets
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    # debugging all bullets:
    # print(bullets) # remove this

    for idx in range(0,len(bullets)): # paint ALL bullets in the bullets list
        bulletTurtle = turtle.Turtle()
        b = bullets[idx] # current bullet we are painting
        bulletTurtle.pu()
        bulletTurtle.ht()
        bulletTurtle.setpos(b[0], b[1])
        bulletTurtle.pd()
        bulletTurtle.circle(2)
        b[1] += 13 # quick and dirty approach, move bulltet after painting
                   # to save another complete bullets-foreach-loop

    # quick n dirty bullet removal for out of screen bullets
    # normally I would do this probably in your "check if enemy hit"
    # method as you are going over bullets there as well and can remove
    # them as soon as they passed all enemies
    bullets = [x for x in bullets if x[1] < 500]

def key_space():
    global x
    global y
    global bullets
    bullets.append([userx,-300]) # start a new bullet at current player position
</code>```

Edit:

You might want to take a look at turtle.shape, turtle.size and turtle.stamp - by using a "circle" shape and a size that fits, you might be able to "stamp" this shape down. Advantage: you can simply delete the stamped shape - by its integer-id. I haven*t worked with turtle ever - consider yourself if that would be a way to easily redraw your players position and/or bullets

Body:
I am trying to make a space invaders game using turtle, and in order to move the bullet up the screen I am trying to update the y coordinate of the bullet every 0.5 seconds. I tried to do this with a while loop and the time.sleep() function, but everytime I try to fire a bullet, the program crashes. Is there any way I can stop it from doing this? Or why is it not working? Is there an equally effective method that will not crash my program?

import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    bullet = turtle.Turtle()
    bullet.pu()
    bullet.ht()
    bullet.setpos(x, y)
    bullet.pd()
    bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx
    while y <= 300:
        time.sleep(0.5)
        y += 4
    else: y = 0
    bullets += (x,y)

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        frame()
        turtle.update()
        time.sleep(0.05)

main()

Body:
I would:

def key_space():
    # simply spawn a new bullet and put it into your bullets list

def advance_bullet(): # call this after paintnig all bullets in frame
    # iterate over all bullets inside bullets, advance the Y position by 3

def frame():
    # add code to paint all bullets inside bullets - and call advance_bullets()

In the code that checks for collision with enemies:

# remove a bullet from bullets when its outside your screen (or passed all enemies max y coord) - no need to track that bullet anymore

if you ned to advance the bullets slower then your main loops intervall, make a "framespassed" counter and see if framespassed % something == 0 and only then advance your bullets.

Adapted to what you already have

You need to change these parts:

def frame():
    global bullets
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    # debugging all bullets:
    # print(bullets) # remove this

    for idx in range(0,len(bullets)): # paint ALL bullets in the bullets list
        bulletTurtle = turtle.Turtle()
        b = bullets[idx] # current bullet we are painting
        bulletTurtle.pu()
        bulletTurtle.ht()
        bulletTurtle.setpos(b[0], b[1])
        bulletTurtle.pd()
        bulletTurtle.circle(2)
        b[1] += 13 # quick and dirty approach, move bulltet after painting
                   # to save another complete bullets-foreach-loop

    # quick n dirty bullet removal for out of screen bullets
    # normally I would do this probably in your "check if enemy hit"
    # method as you are going over bullets there as well and can remove
    # them as soon as they passed all enemies
    bullets = [x for x in bullets if x[1] < 500]

def key_space():
    global x
    global y
    global bullets
    bullets.append([userx,-300]) # start a new bullet at current player position

Edit:

You might want to take a look at turtle.shape, turtle.size and turtle.stamp - by using a "circle" shape and a size that fits, you might be able to "stamp" this shape down. Advantage: you can simply delete the stamped shape - by its integer-id. I haven*t worked with turtle ever - consider yourself if that would be a way to easily redraw your players position and/or bullets


问:
When pressed 'Enter', sum the input and clear it
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

```<code><input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
</code>```

My JS:

```<code>input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;
</code>```

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!

答:
Get the value before your clear it.

var input = document.getElementById("input");
var output = document.getElementById("output");
var total = 0;

input.onkeypress = function(e) {
  if (e.keyCode == 13 ||  e.key == 13) {
    total += +input.value;
    output.value = total;
    input.value = "";
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="input">
<p>Uw totaal:</p>
<input type="number" id="output"></code>```

Body:
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

<input type="text" id="input">

Uw totaal:

<input type="text" id="output">

My JS:

input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!

Body:
Get the value before your clear it.

var input = document.getElementById("input");
var output = document.getElementById("output");
var total = 0;

input.onkeypress = function(e) {
  if (e.keyCode == 13 ||  e.key == 13) {
    total += +input.value;
    output.value = total;
    input.value = "";
  }
};

<input type="number" id="input">
<p>Uw totaal:</p>
<input type="number" id="output">


问:
Firebase crashes with Android Instant apps
I am trying to initialize Firebase(11.2.0) in an Android instant app using:

```<code>FirebaseApp.initializeApp(this);
</code>```

But it throws following exception stating jobscheduler is not supported:

```<code>      E/FirebaseApp: Firebase API initialization failure.
  java.lang.reflect.InvocationTargetException
      at java.lang.reflect.Method.invoke(Native Method)
      at com.google.firebase.FirebaseApp.zza(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.hello.world.myapp.provider.MyApplication.onCreate(MyApplication.java:93)
      at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5403)
      at android.app.ActivityThread.-wrap2(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
   Caused by: java.lang.SecurityException: Service: jobscheduler is not supported.
      at android.os.Parcel.readException(Parcel.java:1684)
      at android.os.Parcel.readException(Parcel.java:1637)
      at android.app.job.IJobScheduler$Stub$Proxy.cancel(IJobScheduler.java:202)
      at android.app.JobSchedulerImpl.cancel(JobSchedulerImpl.java:60)
      at com.google.android.gms.internal.zzcfj.zzazu(Unknown Source)
      at com.google.android.gms.internal.zzcfj.zzuh(Unknown Source)
      at com.google.android.gms.internal.zzcdm.initialize(Unknown Source)
</code>```

I followed integration instructions given on android developer docs here.

答:
With reference to Google issue tracker JobScheduler should be fixed now

The recommended approach would be to use the framework’s JobScheduler for API >= 21 since Instant Apps are only supported down to 21 anyways, and use Firebase JobDispatcher for the installed app for below 21.

example https://github.com/firebase/firebase-jobdispatcher-android

If any issue persists, please report at Google issue tracker they will re-open to examine.

Body:
I am trying to initialize Firebase(11.2.0) in an Android instant app using:

FirebaseApp.initializeApp(this);

But it throws following exception stating jobscheduler is not supported:

      E/FirebaseApp: Firebase API initialization failure.
  java.lang.reflect.InvocationTargetException
      at java.lang.reflect.Method.invoke(Native Method)
      at com.google.firebase.FirebaseApp.zza(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
      at com.hello.world.myapp.provider.MyApplication.onCreate(MyApplication.java:93)
      at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5403)
      at android.app.ActivityThread.-wrap2(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
   Caused by: java.lang.SecurityException: Service: jobscheduler is not supported.
      at android.os.Parcel.readException(Parcel.java:1684)
      at android.os.Parcel.readException(Parcel.java:1637)
      at android.app.job.IJobScheduler$Stub$Proxy.cancel(IJobScheduler.java:202)
      at android.app.JobSchedulerImpl.cancel(JobSchedulerImpl.java:60)
      at com.google.android.gms.internal.zzcfj.zzazu(Unknown Source)
      at com.google.android.gms.internal.zzcfj.zzuh(Unknown Source)
      at com.google.android.gms.internal.zzcdm.initialize(Unknown Source)

I followed integration instructions given on android developer docs here.


问:
Problem while running SQL Management Studio 2008
I install the MS SQL Management Studio 2008, the installation was successfull but when i run the Management Studio and connect to any Server (diffrent Servers in diffrent locations) I got following error

************** Ausnahmetext **************
  System.TypeLoadException: Der Typ "Microsoft.SqlServer.Management.Sdk.Sfc.ISfcDomainLite" in der Assembly "Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" konnte nicht geladen werden.
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItem.get_State()
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.LazyTreeView.AdjustStateHealthStatus(TreeNode inputNode)
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.LazyTreeView.AddIconToImageMap(TreeNode node)
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ExplorerHierarchyNode.LoadNodeValuesFromItem(INavigableItem containedItem)
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ExplorerHierarchyNode.AddedToTree()
     bei Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.LazyTreeView.AddNodesInternal(TreeNode source, TreeNode[] nodesToAdd)

Any suggestions to solve this Problem? The System is Win7x64.

Regards
Rene

答:
Sorry for that late answer. I had this problem, too. And I could solve it - not by reinstallation of the OS :-)

Problem description:

The problem occured, because I made an installation of "sql server express 2008 R2". Don't ask why, I thought it was a good idea. But SQL Management Server 2008 R2 did'nt worked. So I uninstalled the whole R2-SQL Server and installed a early "SQL Server 2008 express advanced edtion". SQL Server worked, but Management Studio throught that exception (s.a.).

The Solution:

The Problem is, the there are rests of the SQL Server R2 installation. Some assemblies are newer.
Note: for the following solution I will not garantee, that it works nor that your system will work properly after it.

 USE IT ON YOUR OWN RISK!

So do the following steps:

Uninstall all "Microsoft SQL Server 2008" entries with the standard uninstall-page (System > Programs > uninstallation, in german: "Systemsteuerung > Programme > Programm deinstallieren").
Also uninstall the entry "Support for SQL Server Setup" (german: "Unterstützung für SQL Server Setup")

Now, if you - like me - have problems to uninstall the SQL Server entries, then download the microsoft tool Windows Installer clean up. After starting it, you will get a list of the setups. These setups can be cleaned up with this tool.

So, we have to get rid of the R2 assemblies. Open explorer and navigate to "C:\Windows\assembly". Find the entries starting with "Microsoft.SqlServer". Select them all and press "delete". If there comes a message, that not all could be deleted, then you missed an installation in step 2!

Now you can install "SQL Server 2008 express". I used the x86 installation without ServicePack.

ContentLicense: CC BY-SA 2.5


答:
Give this a shot -

 var total = 0;
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(e) {
  total = total + input.value * 1;
  if(e.keyCode == 13) {
   input.value = "";
 }
  output.value = total;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output"></code>```

And hey, welcome to JS!

Title: When pressed 'Enter', sum the input and clear it

Body:
Give this a shot -

 var total = 0;
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(e) {
  total = total + input.value * 1;
  if(e.keyCode == 13) {
   input.value = "";
 }
  output.value = total;
};

<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">

And hey, welcome to JS!


答:
you clear your input field too early.

```<code> var number = 0
 function ceckKey(e) {
        // check for enter: e.key is for Firefox
        // if true, make input empty
        if (e.keyCode == 13 || e.key == 13) {
            number += input.value;
            input.value = "";
        }
        return number;
    }

    document.getElementById("output").value = number;
</code>```

note that your number variable may not be declared inside of the checkKey function. Greetings

Body:
you clear your input field too early.

 var number = 0
 function ceckKey(e) {
        // check for enter: e.key is for Firefox
        // if true, make input empty
        if (e.keyCode == 13 || e.key == 13) {
            number += input.value;
            input.value = "";
        }
        return number;
    }

    document.getElementById("output").value = number;

note that your number variable may not be declared inside of the checkKey function. Greetings


问:
Why does Node.js HTTP server not respond to a request from Python?
I've got a working HTTP node.js server.

I then created a program on python that uses the socket module to connect to the above server

Please for the time being do not mind the try and except statements. The code's connectTO() function simply connects to a server like any other code, with the exception that it handles some errors. Then the program send the message "hello". Next in the while loop it repeatedly waits for an answer and when it receives one, it prints it.

When I connect to the Node.js http server from python, I do get the message:

```<code>"You have just succesfully connected to the node.js server"
</code>```

Which if you look at my code means that the s.connect(()) command was successful. My problem is that when a request is send to the server, it's supposed to output a message back, but it doesn't.

I also tried sending a message to the server, in which case the server sends back the following message:

HTTP/1.1 400 Bad Request

So why is the server not responding to the requests? Why is it rejecting them?

Python Client:

```<code>from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, socket, time, sys

s = socket.socket(AF_INET,SOCK_STREAM)

def connectTO(host,port):
    connect = False
    count = 0
    totalCount = 0
    while connect!= True:
        try:
            s.connect((host,port))
            connect = True
            print("You have just succesfully connected to the node.js server")
        except OSError:
            count += 1
            totalCount += 1
            if totalCount == 40 and count == 4:
                print("Error: 404. Connection failed repeatedly")
                sys.exit(0)
            elif count == 4:
                print("Connection failed, retrying...")
                count = 0
            else:
                pass

connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777)
message = "hello"
s.send(message.encode("utf-8"))

while True:
    try:
        data, addr = s.recvfrom(1024)
        if data == "":
            pass
        else:
            print(data.decode())
    except ConnectionResetError:
        print("it seems like we can't reach the server anymore..")
        print("This could be due to a change in your internet connection or the server.")
    s.close()
</code>```

Node.js HTTP server:

```<code>function onRequest(req, res) {
    var postData = "";
    var pathname = url.parse(req.url).pathname;

    //Inform console of event recievent
    console.log("Request for "+pathanme+" received.");

    //Set the encoding to equivelant one used in html
    req.setEncoding("utf8");

    //add a listener for whenever info comes in and output full result
    req.addListener("data", function(postDataChunk) {
        postData += postDataChunk;
        console.log("Received POST data chunk: '"+postDataChunk+"'");
    });

    req.addListener("end", function() {
        route(handle, pathname, res, frontPage, postData);
    });

};

http.createServer(onRequest).listen(port,ip);
console.log("Server has started.");
</code>```

Some of my Research

I should also note that after some research, it seems that an HTTP server accepts HTTP requests, but I don't understand most of what's on Wikipedia. Is this the reason why the server is not responding? And how do I fix that while still using the socket module.

Also there are a lot of similar questions on Stack Overflow, but none help me solve my problem. One of them describes my issue, and the only answer is about "handshakes". Google is also pointless here, but from what I understand it is simply a reaction between the server and the client which defines what the protocol will be. Could this be what I'm missing, and how do I implement it?

Some of these questions also use modules that I'm not ready to use yet like websocket. Either that or they describe a way in which the server connects to the client, which can be done by directly calling python code or connecting to it from Node.js express. I want the client to be the one connecting to an HTTP server, by the means of the socket module in python. For the sake of future visitors who are looking for something like this, here are some of these question:

How to connect node.js app with python script?

Python Client to nodeJS Server with Socket.IO

Python connecting to an HTTP server

A blog that also does something similar to what is described above: https://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/

Here is an answer that doesn't actually seem that obvious, but also solves the issue with only the relevant code. People who don't yet no much about servers in general will have probably missed it:
how to use socket fetch webpage use python

答:
You will need to construct an HTTP request.

Example: GET / HTTP/1.1\n\n

Try this:

```<code>from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, socket, time, sys

s = socket.socket(AF_INET,SOCK_STREAM)

def connectTO(host,port):
    connect = False
    count = 0
    totalCount = 0
    while connect!= True:
        try:
            s.connect((host,port))
            connect = True
            print("You have just succesfully connected to the node.js server")
        except OSError:
            count += 1
            totalCount += 1
            if totalCount == 40 and count == 4:
                print("Error: 404. Connection failed repeatedly")
                sys.exit(0)
            elif count == 4:
                print("Connection failed, retrying...")
                count = 0
            else:
                pass

connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777)
message = "GET / HTTP/1.1\n\n"
s.send(message.encode("utf-8"))

while True:
    try:
        data, addr = s.recvfrom(1024)
        if data == "":
            pass
        else:
            print(data.decode())
    except ConnectionResetError:
        print("it seems like we can't reach the server anymore..")
        print("This could be due to a change in your internet connection or the server.")
    s.close()
</code>```

Read this to learn more about HTTP.

Now, I would recommend using this python lib to do what you're trying to do. It makes things much easier. However, if you are 100% set on using raw sockets, then you should make the node server use raw sockets as well. (Assuming you will only be connecting via python). Here is an excellent tutorial

Body:
I've got a working HTTP node.js server.

I then created a program on python that uses the socket module to connect to the above server

Please for the time being do not mind the try and except statements. The code's connectTO() function simply connects to a server like any other code, with the exception that it handles some errors. Then the program send the message "hello". Next in the while loop it repeatedly waits for an answer and when it receives one, it prints it.

When I connect to the Node.js http server from python, I do get the message:

"You have just succesfully connected to the node.js server"

Which if you look at my code means that the s.connect(()) command was successful. My problem is that when a request is send to the server, it's supposed to output a message back, but it doesn't.

I also tried sending a message to the server, in which case the server sends back the following message:

HTTP/1.1 400 Bad Request

So why is the server not responding to the requests? Why is it rejecting them?

Python Client:

from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, socket, time, sys

s = socket.socket(AF_INET,SOCK_STREAM)

def connectTO(host,port):
    connect = False
    count = 0
    totalCount = 0
    while connect!= True:
        try:
            s.connect((host,port))
            connect = True
            print("You have just succesfully connected to the node.js server")
        except OSError:
            count += 1
            totalCount += 1
            if totalCount == 40 and count == 4:
                print("Error: 404. Connection failed repeatedly")
                sys.exit(0)
            elif count == 4:
                print("Connection failed, retrying...")
                count = 0
            else:
                pass

connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777)
message = "hello"
s.send(message.encode("utf-8"))

while True:
    try:
        data, addr = s.recvfrom(1024)
        if data == "":
            pass
        else:
            print(data.decode())
    except ConnectionResetError:
        print("it seems like we can't reach the server anymore..")
        print("This could be due to a change in your internet connection or the server.")
    s.close()

Node.js HTTP server:

function onRequest(req, res) {
    var postData = "";
    var pathname = url.parse(req.url).pathname;

    //Inform console of event recievent
    console.log("Request for "+pathanme+" received.");

    //Set the encoding to equivelant one used in html
    req.setEncoding("utf8");

    //add a listener for whenever info comes in and output full result
    req.addListener("data", function(postDataChunk) {
        postData += postDataChunk;
        console.log("Received POST data chunk: '"+postDataChunk+"'");
    });

    req.addListener("end", function() {
        route(handle, pathname, res, frontPage, postData);
    });

};

http.createServer(onRequest).listen(port,ip);
console.log("Server has started.");

Some of my Research

I should also note that after some research, it seems that an HTTP server accepts HTTP requests, but I don't understand most of what's on Wikipedia. Is this the reason why the server is not responding? And how do I fix that while still using the socket module.

Also there are a lot of similar questions on Stack Overflow, but none help me solve my problem. One of them describes my issue, and the only answer is about "handshakes". Google is also pointless here, but from what I understand it is simply a reaction between the server and the client which defines what the protocol will be. Could this be what I'm missing, and how do I implement it?

Some of these questions also use modules that I'm not ready to use yet like websocket. Either that or they describe a way in which the server connects to the client, which can be done by directly calling python code or connecting to it from Node.js express. I want the client to be the one connecting to an HTTP server, by the means of the socket module in python. For the sake of future visitors who are looking for something like this, here are some of these question:

How to connect node.js app with python script?

Python Client to nodeJS Server with Socket.IO

Python connecting to an HTTP server

A blog that also does something similar to what is described above: https://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/

Here is an answer that doesn't actually seem that obvious, but also solves the issue with only the relevant code. People who don't yet no much about servers in general will have probably missed it:
how to use socket fetch webpage use python

Body:
You will need to construct an HTTP request.

Example: GET / HTTP/1.1\n\n

Try this:

from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, socket, time, sys

s = socket.socket(AF_INET,SOCK_STREAM)

def connectTO(host,port):
    connect = False
    count = 0
    totalCount = 0
    while connect!= True:
        try:
            s.connect((host,port))
            connect = True
            print("You have just succesfully connected to the node.js server")
        except OSError:
            count += 1
            totalCount += 1
            if totalCount == 40 and count == 4:
                print("Error: 404. Connection failed repeatedly")
                sys.exit(0)
            elif count == 4:
                print("Connection failed, retrying...")
                count = 0
            else:
                pass

connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777)
message = "GET / HTTP/1.1\n\n"
s.send(message.encode("utf-8"))

while True:
    try:
        data, addr = s.recvfrom(1024)
        if data == "":
            pass
        else:
            print(data.decode())
    except ConnectionResetError:
        print("it seems like we can't reach the server anymore..")
        print("This could be due to a change in your internet connection or the server.")
    s.close()

Read this to learn more about HTTP.

Now, I would recommend using this python lib to do what you're trying to do. It makes things much easier. However, if you are 100% set on using raw sockets, then you should make the node server use raw sockets as well. (Assuming you will only be connecting via python). Here is an excellent tutorial


问:
Django FileField update writes to disk but not to database
I am trying to update a FileField to an image of something downloaded from internet. I have the following code

# update profile pic
pic_url = fb_login_data['picture']['data']['url']
pic_url_parsed = urllib.parse.urlparse(pic_url)
image_req = urllib.request.urlretrieve(pic_url)
with open(image_req[0], 'rb') as f:
    user.profile_image.save(os.path.basename(pic_url_parsed.path),
                                        File(f))```

The behavior is pretty strange: the image is saved to disk properly in the MEDIA_ROOT directory where it should be, but in database, the field remains empty. I also tried calling user.save() manually.

Do you have any ideas why is that happening and how can I update properly the FileField?

using Django 2.0 and Python 3.6.3

答: I just managed to make it work. All I had to do is to add a default value for the FileField to point to an already existing file. But still I am not sure why this is happening.

Body:
I am trying to update a FileField to an image of something downloaded from internet. I have the following code

# update profile pic
pic_url = fb_login_data['picture']['data']['url']
pic_url_parsed = urllib.parse.urlparse(pic_url)
image_req = urllib.request.urlretrieve(pic_url)
with open(image_req[0], 'rb') as f:
    user.profile_image.save(os.path.basename(pic_url_parsed.path),
                                        File(f))

The behavior is pretty strange: the image is saved to disk properly in the MEDIA_ROOT directory where it should be, but in database, the field remains empty. I also tried calling user.save() manually.

Do you have any ideas why is that happening and how can I update properly the FileField?

using Django 2.0 and Python 3.6.3