问:
Google maps JS API v3: get markers in circle with containsLocation() doesn't work - why?
I'm trying to get all markers within a given radius (google.maps.Circle) by using google.maps.geometry.poly.containsLocation as recommended here, but I get an error: TypeError: e is undefined.

Snippet:

```<code>// ...
if (google.maps.geometry.poly.containsLocation(randomMarkers[i].marker.getPosition(), searchArea)) {
    console.log('=> is in searchArea');
} else {
    console.log('=> is NOT in searchArea');
}
// ...
</code>```

Full code:

```<code><!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
  }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map,
    searchArea,
    searchAreaMarker,
    searchAreaRadius = 1000, // metres
    startLat = 40.782827,
    startLng = -73.966167
;

function init() {
    var startLatLng = new google.maps.LatLng(startLat, startLng);

    map = new google.maps.Map(document.getElementById('map-canvas'), {
        center: startLatLng,
        zoom: 12
    });

    searchArea = new google.maps.Circle({
        strokeColor: '#FF0000',
        strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.2,
        map: map,
        center: startLatLng,
        radius: searchAreaRadius
    });

    searchAreaMarker = new google.maps.Marker({
        position: startLatLng,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        title: 'searchAreaMarker'
    });

    var randomMarkers = [
        { title: 'Marker 1', latLng: new google.maps.LatLng(40.770088, -73.971146) },
        { title: 'Marker 2', latLng: new google.maps.LatLng(40.782048, -73.972691) },
        { title: 'Marker 3', latLng: new google.maps.LatLng(40.769048, -73.987797) },
        { title: 'Marker 4', latLng: new google.maps.LatLng(40.773858, -73.956211) },
        { title: 'Marker 5', latLng: new google.maps.LatLng(40.800372, -73.952091) },
        { title: 'Marker 6', latLng: new google.maps.LatLng(40.804661, -73.939388) }
    ];

    for (var i = 0; i < randomMarkers.length; i++) {
        randomMarkers[i].marker = new google.maps.Marker({
            position: randomMarkers[i].latLng,
            map: map,
            title: randomMarkers[i].title
        });
    }

    google.maps.event.addListener(searchAreaMarker, 'dragend', function(e) {
        startLatLng = e.latLng;

        searchArea.setOptions({
            center: startLatLng
        });

        map.panTo(searchAreaMarker.getPosition());

        // find markers in area
        for (var i = 0; i < randomMarkers.length; i++) {
            console.log('Marker: ' + randomMarkers[i].marker.title + ', position: ' + randomMarkers[i].marker.getPosition());

            // ---------- Here comes the error:
            // TypeError: e is undefined
            if (google.maps.geometry.poly.containsLocation(randomMarkers[i].marker.getPosition(), searchArea)) {
                console.log('=> is in searchArea');
            } else {
                console.log('=> is NOT in searchArea');
            }
        }
    });
}

google.maps.event.addDomListener(window, 'load', init);
</script>
</code>```

答:
The solution suggested by @Sumuray will create points also outside of the circle, but still in the bounds (square/rectangle) of the circle.

using the method he suggested:

// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')) {

  // Coordinates to center the map
  var myLatlng = new google.maps.LatLng(52.525595, 13.393085);

  // Other options for the map, pretty much selfexplanatory
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // Attach a map to the DOM Element, with the defined settings
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  var marker = new google.maps.Marker({
    map: map,
    position: myLatlng
  });
  var circle = new google.maps.Circle({
    map: map,
    radius: 1000,
    fillColor: '#AA0000',
    fillOpacity: 0.15,
    strokeWeight: 0.9,
    position: myLatlng
  });
  circle.bindTo('center', marker, 'position');

  var circleBounds = circle.getBounds();
  for (var i = 0; i < 50; i++) {
    var marker = generateMarkerInBoundries(circleBounds);
    marker.setMap(map);
  }

  function generateMarkerInBoundries(boundries) {
    var marker = new google.maps.Marker();
    marker.setPosition(new google.maps.LatLng(0, 0));
    while (!boundries.contains(marker.position)) {
      var
        ne = boundries.getNorthEast(),
        sw = boundries.getSouthWest(),
        lat = randomFloat(ne.lat(), sw.lat()),
        lng = randomFloat(ne.lng(), sw.lng());
      marker.setPosition(new google.maps.LatLng(lat, lng))
    }
    return marker;
  }

  function randomFloat(min, max) {
    return Math.random() * (max - min) + min;
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map-canvas {
  height: 500px;
  width: 500px;
  border: 3px solid black;
}</code>```

```
</div>
</div>
</p>

<p>You can clearly see that some of the markers are outside of the circle, but within the bounding box of the circle.</p>

<p>To fix the issue, you could use the geometry library and add a method to check if the point is within the circle's radius</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')) {

  // Coordinates to center the map
  var myLatlng = new google.maps.LatLng(52.525595, 13.393085);

  // Other options for the map, pretty much selfexplanatory
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // Attach a map to the DOM Element, with the defined settings
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  var marker = new google.maps.Marker({
    map: map,
    position: myLatlng
  });
  var circle = new google.maps.Circle({
    map: map,
    radius: 1000,
    fillColor: '#AA0000',
    fillOpacity: 0.15,
    strokeWeight: 0.9,
    position: myLatlng
  });
  circle.bindTo('center', marker, 'position');

  var circleBounds = circle.getBounds();
  for (var i = 0; i < 50; i++) {
    var marker = generateMarkerInCircleRadius(circleBounds);
    marker.setMap(map);
  }

  function generateMarkerInCircleRadius(boundries) {
    var marker = new google.maps.Marker();
    marker.setPosition(new google.maps.LatLng(0, 0));
    while (!isMarkerInRadius(marker, circle)) {
      var
        ne = boundries.getNorthEast(),
        sw = boundries.getSouthWest(),
        lat = randomFloat(ne.lat(), sw.lat()),
        lng = randomFloat(ne.lng(), sw.lng());
      marker.setPosition(new google.maps.LatLng(lat, lng))
    }
    return marker;
  }

  function randomFloat(min, max) {
    return Math.random() * (max - min) + min;
  }

  function isMarkerInRadius(marker, circle) {
    return google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), circle.getCenter()) <= circle.getRadius();
  }
}</code>```

#map-canvas {
  height: 500px;
  width: 500px;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=false" type="text/javascript"></script></code>```

Body:
I'm trying to get all markers within a given radius (google.maps.Circle) by using google.maps.geometry.poly.containsLocation as recommended here, but I get an error: TypeError: e is undefined.

Snippet:

// ...
if (google.maps.geometry.poly.containsLocation(randomMarkers[i].marker.getPosition(), searchArea)) {
    console.log('=> is in searchArea');
} else {
    console.log('=> is NOT in searchArea');
}
// ...

Full code:

<!DOCTYPE html>

<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">

Body:
The solution suggested by @Sumuray will create points also outside of the circle, but still in the bounds (square/rectangle) of the circle.

using the method he suggested:

// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')) {

  // Coordinates to center the map
  var myLatlng = new google.maps.LatLng(52.525595, 13.393085);

  // Other options for the map, pretty much selfexplanatory
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // Attach a map to the DOM Element, with the defined settings
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  var marker = new google.maps.Marker({
    map: map,
    position: myLatlng
  });
  var circle = new google.maps.Circle({
    map: map,
    radius: 1000,
    fillColor: '#AA0000',
    fillOpacity: 0.15,
    strokeWeight: 0.9,
    position: myLatlng
  });
  circle.bindTo('center', marker, 'position');

  var circleBounds = circle.getBounds();
  for (var i = 0; i < 50; i++) {
    var marker = generateMarkerInBoundries(circleBounds);
    marker.setMap(map);
  }

  function generateMarkerInBoundries(boundries) {
    var marker = new google.maps.Marker();
    marker.setPosition(new google.maps.LatLng(0, 0));
    while (!boundries.contains(marker.position)) {
      var
        ne = boundries.getNorthEast(),
        sw = boundries.getSouthWest(),
        lat = randomFloat(ne.lat(), sw.lat()),
        lng = randomFloat(ne.lng(), sw.lng());
      marker.setPosition(new google.maps.LatLng(lat, lng))
    }
    return marker;
  }

  function randomFloat(min, max) {
    return Math.random() * (max - min) + min;
  }

}

#map-canvas {
  height: 500px;
  width: 500px;
  border: 3px solid black;
}

<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>

You can clearly see that some of the markers are outside of the circle, but within the bounding box of the circle.

To fix the issue, you could use the geometry library and add a method to check if the point is within the circle's radius

// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')) {

  // Coordinates to center the map
  var myLatlng = new google.maps.LatLng(52.525595, 13.393085);

  // Other options for the map, pretty much selfexplanatory
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // Attach a map to the DOM Element, with the defined settings
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  var marker = new google.maps.Marker({
    map: map,
    position: myLatlng
  });
  var circle = new google.maps.Circle({
    map: map,
    radius: 1000,
    fillColor: '#AA0000',
    fillOpacity: 0.15,
    strokeWeight: 0.9,
    position: myLatlng
  });
  circle.bindTo('center', marker, 'position');

  var circleBounds = circle.getBounds();
  for (var i = 0; i < 50; i++) {
    var marker = generateMarkerInCircleRadius(circleBounds);
    marker.setMap(map);
  }

  function generateMarkerInCircleRadius(boundries) {
    var marker = new google.maps.Marker();
    marker.setPosition(new google.maps.LatLng(0, 0));
    while (!isMarkerInRadius(marker, circle)) {
      var
        ne = boundries.getNorthEast(),
        sw = boundries.getSouthWest(),
        lat = randomFloat(ne.lat(), sw.lat()),
        lng = randomFloat(ne.lng(), sw.lng());
      marker.setPosition(new google.maps.LatLng(lat, lng))
    }
    return marker;
  }

  function randomFloat(min, max) {
    return Math.random() * (max - min) + min;
  }

  function isMarkerInRadius(marker, circle) {
    return google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), circle.getCenter()) <= circle.getRadius();
  }
}

#map-canvas {
  height: 500px;
  width: 500px;
  border: 3px solid black;
}

<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=false" type="text/javascript"></script>


来源: stackexchange

问:
Error Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] while saving timestamp into databse
```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
String DateToStoreInDataBase= sdf.format(obj1.getSomeDate().toGregorianCalendar().getTime());
System.out.println(emprSubDte);

Timestamp ts = Timestamp.valueOf(emprSubDte);

preparedStatement.setTimestamp(72,ts);
</code>```

sysout of DateToStoreInDataBase is = " 2014-19-13 12:19:59 PM EDT" when i am trying to save this result into database in am getting error Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff].

I have the same format but still i am reciving the error.

答: check if there is incompatible setter or getter , either form your database model side , view pages , beans to xhtml mapping. I found date value for float and fixed it.

ContentLicense: CC BY-SA 3.0

Body:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
String DateToStoreInDataBase= sdf.format(obj1.getSomeDate().toGregorianCalendar().getTime());
System.out.println(emprSubDte);

Timestamp ts = Timestamp.valueOf(emprSubDte);

preparedStatement.setTimestamp(72,ts);

sysout of DateToStoreInDataBase is = " 2014-19-13 12:19:59 PM EDT" when i am trying to save this result into database in am getting error Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff].

I have the same format but still i am reciving the error.


问:
Selenium IDE rollup rule with gotoIf and label
Ok so I'm using the rollup rule in a userextension and for some reason Selenium will keep saying my labels for my gotoIF don't exist. Does anyone has any idea why or how I can fix this problem? The language is JS (JavaScript)

```<code>var manager = new RollupManager();

manager.addRollupRule({
name: 'FRLanguageCheck'
 , description: 'Check the language to make sure its in french'
 , args: [
 ], commandMatchers: [
 ]
 , getExpandedCommands: function(args) {
 var commands = [];

commands.push({
 command: 'storeTextPresent'
 , target: 'English'
 , value: 'LanguageCheck'
 });
 commands.push({
 command: 'gotoIf'
 , target: '${LanguageCheck}==false'
 , value: 'StepWithWrongLanguage'
 });
commands.push({
 command: 'gotoIf'
 , target: '${LanguageCheck}==true'
 , value: 'StepWithRightLanguage'
 });
 commands.push({
 command: 'label'
 , target: 'StepWithWrongLanguage'
 , value: ''
 });
commands.push({
 command: 'click'
 , target: 'TestLanguageChangeToFrench failed. The site was not in French.'
 , value: ''
 });
 commands.push({
 command: 'label'
 , target: 'StepWithRightLanguage'
 , value: ''
 });
 return commands;
 }
});
</code>```

this is the error messages I get from Selenium

```<code>[error] [selblocks] Error @1: [rollup|FRLanguageCheck] Target label 'StepWithRightLanguage' is not found.
[warn] [selblocks] __Stack Trace__
[error] Unexpected Exception: Error: @1: [rollup|FRLanguageCheck] Target label 'StepWithRightLanguage' is not found..
</code>```

答:
Looking for a solution to this problem I also had, I landed on this blog entry:

http://lance.bio/2017/04/18/selenium-ide-rollups-with-arguments/

and its author (Lance Cleveland) kindly answered my question about using label in rollups (see the comments section). Briefly, in the words of Lance, the problem is this:

You cannot use some of the custom commands in the rollups. It has to
  do with how the JavaScript is loaded for the custom commands (those
  are JavaScript as well) and the scope of the variables commands like
  labels / goto have set.

However, since rollups are JavaScript anonymous functions you can use
  any JavaScript trickery you’d like to build the rollup. You can
  simulate your own gotoIf commands using standard JavaScript if
  commands. Any stored values are in the storedVars array.

I hope this helps you.

Body:
Ok so I'm using the rollup rule in a userextension and for some reason Selenium will keep saying my labels for my gotoIF don't exist. Does anyone has any idea why or how I can fix this problem? The language is JS (JavaScript)

var manager = new RollupManager();

manager.addRollupRule({
name: 'FRLanguageCheck'
 , description: 'Check the language to make sure its in french'
 , args: [
 ], commandMatchers: [
 ]
 , getExpandedCommands: function(args) {
 var commands = [];

commands.push({
 command: 'storeTextPresent'
 , target: 'English'
 , value: 'LanguageCheck'
 });
 commands.push({
 command: 'gotoIf'
 , target: '${LanguageCheck}==false'
 , value: 'StepWithWrongLanguage'
 });
commands.push({
 command: 'gotoIf'
 , target: '${LanguageCheck}==true'
 , value: 'StepWithRightLanguage'
 });
 commands.push({
 command: 'label'
 , target: 'StepWithWrongLanguage'
 , value: ''
 });
commands.push({
 command: 'click'
 , target: 'TestLanguageChangeToFrench failed. The site was not in French.'
 , value: ''
 });
 commands.push({
 command: 'label'
 , target: 'StepWithRightLanguage'
 , value: ''
 });
 return commands;
 }
});

this is the error messages I get from Selenium

[error] [selblocks] Error @1: [rollup|FRLanguageCheck] Target label 'StepWithRightLanguage' is not found.
[warn] [selblocks] __Stack Trace__
[error] Unexpected Exception: Error: @1: [rollup|FRLanguageCheck] Target label 'StepWithRightLanguage' is not found..


问:
Error when running if function on mysql results
I'm trying to set permissions in a MySQL table, But i get the error:

```<code>Warning: mysqli::query() expects parameter 1 to be string, object given in
/public/sites/staffpaneel.mc-wonderland.nl/index.php on line 656

Catchable fatal error: Object of class mysqli_result could not be converted
to string in /public/sites/staffpaneel.mc-wonderland.nl/index.php on line 679
</code>```

Does anyone has i fix for this, I've tried a lot of things but nothing worked

```<code>    <?php
    //Perms
    $PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'");
    $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);

if ($conn->query($PermissiesUitlezen) === TRUE) {
    if ($sqlDataPermissies['AccountMakenMag'] == 1) {
        AccountMakenMag();
    }
    if ($sqlDataPermissies['AccountsMag'] == 1) {
        AccountsMag();
    }
    if ($sqlDataPermissies['MeldingMakenMag'] == 1) {
        MeldingMakenMag();
    }
    if ($sqlDataPermissies['RankAanmakenMag'] == 1) {
        RankAanmakenMag();
    }
    if ($sqlDataPermissies['RanksMag'] == 1) {
        RanksMag();
    }
    if ($sqlDataPermissies['StoringMakenMag'] == 1) {
        StoringMakenMag();
    }
    if ($sqlDataPermissies['StoringenMag'] == 1) {
        StoringenMag();
    }
} else {
    echo "Fout: " . $PermissiesUitlezen . "<br>" . $conn->error;
}
    ?>
</code>```

答:
The problem is that $PermissiesUitlezen hold the result of a mysqli_query() call and in the if you use this as a parameter of another mysqli_query() call. This does not make any sense.

Actually, had you read the manual on mysqli_query() on php.net, you would know how to properly check for errors:

```<code> if ($PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID = '".$sqlDataIngelogd['RankID']."'")) {
     $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);
     ...
</code>```

Note, that I also corrected the sql statement (replaced ° with = . But pls also note that you should use prepared statements if you have parameters in your sql query.

Body:
I'm trying to set permissions in a MySQL table, But i get the error:

Warning: mysqli::query() expects parameter 1 to be string, object given in
/public/sites/staffpaneel.mc-wonderland.nl/index.php on line 656

Catchable fatal error: Object of class mysqli_result could not be converted
to string in /public/sites/staffpaneel.mc-wonderland.nl/index.php on line 679

Does anyone has i fix for this, I've tried a lot of things but nothing worked

    <?php
    //Perms
    $PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'");
    $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);

if ($conn->query($PermissiesUitlezen) === TRUE) {
    if ($sqlDataPermissies['AccountMakenMag'] == 1) {
        AccountMakenMag();
    }
    if ($sqlDataPermissies['AccountsMag'] == 1) {
        AccountsMag();
    }
    if ($sqlDataPermissies['MeldingMakenMag'] == 1) {
        MeldingMakenMag();
    }
    if ($sqlDataPermissies['RankAanmakenMag'] == 1) {
        RankAanmakenMag();
    }
    if ($sqlDataPermissies['RanksMag'] == 1) {
        RanksMag();
    }
    if ($sqlDataPermissies['StoringMakenMag'] == 1) {
        StoringMakenMag();
    }
    if ($sqlDataPermissies['StoringenMag'] == 1) {
        StoringenMag();
    }
} else {
    echo "Fout: " . $PermissiesUitlezen . "
" . $conn->error;
}
    ?>

Body:
The problem is that $PermissiesUitlezen hold the result of a mysqli_query() call and in the if you use this as a parameter of another mysqli_query() call. This does not make any sense.

Actually, had you read the manual on mysqli_query() on php.net, you would know how to properly check for errors:

 if ($PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID = '".$sqlDataIngelogd['RankID']."'")) {
     $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);
     ...

Note, that I also corrected the sql statement (replaced ° with = . But pls also note that you should use prepared statements if you have parameters in your sql query.


问:
Reversing the letters in words in a String
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

```<code> // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }
</code>```

Here is my output for some tests of mine:

```<code>     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }
</code>```

答:
A compact solution is

```<code>public static String reverse(String x) {
    Matcher m = Pattern.compile("\\w+").matcher(x);
    if(!m.find()) return x;
    StringBuffer target = new StringBuffer(x.length());
    do m.appendReplacement(target, new StringBuilder(m.group()).reverse().toString());
    while(m.find());
    return m.appendTail(target).toString();
}
</code>```

The appendReplacement loop + appendTail on a Matcher is the manual equivalent of String.replaceAll(regex), intended to support exactly such cases where the replacement is more complex than a simple string with placeholders, like reversing the found words.

Unfortunately, we have to use the outdated StringBuffer here, as the API is older than StringBuilder. Java 9 is going to change that.

A potentially more efficient alternative is

```<code>public static String reverse(String x) {
    Matcher m = Pattern.compile("\\w+").matcher(x);
    if(!m.find()) return x;
    StringBuilder target = new StringBuilder(x.length());
    int last=0;
    do {
        int s = m.start(), e = m.end();
        target.append(x, last, s).append(new StringBuilder(e-s).append(x, s, e).reverse());
        last = e;
    }
    while(m.find());
    return target.append(x, last, x.length()).toString();
}
</code>```

This uses StringBuilder throughout the operation and usese the feature to append partial character sequences, not creating intermediate strings for the match and replacement. It also elides the search for placeholders in the replacement, which appendReplacement does internally.

Body:
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

 // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }

Here is my output for some tests of mine:

     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }

Body:
A compact solution is

public static String reverse(String x) {
    Matcher m = Pattern.compile("\\w+").matcher(x);
    if(!m.find()) return x;
    StringBuffer target = new StringBuffer(x.length());
    do m.appendReplacement(target, new StringBuilder(m.group()).reverse().toString());
    while(m.find());
    return m.appendTail(target).toString();
}

The appendReplacement loop + appendTail on a Matcher is the manual equivalent of String.replaceAll(regex), intended to support exactly such cases where the replacement is more complex than a simple string with placeholders, like reversing the found words.

Unfortunately, we have to use the outdated StringBuffer here, as the API is older than StringBuilder. Java 9 is going to change that.

A potentially more efficient alternative is

public static String reverse(String x) {
    Matcher m = Pattern.compile("\\w+").matcher(x);
    if(!m.find()) return x;
    StringBuilder target = new StringBuilder(x.length());
    int last=0;
    do {
        int s = m.start(), e = m.end();
        target.append(x, last, s).append(new StringBuilder(e-s).append(x, s, e).reverse());
        last = e;
    }
    while(m.find());
    return target.append(x, last, x.length()).toString();
}

This uses StringBuilder throughout the operation and usese the feature to append partial character sequences, not creating intermediate strings for the match and replacement. It also elides the search for placeholders in the replacement, which appendReplacement does internally.


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答: You can't dynamically evaluate CFML stored in a database without first writing it to file and then using <cfinclude> to include it.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?


问:
Does packagename:::function cannot be used or modify?
I am working on a project and I need to modify some funciton of existing package. Some of these functions are not exported and I only can acess them via packagename:::function in R. Are these function cannot be modified or must be not used or we do not allowded to modify them since there are not exported by the author? any help please?

Note that: I need to build my own function based on some existing function from the package. The existing functions are very helful and for my project I need to modify them to what I need. Then I will use these functions in my project only for my use. I will not modify the package itself. Hope it is clear.

答: Just take the source code, paste it in your R script (and give it another name), modify the code as you want and run the function. Then it will be saved in your environment and you can run it as a normal function. Hope this helps!</p>


问:
Typing effect: Word per Word
I've been figuring out how to have a typing effect that is word per word instead of letter per letter. So far, all links I've searched are offering letter per letter typewriter effect.

https://macarthur.me/typeit/
https://github.com/mattboldt/typed.js/

Is this possible to achieve? Or have you done something similar?

答:
create an array with whichever words you want to print one at a time.</p>

```<code>const sentence = 'this sentence will be displayed one word at a time';
var arrayOfWords = sentence.split(' ');

for (var i = sentence.length - 1; i >= 0; i--) {
    setTimeout(function(){
        console.log(sentence[i]); // or display another way
    }, 400) // set this to your desired interval
}
</code>```

Title: Typing effect: Word per Word

Body:
create an array with whichever words you want to print one at a time.

const sentence = 'this sentence will be displayed one word at a time';
var arrayOfWords = sentence.split(' ');

for (var i = sentence.length - 1; i >= 0; i--) {
    setTimeout(function(){
        console.log(sentence[i]); // or display another way
    }, 400) // set this to your desired interval
}


问:
jQuery Autocomplete not getting updated value
I am trying to get the value in text box and its working  but the main problem is when I update the vendor from select box the current_vendor variable changes its value but in autocomplete function source URL keeps the old value of current_vendor which is 0 instead of new one I don't know what I am doing wrong or missing here is my code

```<code>$(document).ready(function(){
    var current_vendor = 0;
$("select[name=txtvendor]").change(function() {
    var current_vendor = $(this).find("option:selected").val();
});
$("input#ProdDescription").autocomplete({
    source: "includes/modProducts/search-products.php?viewVendor="+current_vendor,
    minLength: 1,
    select: function (event, ui) {
        var item = ui.item;
            if(item) {
                $(this).closest('.row').find('.txtchassis').val(item.ChassisNo);
                $(this).closest('.row').find('.txtdescription').val(item.BikeDescription);
                $(this).closest('.row').find('.txtprice').val(item.SellingAmount);

                $(this).closest('.row').find('.txtbikeid').val(item.BikeID);
                $(this).closest('.row').find('.txtcostprice').val(item.CostPrice);
                $(this).closest('.row').find('.txtcolorcode').val(item.ColorCode);
            }
        }
});
});
</code>```

答:
You need to call AutoComFunction() function to update values of current_vendor variable try this code it will resolve the problem

```<code>$("select[name=txtvendor]").change(function() {
vendor_code = this.value;
$('.selectpicker').selectpicker('refresh');
AutoComFunction();
}).change();
</code>```

Body:
I am trying to get the value in text box and its working  but the main problem is when I update the vendor from select box the current_vendor variable changes its value but in autocomplete function source URL keeps the old value of current_vendor which is 0 instead of new one I don't know what I am doing wrong or missing here is my code

$(document).ready(function(){
    var current_vendor = 0;
$("select[name=txtvendor]").change(function() {
    var current_vendor = $(this).find("option:selected").val();
});
$("input#ProdDescription").autocomplete({
    source: "includes/modProducts/search-products.php?viewVendor="+current_vendor,
    minLength: 1,
    select: function (event, ui) {
        var item = ui.item;
            if(item) {
                $(this).closest('.row').find('.txtchassis').val(item.ChassisNo);
                $(this).closest('.row').find('.txtdescription').val(item.BikeDescription);
                $(this).closest('.row').find('.txtprice').val(item.SellingAmount);

                $(this).closest('.row').find('.txtbikeid').val(item.BikeID);
                $(this).closest('.row').find('.txtcostprice').val(item.CostPrice);
                $(this).closest('.row').find('.txtcolorcode').val(item.ColorCode);
            }
        }
});
});

Body:
You need to call AutoComFunction() function to update values of current_vendor variable try this code it will resolve the problem

$("select[name=txtvendor]").change(function() {
vendor_code = this.value;
$('.selectpicker').selectpicker('refresh');
AutoComFunction();
}).change();


问:
XPATH: exclude elements which which has a specific child
```<code><ul>
  <li><a></li>
  <li><a></li>
  <li>
    <div>
      <a>
    </div>
  </li>
</ul>
</code>```

How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

```<code>./li[not(contains(descendant::div]
</code>```

But obviously that didn't work

答:
```<code>//li[not(contains(div,' '))]
</code>```

This works for me.

your code:

./li[not(contains(descendant::div]

is missing some ')', should have been:

```<code>./li[not(contains(descendant::div))]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

./li[not(contains(descendant::div]

But obviously that didn't work

Body:
//li[not(contains(div,' '))]

This works for me.

your code:

./li[not(contains(descendant::div]

is missing some ')', should have been:

./li[not(contains(descendant::div))]


问:
Exporting a MySQL database through PHPMyAdmin
I'm hoping to export a database that I only have access to through phpMyAdmin so that I can make a copy of it on my localhost.  I've never done this before and the database is fairly large at 200 tables.  Does anyone have experience doing this?  I'm just unsure if the web interface of phpMyAdmin is a reliable way to export that much data or if I'd be causing some performance issues by attempting to export the data.

Thanks for any advice. Thy phpMyAdmin version is 2.1 if that helps any.

答:
The issue you will come against is the max_execution_time setting.

What i have found is large databases take longer to dump than what is set here (defaults to 30 seconds).

This will cause your export to fail.

Also make sure you are not trying to dump to the browser, I have found that option unreliable. Choose the save to a file option, and download the dump via ftp .

But as Col. Shrapnel said, try it first!


问:
asp.net mvc fileupload ReadTimeout in HttpPostedFileBase inputstream
I have action in asp.net mvc that accepts a uploaded file. The HttpPostedFileBase I get is not null and even ContentLength has value greater than 0, but when I inspect "InputSream", it has following error :

ReadTimeout = '((System.Web.HttpPostedFileWrapper)refile).InputStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

So when I want to convert to readitbytes as follow, the there is nothing except empty array :

```<code>using (var reader = new System.IO.BinaryReader(refile.InputStream))
                    {
                        var a = reader.ReadBytes(model.File.ContentLength);
                    }
</code>```

So "a" get "{byte[0]}".

What is the problem ?

答:
You might be missing enctype in you form. Please correct your form if there is such kind of issue. A MVC Form with files will be like this

```<code>@using (Html.BeginForm("Add", "Advertisement", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
    //Content
}
</code>```

Thanks Hope this help!

Body:
I have action in asp.net mvc that accepts a uploaded file. The HttpPostedFileBase I get is not null and even ContentLength has value greater than 0, but when I inspect "InputSream", it has following error :

ReadTimeout = '((System.Web.HttpPostedFileWrapper)refile).InputStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

So when I want to convert to readitbytes as follow, the there is nothing except empty array :

using (var reader = new System.IO.BinaryReader(refile.InputStream))
                    {
                        var a = reader.ReadBytes(model.File.ContentLength);
                    }

So "a" get "{byte[0]}".

What is the problem ?

Body:
You might be missing enctype in you form. Please correct your form if there is such kind of issue. A MVC Form with files will be like this

@using (Html.BeginForm("Add", "Advertisement", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
    //Content
}

Thanks Hope this help!


问:
Fetch the questions from json in Angular

(function() {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];
Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="ad-container">
    <h1 class="text-center headtext">Interview Questions</h1>
    <form name="interviewForm">
        <p></p>
    </form>
</div></code>```

Here is my json

```<code>{
  "Q1": "What is a pointer on pointer?",
  "Q2": "Write about yourself?",
  "Q3": "write a program to find multiplication of two number?",
  "Q4": "write a program to find addition of two number?",
  "Q5": "write a program to find subtraction of two number?",
  "Q6": "write a program to find percentage?",
  "Q7": "write a program to find addition of two number?",
  "Q8": "write a program to find addition of two number?"
}
</code>```

How to fetch a sigle question from the json and show in html?

答:
If I understand you correctly, a simple ng-repeat

```<code><p ng-repeat="dataItem in data">{{dataItem}}</p>
</code>```

the following snippet will give you some insights

(function() {
  'use strict';
  angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
  InterviewController.$inject = ['$scope', 'Interview'];

  function InterviewController($scope, Interview) {
    $scope.data = {}
    $scope.showSubmit = false;
    Interview.fetchQuestion().then(function(data) {
      $scope.curentPage = 0;
      console.log(data)
      $scope.data = data;
      $scope.updateCurrentPage = function() {
        if (Object.keys($scope.data).length - 1 > $scope.curentPage) {
          $scope.curentPage++;
        } else {
          $scope.showSubmit = true;
        }
      }
    })
  };

  Interview.$inject = ['$http', '$q'];

  function Interview($http, $q) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
      //return $http.get('/app/interview/questions.json');
      var data = {
        "Q1": "What is a pointer on pointer?",
        "Q2": "Write about yourself?",
        "Q3": "write a program to find multiplication of two number?",
        "Q4": "write a program to find addition of two number?",
        "Q5": "write a program to find subtraction of two number?",
        "Q6": "write a program to find percentage?",
        "Q7": "write a program to find addition of two number?"
      };
      var deferred = $q.defer();
      deferred.resolve(data);
      return deferred.promise;
    }
  }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.min.js"></script>
<div ng-app="app.interview">
  <div class="ad-container" ng-controller="InterviewController">
    <h1 class="text-center headtext">Interview Questions</h1>
    <form name="interviewForm">
      <div ng-repeat="dataItem in data track by $index" ng-show="$index==curentPage">
        <p>{{dataItem}}</p>
        <input type="text" placeholder="Aswer">
      </div>
      <div ng-if="!showSubmit">
        <button ng-click="updateCurrentPage()">Next</button>
      </div>
      <div ng-if="showSubmit">
        <button>Submit</button>
      </div>
    </form>
  </div>
</div></code>```

Body:
(function() {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];
Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}
})();

Interview Questions

    <form name="interviewForm">

    </form>

Here is my json

{
  "Q1": "What is a pointer on pointer?",
  "Q2": "Write about yourself?",
  "Q3": "write a program to find multiplication of two number?",
  "Q4": "write a program to find addition of two number?",
  "Q5": "write a program to find subtraction of two number?",
  "Q6": "write a program to find percentage?",
  "Q7": "write a program to find addition of two number?",
  "Q8": "write a program to find addition of two number?"
}

How to fetch a sigle question from the json and show in html?

Body:
If I understand you correctly, a simple ng-repeat

<p ng-repeat="dataItem in data">{{dataItem}}</p>

the following snippet will give you some insights

(function() {
  'use strict';
  angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
  InterviewController.$inject = ['$scope', 'Interview'];

  function InterviewController($scope, Interview) {
    $scope.data = {}
    $scope.showSubmit = false;
    Interview.fetchQuestion().then(function(data) {
      $scope.curentPage = 0;
      console.log(data)
      $scope.data = data;
      $scope.updateCurrentPage = function() {
        if (Object.keys($scope.data).length - 1 > $scope.curentPage) {
          $scope.curentPage++;
        } else {
          $scope.showSubmit = true;
        }
      }
    })
  };

  Interview.$inject = ['$http', '$q'];

  function Interview($http, $q) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
      //return $http.get('/app/interview/questions.json');
      var data = {
        "Q1": "What is a pointer on pointer?",
        "Q2": "Write about yourself?",
        "Q3": "write a program to find multiplication of two number?",
        "Q4": "write a program to find addition of two number?",
        "Q5": "write a program to find subtraction of two number?",
        "Q6": "write a program to find percentage?",
        "Q7": "write a program to find addition of two number?"
      };
      var deferred = $q.defer();
      deferred.resolve(data);
      return deferred.promise;
    }
  }
})();

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.min.js"></script>
<div ng-app="app.interview">
  <div class="ad-container" ng-controller="InterviewController">
    <h1 class="text-center headtext">Interview Questions</h1>
    <form name="interviewForm">
      <div ng-repeat="dataItem in data track by $index" ng-show="$index==curentPage">
        <p>{{dataItem}}</p>
        <input type="text" placeholder="Aswer">
      </div>
      <div ng-if="!showSubmit">
        <button ng-click="updateCurrentPage()">Next</button>
      </div>
      <div ng-if="showSubmit">
        <button>Submit</button>
      </div>
    </form>
  </div>
</div>


问:
Redux Form Dynamic Field Level Validation
I have a dynamic form field that is required based on the value of a form selected field. ie If the value of a certain field is "Yes" then the comment box is required and if "No" then it is not required.

If I initially select "Yes" and touch and blur the comment field the validation will return the required error. But after if I switch to "No" and back to "Yes" the validation error no longer occurs. If I type into the comment box and remove the validation will occur again.

I am using field level validation and have also use sync validation with the same issue.

```<code><Field name={`${fieldId}.comment`}  validate={condition.required ? [required] : []} label={condition.label} className="form-control" component={renderTextField} />
</code>```

Where condition is the check to see whether the field should be required.

The logic is correct as the validation work on initial selection and if you fill the comment field and remove the text but it just does not seem to receive the validation error.

Thanks in advance

答:
Quote from the Redux-Form Field component docs (v 6.8.0):

validate : (value, allValues, props) => error [optional]

Allows you to to provide a field-level validation rule. The function
  will be given the current value of the field, all the other form
  values, and any props passed to the form. If the field is valid, it
  should return undefined, if the field is invalid, it should return an
  error (usually, but not necessarily, a String).

You're trying to pass the error value in to the Field directly, but the validate prop is meant to accept a validation function that is used to determine validity. You should do something like this:

```<code>const validateComment = (value, allValues, props) => {
  // naturally you do something else here if the value
  // used to determine whether this field is required or
  // not is not managed by the same redux form
  const isRequired = allValues.commentRequired === 'Yes'

  if (isRequired && !value) return "Can't be empty."
}

<Field
  name={`${fieldId}.comment`}
  validate={ validateComment }
  label={condition.label}
  className="form-control"
  component={renderTextField}
/>
</code>```

Hope this helps!

Body:
I have a dynamic form field that is required based on the value of a form selected field. ie If the value of a certain field is "Yes" then the comment box is required and if "No" then it is not required.

If I initially select "Yes" and touch and blur the comment field the validation will return the required error. But after if I switch to "No" and back to "Yes" the validation error no longer occurs. If I type into the comment box and remove the validation will occur again.

I am using field level validation and have also use sync validation with the same issue.

<Field name={`${fieldId}.comment`}  validate={condition.required ? [required] : []} label={condition.label} className="form-control" component={renderTextField} />

Where condition is the check to see whether the field should be required.

The logic is correct as the validation work on initial selection and if you fill the comment field and remove the text but it just does not seem to receive the validation error.

Thanks in advance

Body:
Quote from the Redux-Form Field component docs (v 6.8.0):

validate : (value, allValues, props) => error [optional]

Allows you to to provide a field-level validation rule. The function
  will be given the current value of the field, all the other form
  values, and any props passed to the form. If the field is valid, it
  should return undefined, if the field is invalid, it should return an
  error (usually, but not necessarily, a String).

You're trying to pass the error value in to the Field directly, but the validate prop is meant to accept a validation function that is used to determine validity. You should do something like this:

const validateComment = (value, allValues, props) => {
  // naturally you do something else here if the value
  // used to determine whether this field is required or
  // not is not managed by the same redux form
  const isRequired = allValues.commentRequired === 'Yes'

  if (isRequired && !value) return "Can't be empty."
}

<Field
  name={`${fieldId}.comment`}
  validate={ validateComment }
  label={condition.label}
  className="form-control"
  component={renderTextField}
/>

Hope this helps!


问:
List of tables in all databases used in stored procedures
We have created stored procedures which include lot of tables from different databases in same server. Now i need to list all the table corresponding  particular stored procedures.
I have tried the following query, but it shows only tables which related to particular database only.

The query is attached here:

```<code>SELECT
  t.TABLE_NAME,
  s.ROUTINE_NAME,
  s.SPECIFIC_SCHEMA
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.ROUTINES s
  ON s.ROUTINE_NAME IN (SELECT
    referencing_entity_name
  FROM sys.dm_sql_referencing_entities(TABLE_SCHEMA + '.' + TABLE_NAME, 'OBJECT'))
  AND s.ROUTINE_TYPE = 'PROCEDURE'
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND s.ROUTINE_NAME LIKE '%Procedure name%'
ORDER BY s.ROUTINE_NAME
</code>```

答:
This query will give a list of tables used in 'spName' Stored Procedure. You can also remove this condition to get details about all Stored procedures in the DB

```<code>SELECT TBL.TABLE_NAME, SR.ROUTINE_NAME,SR.SPECIFIC_SCHEMA
    FROM INFORMATION_SCHEMA.TABLES TBL
    INNER JOIN INFORMATION_SCHEMA.ROUTINES SR
    ON SR.ROUTINE_NAME IN
    (
            SELECT referencing_entity_name
            FROM sys.dm_sql_referencing_entities(TABLE_SCHEMA + '.' + TABLE_NAME, 'OBJECT')
    )
    AND SR.ROUTINE_TYPE = 'PROCEDURE'
    WHERE TBL.TABLE_TYPE = 'BASE TABLE' and SR.ROUTINE_NAME='spName'
</code>```

Also
To obtain whole Tables List in DB use

```<code>SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
</code>```

And to obtain all Procedures name use

```<code>SELECT SPECIFIC_NAME
    FROM INFORMATION_SCHEMA.ROUTINES
</code>```

Body:
We have created stored procedures which include lot of tables from different databases in same server. Now i need to list all the table corresponding  particular stored procedures.
I have tried the following query, but it shows only tables which related to particular database only.

The query is attached here:

SELECT
  t.TABLE_NAME,
  s.ROUTINE_NAME,
  s.SPECIFIC_SCHEMA
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.ROUTINES s
  ON s.ROUTINE_NAME IN (SELECT
    referencing_entity_name
  FROM sys.dm_sql_referencing_entities(TABLE_SCHEMA + '.' + TABLE_NAME, 'OBJECT'))
  AND s.ROUTINE_TYPE = 'PROCEDURE'
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND s.ROUTINE_NAME LIKE '%Procedure name%'
ORDER BY s.ROUTINE_NAME

Body:
This query will give a list of tables used in 'spName' Stored Procedure. You can also remove this condition to get details about all Stored procedures in the DB

SELECT TBL.TABLE_NAME, SR.ROUTINE_NAME,SR.SPECIFIC_SCHEMA
    FROM INFORMATION_SCHEMA.TABLES TBL
    INNER JOIN INFORMATION_SCHEMA.ROUTINES SR
    ON SR.ROUTINE_NAME IN
    (
            SELECT referencing_entity_name
            FROM sys.dm_sql_referencing_entities(TABLE_SCHEMA + '.' + TABLE_NAME, 'OBJECT')
    )
    AND SR.ROUTINE_TYPE = 'PROCEDURE'
    WHERE TBL.TABLE_TYPE = 'BASE TABLE' and SR.ROUTINE_NAME='spName'

Also
To obtain whole Tables List in DB use

SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES

And to obtain all Procedures name use

SELECT SPECIFIC_NAME
    FROM INFORMATION_SCHEMA.ROUTINES


问:
use of undeclared type 'Date' Xcode 9 Swift 4
This is my code in xcode 9 playground </p>

```<code>class Tutorial: Codable {
    let title: String
    let author: String
    let editor: String
    let type: String
    let publishDate: Date

    init(title: String, author: String, editor: String, type: String, publishDate: Date) {
        self.title = title
        self.author = author
        self.editor = editor
        self.type = type
        self.publishDate = publishDate
    }
}
</code>```

<p>its showing error use of undeclared type 'Date' </p>

答:
The Date struct is part of the Foundation framework.

Add import Foundation at the beginning of your playground.

As a general rule, you should always import at least Foundation because many of the everyday types we use are part of Foundation. You can also import only UIKit (because UIKit automatically imports Foundation).

Body:
This is my code in xcode 9 playground

class Tutorial: Codable {
    let title: String
    let author: String
    let editor: String
    let type: String
    let publishDate: Date

    init(title: String, author: String, editor: String, type: String, publishDate: Date) {
        self.title = title
        self.author = author
        self.editor = editor
        self.type = type
        self.publishDate = publishDate
    }
}

its showing error use of undeclared type 'Date'


问:
What does the author mean by "event handler function wants to unbind itself after it fires"
I'm currently studying JavaScript by following the book series "you don't know js"

In the scope & closure section of the book, when discussing naming function expressions, the author mentioned.

Without a name, if the function needs to refer to itself, for
  recursion, etc., the deprecated arguments.callee reference is
  unfortunately required. Another example of needing to self-reference
  is when an event handler function wants to unbind itself after it
  fires.

Because I am relatively inexperienced at JavaScript, I'm not really sure what "event handler function unbinding" is (I know what "event handler function" is) and how it works.

So I was just wondering if someone could explain it; what it actually does? (a code sample would be even better).

答:
Event handlers can take anonymous functions, this works fine.

document.querySelector("button").addEventListener("click",function(){
    console.log("Clicked from anonymous func");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click me</button></code>```

It is possible to remove an event handler too (removeEventListener) and it is possible that the programmer wants that to happen after the event has been raised (typically, you might only want an event to occur once). Using the code above that would be difficult as you have no way to refer to the anonymous function acting as the event listener.

Changing for a named function makes this much easier:

function myEventHandler(){
    console.log("Clicked from named func - but it'll only work once");
    // In an event handler "this" refers to the clicked element
    this.removeEventListener('click',myEventHandler)
}

document.querySelector("button").addEventListener("click",myEventHandler);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click me</button></code>```

Body:
Event handlers can take anonymous functions, this works fine.

document.querySelector("button").addEventListener("click",function(){
    console.log("Clicked from anonymous func");
});

<button>Click me</button>

It is possible to remove an event handler too (removeEventListener) and it is possible that the programmer wants that to happen after the event has been raised (typically, you might only want an event to occur once). Using the code above that would be difficult as you have no way to refer to the anonymous function acting as the event listener.

Changing for a named function makes this much easier:

function myEventHandler(){
    console.log("Clicked from named func - but it'll only work once");
    // In an event handler "this" refers to the clicked element
    this.removeEventListener('click',myEventHandler)
}

document.querySelector("button").addEventListener("click",myEventHandler);

<button>Click me</button>


问:
Google Places Photos .GetUrl is adding width and height to url
I'm trying to get images from google places. All is working for details: reviews, address... but when I try to get photos, I get a 404.

```<code>if(place.photos != null){
      for(var i = 0; i < place.photos.length; i++){
        var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
        var res = str.replace("w100-h100-p", "p");
        self.pacPhotos.push({
          id : res

        });

      }
    }else {
      console.log("no photo");
    }
  }
</code>```

This will return the list ok but the URL is formatted wrong. it comes out like this.

" https://lh3.googleusercontent.com/w100-h100-p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "

What I gather it wants is this.
" https://lh3.googleusercontent.com/p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "

The only difference is the "w100-h100-"

*** There is a great work-around here from "Sulyman". I know it's not a long term solution as I'm sure google will fix their results (as discussed here Place API - getting place photo as marker icon )

For now I've adjusted the code above to reflect Sulymans suggestion. ***

答:
it seems like every API Key generates different path
for example you got w100-h100-p and i got w200-p
and the good news that this section whatever it is...is fixed so you can replace it with another string which is p

```<code>var str = place.photos[0].getUrl();
var res = str.replace(""w100-h100-p", "p");
</code>```

or you can delete the w100-h100-

Body:
I'm trying to get images from google places. All is working for details: reviews, address... but when I try to get photos, I get a 404.

if(place.photos != null){
      for(var i = 0; i < place.photos.length; i++){
        var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
        var res = str.replace("w100-h100-p", "p");
        self.pacPhotos.push({
          id : res

        });

      }
    }else {
      console.log("no photo");
    }
  }

This will return the list ok but the URL is formatted wrong. it comes out like this.

" https://lh3.googleusercontent.com/w100-h100-p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "

What I gather it wants is this.
" https://lh3.googleusercontent.com/p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "

The only difference is the "w100-h100-"

*** There is a great work-around here from "Sulyman". I know it's not a long term solution as I'm sure google will fix their results (as discussed here Place API - getting place photo as marker icon )

For now I've adjusted the code above to reflect Sulymans suggestion. ***

Body:
it seems like every API Key generates different path
for example you got w100-h100-p and i got w200-p
and the good news that this section whatever it is...is fixed so you can replace it with another string which is p

var str = place.photos[0].getUrl();
var res = str.replace(""w100-h100-p", "p");

or you can delete the w100-h100-


问:
Unable to access React instance (this) inside event handler
I am writing a simple component in ES6 (with BabelJS), and functions this.setState is not working.

Typical errors include something like

Cannot read property 'setState' of undefined

or

this.setState is not a function

Do you know why? Here is the code:

```<code>import React from 'react'

class SomeClass extends React.Component {
  constructor(props) {
    super(props)
    this.state = {inputContent: 'startValue'}
  }

  sendContent(e) {
    console.log('sending input content '+React.findDOMNode(React.refs.someref).value)
  }

  changeContent(e) {
    this.setState({inputContent: e.target.value})
  }

  render() {
    return (
      <div>
        <h4>The input form is here:</h4>
        Title:
        <input type="text" ref="someref" value={this.inputContent}
          onChange={this.changeContent} />
        <button onClick={this.sendContent}>Submit</button>
      </div>
    )
  }
}

export default SomeClass
</code>```

答:
In case you want to keep the bind in constructor syntax, you can use the proposal-bind-operator and transform your code like follow :

```<code>constructor() {
  this.changeContent = ::this.changeContent;
}
</code>```

Instead of :

```<code>constructor() {
  this.changeContent = this.changeContent.bind(this);
}
</code>```

much simpler, no need of bind(this) or fatArrow.

Body:
I am writing a simple component in ES6 (with BabelJS), and functions this.setState is not working.

Typical errors include something like

Cannot read property 'setState' of undefined

or

this.setState is not a function

Do you know why? Here is the code:

import React from 'react'

class SomeClass extends React.Component {
  constructor(props) {
    super(props)
    this.state = {inputContent: 'startValue'}
  }

  sendContent(e) {
    console.log('sending input content '+React.findDOMNode(React.refs.someref).value)
  }

  changeContent(e) {
    this.setState({inputContent: e.target.value})
  }

  render() {
    return (

The input form is here:

        Title:
        <input type="text" ref="someref" value={this.inputContent}
          onChange={this.changeContent} />
        <button onClick={this.sendContent}>Submit</button>

    )
  }
}

export default SomeClass

Body:
In case you want to keep the bind in constructor syntax, you can use the proposal-bind-operator and transform your code like follow :

constructor() {
  this.changeContent = ::this.changeContent;
}

Instead of :

constructor() {
  this.changeContent = this.changeContent.bind(this);
}

much simpler, no need of bind(this) or fatArrow.


问:
Display a list only when a checkbox is checked
I'm having some trouble with HTML and Javascript (which I'm still new to). I use the Django Framework to display a list in a table case : for each element of my database, I display a list, and in this first list, a new list of corresponding elements in the database.

I made a  JSFiddle.

The situation :

```<code><tr>
               <td>Foo</td>
               <td>Fighters<td>
               <td>Bar</td>
               <td>Baz</td>
               <td>
                   <ul>
                         {% for domain,terms in django_database %}
                               <li>
                               <input type="checkbox" class="listcheck"><label for="listcheck">  -  {{ domain }}</label>
                               <!-- When checkbox is checked, the following list displays -->
                                <ul>
                                   {% for object in database %}
                                       <li>{{ object }}</li>
                                   {% endfor %}
                                </ul>
                               </li>
                          {% endfor %}
                    </ul>
                </td>
</tr>
</code>```

This is the Javascript that I tried, shamelessly stolen from a related question.

```<code>for (var i = 0; i < checkboxes.length; i++)
{
   var box = checkboxes[i];
    box.onclick = function()
    {
        var currentList = this.parentNode;
        var secondColumn = currentRow.getElementsByTagName("ul")[1];

        alert("My text is: " + secondColumn.textContent );
    };
}
</code>```

Now, I can display the two HTML lists without any trouble, it works fine. But I can't manage to get a checkbox that works. Hmm.

答:
take a look at this JS Fiddle . Its a simple JS solution with a fadeToggle. The Delay of 100 is optional but it makes the hole thing more elegant.

```<code><input class="collapsed" type="checkbox">The Checkbox
<div class="collapse2 collapse" style="display:none;">
   <li>hello there</li>
   <li>hello there</li>
   <li>hello there</li>
</div>

$(".collapsed").click(function(event){
    $(".collapse2").fadeToggle().delay(100);
})
</code>```

That should do the Trick if not leave a comment.

Body:
I'm having some trouble with HTML and Javascript (which I'm still new to). I use the Django Framework to display a list in a table case : for each element of my database, I display a list, and in this first list, a new list of corresponding elements in the database.

I made a  JSFiddle.

The situation :

               Foo
               Fighters
               Bar
               Baz

                         {% for domain,terms in django_database %}

                               <input type="checkbox" class="listcheck">  -  {{ domain }}

                                   {% for object in database %}

{{ object }}

                                   {% endfor %}

                          {% endfor %}

This is the Javascript that I tried, shamelessly stolen from a related question.

for (var i = 0; i < checkboxes.length; i++)
{
   var box = checkboxes[i];
    box.onclick = function()
    {
        var currentList = this.parentNode;
        var secondColumn = currentRow.getElementsByTagName("ul")[1];

        alert("My text is: " + secondColumn.textContent );
    };
}

Now, I can display the two HTML lists without any trouble, it works fine. But I can't manage to get a checkbox that works. Hmm.

Body:
take a look at this JS Fiddle . Its a simple JS solution with a fadeToggle. The Delay of 100 is optional but it makes the hole thing more elegant.

<input class="collapsed" type="checkbox">The Checkbox
<div class="collapse2 collapse" style="display:none;">
   <li>hello there</li>
   <li>hello there</li>
   <li>hello there</li>
</div>

$(".collapsed").click(function(event){
    $(".collapse2").fadeToggle().delay(100);
})

That should do the Trick if not leave a comment.


问:
I'm Confused About Naming Between Sap Odata and Sapui5
https://blogs.sap.com/2015/02/05/simple-exercise-on-odata-and-sap-ui5-application-for-the-basic-crud-operation/

Im trying to make my own sapui5 project based on project above. But I'm so much confused about field naming in data base. There is too much names similar to each other(they represent each other but I just dont understand which one im using in abap an wich one I'm using in js).

Can someone please highlight it? At least i should understand relation between them.

答:
For the project new DB table ZMM_EMP created. Data model use source parameters imported from the table. Fields for mapping are provided by function modules with names IV_* and ET_*.

Regards
Sergii


问:
Splitting a table cell into two columns in HTML
I have the following table:

```<code><table border="1">
  <tr>
    <th scope="col">Header</th>
    <th scope="col">Header</th>
    <th scope="col">Header</th>
  </tr>
  <tr>
    <th scope="row"> </th>
    <td> </td>
    <td>Split this one into two columns</td>
  </tr>
</table>
</code>```

And I wish to split the cell which contains "Split this one into two columns" into two cells/columns. How do I go about this?

Fiddle

答:
Please try the following way.</p>

```<code><table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <td colspan="2">Sum: $180</td>
  </tr>
</table>
</code>```

Body:
I have the following table:

    Header
    Header
    Header

    Split this one into two columns

And I wish to split the cell which contains "Split this one into two columns" into two cells/columns. How do I go about this?

Fiddle

Body:
Please try the following way.

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <td colspan="2">Sum: $180</td>
  </tr>
</table>


问:
Is the kubernetes api exposed by openshift the original kubernetes api?
Openshift exposes a Kubernetes api. Tools like Spinnaker can access Kubernetes natively.

I would like to access the Kubernetes API exposed by Openshift via Spinnaker.

Is the Kubernetes api that is exposed by Openshift the original Kubernetes api or a modified version?
If it is the original API it should be possible to access it directly from Spinnaker?

答:
From https://www.openshift.com/container-platform/kubernetes.html and https://docs.openshift.com/enterprise/3.0/rest_api/kubernetes_v1.html, it can be seen that Openshift includes the original k8s API (v1). Apart from that, it also includes its own API group with custom API objects (https://docs.openshift.com/enterprise/3.0/rest_api/openshift_v1.html). So, as long as you want to use API v1 elements, you can access the API just as you would do with vanilla Kubernetes. Examples of API access can be seen here https://docs.openshift.com/container-platform/3.5/rest_api/index.html#rest-api-example-curl. If you can access with curl, Spinnaker should pose no problem.

EDIT: As Graham Dumpleton says in the comments, you may need to configure some RBAC policies to allow the access for your user: https://docs.openshift.com/enterprise/3.0/admin_guide/manage_authorization_policy.html


问:
How to show / hide a button on a sheet in libreoffice calc using macros?
I face a little problem with libreoffice calc v5.1.6.2 as I didn't managed to find how to show / hide a button on a sheet using macros.

I'm talking about buttons directly on the sheet, not the dialog ones (haven't tested on dialogs yet, maybe it will be the same problem...).

So I can enable / disable them by using something like:

```<code>MyButton.enabled = True (or False)
</code>```

after I populated "MyButton" with the right object, but there is no

```<code>MyButton.visible = False
</code>```

or

```<code>MyButton.isVisible = False
</code>```

Despite the fact the "visible" property exists in the editor, right below the "enabled" line in design mode. So how can I acheive that dynamically?

答:
XrayTool shows a property with the somewhat unusual name of EnableVisible.

oSheet = ThisComponent.CurrentController.ActiveSheet
oButton = oSheet.DrawPage.Forms.getByIndex(0).getByName("Push Button 1")
oButton.EnableVisible = False  'Hide the button
```

For this to work, Calc's Design Mode must be off.  If it is on, then all buttons will be shown regardless of their visibility setting.

Note: I could not find this property in the API docs.

Body:
I face a little problem with libreoffice calc v5.1.6.2 as I didn't managed to find how to show / hide a button on a sheet using macros.

I'm talking about buttons directly on the sheet, not the dialog ones (haven't tested on dialogs yet, maybe it will be the same problem...).

So I can enable / disable them by using something like:

MyButton.enabled = True (or False)

after I populated "MyButton" with the right object, but there is no

MyButton.visible = False

or

MyButton.isVisible = False

Despite the fact the "visible" property exists in the editor, right below the "enabled" line in design mode. So how can I acheive that dynamically?

Body:
XrayTool shows a property with the somewhat unusual name of EnableVisible.

oSheet = ThisComponent.CurrentController.ActiveSheet
oButton = oSheet.DrawPage.Forms.getByIndex(0).getByName("Push Button 1")
oButton.EnableVisible = False  'Hide the button

For this to work, Calc's Design Mode must be off.  If it is on, then all buttons will be shown regardless of their visibility setting.

Note: I could not find this property in the API docs.


问:
What's a simple way to generate a random bool in C?
I want to generate a random boolean for use in a game, so it does not need to be cryptographically secure. I will use stdbool.h in my code, and I have also done #include <stdlib.h>. Preferably, it should be very fast (as I will be generating many of them), and it should be able to be done in C89 (just preference). I am not interested at all in doing this in C++.

Here are some of the ways I've come up with:

read from /dev/urandom, filter out single digits and >5 = true, <5 = false.

keep calling rand() and filter out low/high values.

答:
If you have RDRAND instruction set on a x86_64 CPU:

```<code>#include <immintrin.h>
#include <cstdint>
...
bool randBool() {
  uint64_t val;
  if(!_rdseed64_step(&val)) {
    printf("Error generating hardware random value\n");
  }
  return bool(val&1);
}
</code>```

However, this wastes 63 out of 64 pseudo-random bits generated. If you need more speed, call _rdseed64_step() once in 64 random bit generations, but change the bit tested in each generation: val&(1<<0) , val & (1<<1), val & (1<<2), val & (1<<3), ... , val & (1<<i), ..., val & (1<<63) .

Body:
If you have RDRAND instruction set on a x86_64 CPU:

#include <immintrin.h>
#include <cstdint>
...
bool randBool() {
  uint64_t val;
  if(!_rdseed64_step(&val)) {
    printf("Error generating hardware random value\n");
  }
  return bool(val&1);
}

However, this wastes 63 out of 64 pseudo-random bits generated. If you need more speed, call _rdseed64_step() once in 64 random bit generations, but change the bit tested in each generation: val&(1<<0) , val & (1<<1), val & (1<<2), val & (1<<3), ... , val & (1<<i), ..., val & (1<<63) .


问:
Add group "Everyone" to directory and all of it's sub-directories
I'm currently using Vista 32-bit. How do I add the Windows security group "Everyone" and give full control to a directory and all of it's sub-directories and all files? Is there a powershell script that I could use?

Thanks!

答:
Sometimes the "native" PowerShell way isn't necessarily the best way.  For something like this I would still use icacls.exe.  Remember that good ol' exes work pretty good in PowerShell.  Just cd to the directory you want to set and execute:

```<code>icacls $pwd /grant "Everyone":(OI)(CI)F
</code>```

This will give Everyone full access to the current directory downwards (via permission inheritance).  This should work as long as there are no explicit denials to Everyone in the dir structure.

Body:
Sometimes the "native" PowerShell way isn't necessarily the best way.  For something like this I would still use icacls.exe.  Remember that good ol' exes work pretty good in PowerShell.  Just cd to the directory you want to set and execute:

icacls $pwd /grant "Everyone":(OI)(CI)F

This will give Everyone full access to the current directory downwards (via permission inheritance).  This should work as long as there are no explicit denials to Everyone in the dir structure.


问:
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
In order to access to a remote database I have edited config.inc.php and at the end of it, before the end ?> I have added :

```<code>$i++;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
</code>```

but when I connect using browser I have this error message:

Notice in ./libraries/common.inc.php#1204 Undefined variable: i

Backtrace

./phpmyadmin.css.php#14: require_once(./libraries/common.inc.php)

The versions are:

```<code>PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)
</code>```

phpMyAdmin works well with local database, without configure common.inc.php

In the middle of common.inc.php there's this instruction unset($i), but how can I use the i variable a the end of common.inc.php if it is no longer available ?

I have initialized i in this way

```<code>$i=2;
</code>```

now I see a drop down menu with server name, but when I selected one of them it returns to localhost.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

On client server I'm using Linux, on remote I'm using Windows 7

I have entered another request regarding the server selection problem only at phpMyAdmin can't connect to remote sever on Windows 7 from Linux client

答:
It's a Notice that occurs when you access a variable that is not defined. In your case the variable is $i.

Define is first as below

```<code>$i = 0;
</code>```

Then use it in rest of your code.

Body:
In order to access to a remote database I have edited config.inc.php and at the end of it, before the end ?> I have added :

$i++;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config

but when I connect using browser I have this error message:

Notice in ./libraries/common.inc.php#1204 Undefined variable: i

Backtrace

./phpmyadmin.css.php#14: require_once(./libraries/common.inc.php)

The versions are:

PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)

phpMyAdmin works well with local database, without configure common.inc.php

In the middle of common.inc.php there's this instruction unset($i), but how can I use the i variable a the end of common.inc.php if it is no longer available ?

I have initialized i in this way

$i=2;

now I see a drop down menu with server name, but when I selected one of them it returns to localhost.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

On client server I'm using Linux, on remote I'm using Windows 7

I have entered another request regarding the server selection problem only at phpMyAdmin can't connect to remote sever on Windows 7 from Linux client

Body:
It's a Notice that occurs when you access a variable that is not defined. In your case the variable is $i.

Define is first as below

$i = 0;

Then use it in rest of your code.


问:
The "Xamarin.Build.Download.XamarinBuildAndroidAarProguardConfigs" task could not be loaded from the assembly
So I enabled proguard on one of my application. I had some problems with it but I solved them all ( had to update proguard, make a symlink of android sdk without spaces )

Now I enabled pro guard on another application and i'm constantly getting this error:

```<code>The "Xamarin.Build.Download.XamarinBuildAndroidAarProguardConfigs" task could not be loaded from the assembly C:\Users\xxx\Desktop\xxx oud\packages\Xamarin.Build.Download.0.4.6\build\Xamarin.Build.Download.dll.  Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
</code>```

Anybody knows a way to solve this? Not sure what more I could add

答:
I resolved my issue by restarting my computer

Edit: It seems restarting visual studio might be enough to resolve the problem

Body:
So I enabled proguard on one of my application. I had some problems with it but I solved them all ( had to update proguard, make a symlink of android sdk without spaces )

Now I enabled pro guard on another application and i'm constantly getting this error:

The "Xamarin.Build.Download.XamarinBuildAndroidAarProguardConfigs" task could not be loaded from the assembly C:\Users\xxx\Desktop\xxx oud\packages\Xamarin.Build.Download.0.4.6\build\Xamarin.Build.Download.dll.  Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

Anybody knows a way to solve this? Not sure what more I could add


问:
newline not showing in email (PHP)
I have a the string like the following used within an email sent by my application:

```<code>$msg = "{$name} has submitted an email for review.\n\n You can preview the email here";
</code>```

The  \n doesn't appear within the email - any ideas why?

I am using PHPMailer (old I know..)

答:
There is a new issue with sending html email. Spamfilters strictly enforce the rfc5322 and do not accept any line length > 998 characters.
See https://www.ietf.org/rfc/rfc5322.txt --> par 2.1.1
Adding a html br tag to a large html file does still result in a single text line.

The solution is to use a wrapper (yes even when sending html) like
    $message = wordwrap($message, 70);

In my case (sending large CSV-like datasets) I had to ensure that there were spaces in the html that allow for the wrap to work.
There is no visual effect on the html result as shown by the email client.

Title: newline not showing in email (PHP)

Body:
I have a the string like the following used within an email sent by my application:

$msg = "{$name} has submitted an email for review.\n\n You can preview the email here";

The  \n doesn't appear within the email - any ideas why?

I am using PHPMailer (old I know..)


问:
SMS and/or notification tones
Is there a way to only upload mp3 tones to the Android Market or do they have to be delivered via an APK? </p>

答: You can only list APK files on the Android Market.</p>

Title: SMS and/or notification tones


问:
Debugging MySQL Triggers
I love triggers for one reason - they just work. I hate triggers for one reason - when they don't work, forget about trying to debug. O the sweet frustration.

Basically, I want to see THE update, delete, insert, etc query that was ran. I want to see that query ... somewhere, in my terminal or a log, exactly how and when MySQL executes it, and possibly any corresponding output/errors. Thoughts/hacks?

I'm trying to debug an update query with a few joins and what not. My queries are much more complex but for brevity here's an example.

```<code>DELIMITER |
CREATE TRIGGER ireallyhateyourightnow AFTER UPDATE ON watch_this_table
FOR EACH ROW BEGIN
 IF (OLD.my_value != NEW.my_value) THEN
  update
   my_table
  set
   my_column = NEW.my_value;
 END IF;
END|
DELIMITER ;
</code>```

Here is some additional context that may help influence a suggestion or answer. Again, I'm less interested in semantics/syntax and more interested in seeing MySQL run the query but by all means, I'm open to anything at this point.

Strace does not work/show query.

Non-replicated environment BUT if the bin logs show trigger statements I will certainly set this up.

Does "show full processlist" show trigger execution and/or statements executed within (I never see them after running show full processlist as fast as perl can run it but I might just be missing it)?

General query log does not show these queries (certainly not the error log).

I'm not using aliases (anymore).

No syntax errors when creating the trigger.

The IF statement works.

When I insert the NEW values into a "test/temp" table and manually run the update query it works (I've even went so far as to actually inserting the whole update query)

I can't show you the query but as I just mentioned, it works when I run manually if that helps.

I've removed all erroneous characters, tabs, carriage returns, newlines, etc.

The MySQL socket would only show local connection/data but not MySQL internal workings, I think.

MyISAM so INNODB logs aren't an option

lsof didn't seem to show anything else to be of use.

I'm using MySQL 5.0.77 on CentOS 5.5.

答:
There's an alternate way of testing it by having a temporary debug table. In the example here, they create it in an own debug database.

Step 1: Create a table

```<code>DROP TABLE IF EXISTS debug;
CREATE TABLE debug (
  proc_id varchar(100) default NULL,
  debug_output text,
  line_id int(11) NOT NULL auto_increment,
  PRIMARY KEY  (line_id)
)
</code>```

Step 2: Create debug SPs to fill the debug table

```<code>DELIMITER $$

DROP PROCEDURE IF EXISTS `debug_insert` $$
CREATE PROCEDURE `debug_insert`(in p_proc_id varchar(100),in p_debug_info text)
begin
  insert into debug (proc_id,debug_output)
  values (p_proc_id,p_debug_info);
end $$

DROP PROCEDURE IF EXISTS `debug_on` $$
CREATE PROCEDURE `debug_on`(in p_proc_id varchar(100))
begin
  call debug_insert(p_proc_id,concat('Debug Started :',now()));
end $$

DROP PROCEDURE IF EXISTS `debug_off` $$
CREATE PROCEDURE `debug_off`(in p_proc_id varchar(100))
begin
  call debug_insert(p_proc_id,concat('Debug Ended :',now()));
  select debug_output from debug where proc_id = p_proc_id order by line_id;
  delete from debug where proc_id = p_proc_id;
end $$
</code>```

Step 3: Invoke the debug SPs in your trigger

Like this,

```<code>CREATE PROCEDURE test_debug()
begin
declare l_proc_id varchar(100) default 'test_debug';
  call debug_on(l_proc_id);
  call debug_insert(l_proc_id,'Testing Debug');
  call debug_off(l_proc_id);
end $$
</code>```

As a result the debug table would be filled as follows,

```<code>+------------------------------------+
| debug_output                       |
+------------------------------------+
| Debug Started :2006-03-24 16:10:33 |
| Testing Debug                      |
| Debug Ended :2006-03-24 16:10:33   |
+------------------------------------+
</code>```

Title: Debugging MySQL Triggers

Body:
I love triggers for one reason - they just work. I hate triggers for one reason - when they don't work, forget about trying to debug. O the sweet frustration.

Basically, I want to see THE update, delete, insert, etc query that was ran. I want to see that query ... somewhere, in my terminal or a log, exactly how and when MySQL executes it, and possibly any corresponding output/errors. Thoughts/hacks?

I'm trying to debug an update query with a few joins and what not. My queries are much more complex but for brevity here's an example.

DELIMITER |
CREATE TRIGGER ireallyhateyourightnow AFTER UPDATE ON watch_this_table
FOR EACH ROW BEGIN
 IF (OLD.my_value != NEW.my_value) THEN
  update
   my_table
  set
   my_column = NEW.my_value;
 END IF;
END|
DELIMITER ;

Here is some additional context that may help influence a suggestion or answer. Again, I'm less interested in semantics/syntax and more interested in seeing MySQL run the query but by all means, I'm open to anything at this point.

Strace does not work/show query.

Non-replicated environment BUT if the bin logs show trigger statements I will certainly set this up.

Does "show full processlist" show trigger execution and/or statements executed within (I never see them after running show full processlist as fast as perl can run it but I might just be missing it)?

General query log does not show these queries (certainly not the error log).

I'm not using aliases (anymore).

No syntax errors when creating the trigger.

The IF statement works.

When I insert the NEW values into a "test/temp" table and manually run the update query it works (I've even went so far as to actually inserting the whole update query)

I can't show you the query but as I just mentioned, it works when I run manually if that helps.

I've removed all erroneous characters, tabs, carriage returns, newlines, etc.

The MySQL socket would only show local connection/data but not MySQL internal workings, I think.

MyISAM so INNODB logs aren't an option

lsof didn't seem to show anything else to be of use.

I'm using MySQL 5.0.77 on CentOS 5.5.

Body:
There's an alternate way of testing it by having a temporary debug table. In the example here, they create it in an own debug database.

Step 1: Create a table

DROP TABLE IF EXISTS debug;
CREATE TABLE debug (
  proc_id varchar(100) default NULL,
  debug_output text,
  line_id int(11) NOT NULL auto_increment,
  PRIMARY KEY  (line_id)
)

Step 2: Create debug SPs to fill the debug table

DELIMITER $$

DROP PROCEDURE IF EXISTS `debug_insert` $$
CREATE PROCEDURE `debug_insert`(in p_proc_id varchar(100),in p_debug_info text)
begin
  insert into debug (proc_id,debug_output)
  values (p_proc_id,p_debug_info);
end $$

DROP PROCEDURE IF EXISTS `debug_on` $$
CREATE PROCEDURE `debug_on`(in p_proc_id varchar(100))
begin
  call debug_insert(p_proc_id,concat('Debug Started :',now()));
end $$

DROP PROCEDURE IF EXISTS `debug_off` $$
CREATE PROCEDURE `debug_off`(in p_proc_id varchar(100))
begin
  call debug_insert(p_proc_id,concat('Debug Ended :',now()));
  select debug_output from debug where proc_id = p_proc_id order by line_id;
  delete from debug where proc_id = p_proc_id;
end $$

Step 3: Invoke the debug SPs in your trigger

Like this,

CREATE PROCEDURE test_debug()
begin
declare l_proc_id varchar(100) default 'test_debug';
  call debug_on(l_proc_id);
  call debug_insert(l_proc_id,'Testing Debug');
  call debug_off(l_proc_id);
end $$

As a result the debug table would be filled as follows,

+------------------------------------+
| debug_output                       |
+------------------------------------+
| Debug Started :2006-03-24 16:10:33 |
| Testing Debug                      |
| Debug Ended :2006-03-24 16:10:33   |
+------------------------------------+


问:
Curl show real time loop using php
I am trying to show another page loop using CURL but its not show data at real time after loop finish output will show. I need this real time. check this example code. and if there is another way to do this please tell me. I don't want to show my loop page URL so i use Curl to do that if any other way you know please tell.

Output Page

```<code>$ch = curl_init('http://localhost/test/loop.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
echo $hasil = curl_exec ($ch);
curl_close ($ch);
?>
</code>```

Loop page

```<code> <?php
     $a = 1;
     while (true) {
         echo $a;
         $a++;
         sleep(1);
     }
?>
</code>```

答:
You can do this using output buffering.

```<code>$a = 1;
while(true){
    ob_start();
    echo $a;
    $a++;
    ob_flush();
    sleep(1);
}
</code>```

You will need to configure php to allow for this if you have not done so already. There are settings in the PHP ini for it. This answer will explain how to do this PHP echo-ing content as page loads

It is worth noting that the code above will cause a php timeout based on whatever you have set in the php.ini

Title: Curl show real time loop using php

Body:
I am trying to show another page loop using CURL but its not show data at real time after loop finish output will show. I need this real time. check this example code. and if there is another way to do this please tell me. I don't want to show my loop page URL so i use Curl to do that if any other way you know please tell.

Output Page

$ch = curl_init('http://localhost/test/loop.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
echo $hasil = curl_exec ($ch);
curl_close ($ch);
?>

Loop page

 <?php
     $a = 1;
     while (true) {
         echo $a;
         $a++;
         sleep(1);
     }
?>

Body:
You can do this using output buffering.

$a = 1;
while(true){
    ob_start();
    echo $a;
    $a++;
    ob_flush();
    sleep(1);
}

You will need to configure php to allow for this if you have not done so already. There are settings in the PHP ini for it. This answer will explain how to do this PHP echo-ing content as page loads

It is worth noting that the code above will cause a php timeout based on whatever you have set in the php.ini


问:
Where I can find build.gradle file in order to Add Support Libraries for android in eclipse?
they say go to https://developer.android.com/topic/libraries/support-library/setup.html and follow steps -->
1- OPEN build.gradle ,
I don't get it , Where I can find this file ?

I was thinking that they might mean the folder which consist of the application that I need the library for , but there is no such file in it

答:
In eclipse, we dont have provision of build.gradle file, it's only available in Android studio.
to add support library Using Eclipse follow below steps:

Create a library project based on the support library code:

Make sure you have downloaded the Android Support Library using the SDK Manager.

Create a library project and ensure the required JAR files are included in the project's build path:

Select File > Import.

Select Existing Android Code Into Workspace and click Next.

Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the cardview project, browse to /extras/android/support/v7/cardview/.

Click Finish to import the project. For the v7 cardview project, you should now see a new project titled android-support-v7-cardview.

In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the v7 cardview project, add the android-support-v7-cardview.jar file to the build path.

Right-click the library project folder and select Build Path > Configure Build Path.

In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the cardview project requires you to export the android-support-v7-cardview.jar file.

Uncheck Android Dependencies.

Click OK to complete the changes.

You now have a library project for your selected Support Library that you can use with one or more application projects.

Add the library to your application project:

In the Project Explorer, right-click your project and select Properties.

In the category panel on the left side of the dialog, select Android.

In the Library pane, click the Add button.

Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-cardview.

In the properties window, click OK.


问:
Python : Can I separately use maintain and install ANN libraries and Image processing libraries in same project on windows10
I want to use Opencv library for image processing which supports for python 2.7 and tensorflow library for ANN which supports for python 3.5 in the same project.But when I try to include opencv library after including tensor flow library in to pycharm,it shows an error.Is there any way to handle this problem?I have installed both python2.7 and python3.5 in my computer using anaconda.</p>

答:
Yes, you can use both. Any errors you get are due to a bad installation of either Tensorflow of OpenCV. Best would be to find out what the exact problem is and post a new question to describe that.

Also: it would be a good idea to use Docker to get an image with OpenCV and tensorflow already installed. This is one I like: https://github.com/pkmital/CADL/tree/master/#docker-installation. It really removes the dependency and installation problems!


问:
Simplest way of using Hibernate Sessions
I'm coaching a student project which uses hibernate as a persistence layer. From my projects at work I'm already quite familiar with hibernate and can use it with few 'troubles'. But with this project we have constantly problem with sessions, stale objects and and 'object was loaded from a different session'-errors.

So what I am looking for the simplest possible way to use sessions:

Ideal would be:

Sessions can be fetched from anywhere

It shouldn't matter whether or not a given object was loaded with session A and then updated with Session B

Its a single-process GUI application. The current setting for current_session_context_class is thread. But I use a static field for the session variable (which I think causes some of my troubles) and only fetch it ONCE.

Thanks for your assistance!

Cheers,
Reto

答:
Assuming you're not teaching ORM, the understanding of why these errors happen isn't part of the knowledge the students are supposed to come away with etc etc etc and you just want Hibernate to work as a database wrapper so they can get data to use while learning other things.

This is probably your best bet:

```<code>StatelessSession session = sessionFactory.openStatelessSession();
</code>```

A stateless session is effectively "auto-commit mode for ORM" and as close to raw-JDBC wrapper as hibernate gets.  No Sessions, no L1 caches, no persistence context.  Just SQL/HQL that returns objects.

Body:
Assuming you're not teaching ORM, the understanding of why these errors happen isn't part of the knowledge the students are supposed to come away with etc etc etc and you just want Hibernate to work as a database wrapper so they can get data to use while learning other things.

This is probably your best bet:

StatelessSession session = sessionFactory.openStatelessSession();

A stateless session is effectively "auto-commit mode for ORM" and as close to raw-JDBC wrapper as hibernate gets.  No Sessions, no L1 caches, no persistence context.  Just SQL/HQL that returns objects.