text:
Q: How can I call ActivateKeyboardLayout from 64bit Windows Vista using VBA Running VBA under XP I was able to call ActivateKeyboardLayout to switch my input language from English to another language. However, this no longer works under Vista64.
Any suggestions or workarounds?
The code that used to work under XP was similar to the following:
Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal HKL As Long, ByVal flags As Integer) As Integer
Const aklPUNJABI As Long = &H4460446
ActivateKeyboardLayout aklPUNJABI, 0

There was a suggestion to try
Public Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal nkl As IntPtr, ByVal Flags As uint) As Integer

When I try this I get the error message:
Variable uses an Automation type not supported in Visual Basic

A: Your declaration for the ActivateKeyboardLayout is actually incorrect. For 32-bit systems your code should be something like this:
Private Declare Function ActivateKeyboardLayout Lib "user32" (ByVal HKL As Long, _
    ByVal flags As Long) As Long

Const aklPUNJABI As Long = &H4460446
Dim oldLayout as Long
oldLayout = ActivateKeyboardLayout(aklPUNJABI, 0)
If oldLayout = 0 Then
   'Oops an error'
Else
   'Save old layout for later restore?'
End If

The 64-bitness of the operating system is a bit of a red herring in this case. Since you are running a VBA app it must be running as a 32-bit app regardless of OS. I suspect your problem may be that on your Vista system the Punjabi keyboard layout that you want is not loaded. ActivateKeyboardLayout will only work to activate a keyboard layout that is already loaded. For some reason the designers of this API felt that failure due to the keyboard layout not existing was not an error so the LastDllError is not set. You may want to look into using LoadKeyboardLayout for this type of situation.
EDIT: To double check that the keyboard layout you are trying to get is actually loaded you can use this:
Private Declare Function GetKeyboardLayoutList Lib "user32" (ByVal size As Long, _
    ByRef layouts As Long) As Long

Dim numLayouts As Long
Dim i As Long
Dim layouts() As Long

numLayouts = GetKeyboardLayoutList(0, ByVal 0&)
ReDim layouts(numLayouts - 1)
GetKeyboardLayoutList numLayouts, layouts(0)

Dim msg As String
msg = "Loaded keyboard layouts: " & vbCrLf & vbCrLf

For i = 0 To numLayouts - 1
   msg = msg & Hex(layouts(i)) & vbCrLf
Next

MsgBox msg

A: This is just a blind guess, but have you tried running your app as elevated administrator to see if it makes a difference? What's the error code / value of GetLastError?

A: Did you try a .Net line (as in VB.Net script or those snippets) like:
InputLanguage.CurrentInputLanguage =
    InputLanguage.FromCulture(New System.Globalization.CultureInfo("ar-EG"))

InputLanguage should be supported for Vista64 with a .Net3.5
VB.Net code:
Public Sub ChangeInputLanguage(ByVal InputLang As InputLanguage)
   If InputLanguage.InstalledInputLanguages.IndexOf(InputLang) = -1 Then
        Throw New ArgumentOutOfRangeException()
   End If
    InputLanguage.CurrentInputLanguage = InputLang
End Sub

A: For 64-bit portability you may need to use IntPtr. Can you give this a shot?
Public Declare Function ActivateKeyboardLayout Lib "user32" (ByVal nkl As IntPtr, ByVal Flags As uint) As Integer

A: In 64-bit editions of Office apps, VBA is indeed 64-bit. See Office 2010 documentation for details of the changes. For the example given in Stephen Martin's answer, you will need to change the code as follows to add the PtrSafe attribute and fixup the parameters that have a HKL type in the Win32 API:
Private Declare PtrSafe Function ActivateKeyboardLayout Lib "user32" (ByVal HKL As LongPtr, _
    ByVal flags As Long) As LongPtr

Const aklPUNJABI As LongPtr = &H4460446
Dim oldLayout as LongPtr
oldLayout = ActivateKeyboardLayout(aklPUNJABI, 0)
If oldLayout = 0 Then
   'Oops an error'
Else
   'Save old layout for later restore?'
End If

and
Private Declare PtrSafe Function GetKeyboardLayoutList Lib "user32" (ByVal size As Long, _
    ByRef layouts As LongPtr) As Long

Dim numLayouts As Long
Dim i As Long
Dim layouts() As LongPtr

numLayouts = GetKeyboardLayoutList(0, ByVal 0&)
ReDim layouts(numLayouts - 1)
GetKeyboardLayoutList numLayouts, layouts(0)

Dim msg As String
msg = "Loaded keyboard layouts: " & vbCrLf & vbCrLf

For i = 0 To numLayouts - 1
   msg = msg & Hex(layouts(i)) & vbCrLf
Next

MsgBox msg

A: The thing that everyone seems to overlook here is that you are working in VBA, not in .NET.  IntPtr is a .NET type which represents an integer which is native to the platform.  On a 32-bit platform it is 32 bits, on a 64 bit platform, it is 64 bits.
Given that an HKL is a typedef for a handle, which is a typedef for PVOID which is a typedef for VOID *, it's exactly what you need, if you were using .NET.
VBA doesn't have anything for 64-bit numbers, so you have to take a different approach.
On a 64-bit machine, you will have to do something like this:
Public Type HKL64
    High As Long
    Low As Long
End Type

Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    Byval HklHigh As Long, Byval HklLow As Long, _
    ByVal flags As Integer) As HKL64

This should allow you to pass a 64 bit value on the stack to the API function (across two variables).  However, if you are going to use this code on 64 bit and 32 bit machines, you are going to have to make two declarations of the API and then determine which one to call.
Also, any other code in VBA that calls APIs that deal with pointers or handles will have to be changed appropriately to handle 64 bit input (not 32).
On a side note, the original declaration of ActivateKeyboardLayout is wrong, as it had a return type of Integer, which is a 16-bit value, while the API returns a type of HKL, which is 32 or 64 bits, depending on the platform.


text:
Q: How can I make my Java Servlet class handle SAXException's? When compiling my Java Servlet code, I get the following error...
in javax.servlet.http.HttpServlet; overridden method does not throw org.xml.sax.SAXException

In my overridden doGet() function, I'm using JAXP to process XML which apparently requires me to handle SAXExceptions.  But when I tac "SAXExeption" onto the list of exception types I want my doGet function to handle, I get the above error.  How can I get my doGet function to hangle SAXExcpetions?
thanks in advance for all your help!

A: You can't declare an overriding method that throws checked exceptions that aren't thrown by the method being overridden.  In other words, since HttpServlet.doGet() is declared as throwing IOException and ServletException, you cannot use any other exception types in the throws clause of your doGet method.
However, you can wrap up the SAXException that you are getting as a ServletException to get around this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    try {
        JAXP.possiblyThrowASAXException();
    } catch (SAXException e) {
        throw new ServletException("JAXP had a parsing failure", e);
    }
}

A: When a parent class declares to throw a checked exception, subclasses have to throw at least the same checked exceptions to fulfill the contract of the parent class. The other way round, a child class method does not have to be declared to throw any exception, but it can't be declared to throw a checked exception that the parent class method is not declared to throw.
To illustrate this, lets imagine you have the following class:
package test;

import java.io.IOException;

public class Parent {
    void foo() throws IOException {
        throw new IOException();
    }
}

This would compile:
package test;

class Child1 extends Parent {
    void foo() {
    }
}

But this would not:
package test;

import org.xml.sax.SAXException;

class Child2 extends Parent
{
    void foo() throws SAXException {
        throw new SAXException();
    }
}

The javac compiler would generate the following output:
test/Child2.java:6: foo() in test.Child2 cannot override foo() in test.Parent; overridden method does not throw org.xml.sax.SAXException
    void foo() throws SAXException {
         ^
1 error

In other words, you can't write this:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, SAXException {
    super.doGet(req, resp);
    ...
}

You have to handle the SAXException in the doGet() method and to wrap it in a ServletException if you want to rethrow it.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    super.doGet(req, resp);

    try {
        // code that possibly throws a SAXException
        ...
    } catch (SAXException e) {
        // handle it or rethrow it as ServletException
        ...
    }
}

A: I agree with the answer by @David Winslow
When you throw an Exception in the doGet method of an HttpServlet you are essentially throwing up your hands and giving up any sensible error handling.
Its probably a better approach to trap the SAXException and emit an error which gives useful information.
Is the client sending you information in the get which is XML? If it is, you should probably respond with a sensible error telling them that their XML is incorrect.
Is this error caused by something loaded on the Server side? If it is then there's a basic problem with the get and the user should get an appropriate message for that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Hibernate good for batch processing? What about memory usage? I have a daily batch process that involves selecting out a large number of records and formatting up a file to send to an external system.  I also need to mark these records as sent so they are not transmitted again tomorrow.
In my naive JDBC way, I would prepare and execute a statement and then begin to loop through the recordset.  As I only go forwards through the recordset there is no need for my application server to hold the whole result set in memory at one time.  Groups of records can be feed across from the database server.
Now, lets say I'm using hibernate.  Won't I endup with a bunch of objects representing the whole result set in memory at once?

A: Hibernate does also iterate over the result set so only one row is kept in memory. This is the default. If it to load greedily, you must tell it so.
Reasons to use Hibernate:

*

*"Someone" was "creative" with the column names (PRXFC0315.XXFZZCC12)

*The DB design is still in flux and/or you want one place where column names are mapped to Java.

*You're using Hibernate anyway

*You have complex queries and you're not fluent in SQL

Reasons not to use Hibernate:

*

*The rest of your app is pure JDBC

*You don't need any of the power of Hibernate

*You have complex queries and you're fluent in SQL

*You need a specific feature of your DB to make the SQL perform

A: Hibernate offers some possibilities to keep the session small.
You can use Query.scroll(), Criteria.scroll() for JDBC-like scrolling. You can use Session.evict(Object entity) to remove entities from the session. You can use a StatelessSession to suppress dirty-checking. And there are some more performance optimizations, see the Hibernate documentation.

A: Hibernate as any ORM framework is intended for developing and maintaining systems based on object oriented programming principal. But most of the databases are relational and not object oriented, so in any case ORM is always a trade off between convenient OOP programming and optimized/most effective DB access.
I wouldn't use ORM for specific isolated tasks, but rather as an overall architectural choice for application persistence layer.

A: In my opinion I would NOT use Hibernate, since it makes your application a whole lot bigger and less maintainable and you do not really have a chance of optimizing the generated sql-scripts in a quick way.
Furthermore you could use all the SQL functionality the JDBC-bridge supports and are not limited to the hibernate functionality. Another thing is that you have the limitations too that come along with each layer of legacy code.
But in the end it is a philosophical question and you should do it the way it fits you're way of thinking best.

A: If there are possible performance issues then stick with the JDBC code.
There are a number of well known pure SQL optimisations which
which would be very difficult to do in Hibernate.
Only select the columns you use! (No "select *" stuff ).
Keep the SQl as simple as possible. e.g. Dont include small reference tables like currency codes in the join. Instead load the currency table into memory and resolve currency descriptions with a program lookup.
Depending on the DBMS minor re-ordering of the SQL where predicates can have a major effect on performance.
If you are updateing/inserting only commit every 100 to 1000 updates. i.e. Do not commit every unit of work but keep some counter so you commit less often.
Take advantage of the aggregate functions of your database. If you want totals by DEPT code then do it in the SQL with " SUM(amount) ... GROUP BY DEPT ".


text:
Q: Fixing Black tooltip background in windows 10 under Minimize/Maximize/Close There is a black background on tooltips. It occurs only on title bar Minimize/Maximize/Close option.
I have been facing this for over 2 years now without a solution.

A: We need to disable "Fade or slide ToolTips into view" to fix this issue in Windows 10.
Start -> System -> Display -> Advanced System Settings -> Settings (Under Performance) -> Custom -> Uncheck "Fade or slide ToolTips into view"


text:
Q: jquery Animate only once I have two radio buttons that, on click, display one of two content divs. Code for that:
$("input[name='registrationType']").click(function () {
    var registrationType = $(this).attr('id');
    if (!registrationType) {
        return;
    }
    $("#contributorForm, #studentForm").hide();
    if (registrationType == "Student") {
        $("#studentForm").show();
    } else if (registrationType == "Contributor") {
        $("#contributorForm").show();
    }
});

I wanted to add a simple animation, .show('slow') to this process. As I thought about it though, I realized I only wanted it to use the animation the first time one of the radio buttons is clicked. Is there a way to do this without having to put in some logic to determine if it's the first click (e.g. before my hide logic, check to see if they're both hidden, which is the "on load" state), then coding something like this:
if (registrationType == "Student") {
    if(firstClick) {
        $("#studentForm").show('slow');
    } else {
        $("#studentForm").show();
    }
}

Just seems like a lot of extra code for something that is relatively simple.

A: Working Solution
$("input[name='registrationType']").click(function() {
   var regType = $(this).attr('id');
   if (!regType) return;

   $('div[id$="Form"]').hide();
   var contro = $('div[id^="' + regType.toLowerCase() + '"]');
   if ($(contro).attr("data") != null) $(contro).show();
   else $(contro).show('slow');
   $('div[id$="Form"]').attr("data", "shown");
});

The Demo on jsFiddle.net.
Hope this helps you.


text:
Q: Play a list of image urls as a video in html5 I have a list of image urls that are backups images taken from a security camera.  They are served behind an nginx proxy.
Is there a way to play the images as if they were a video?  I am currently appending 10 images at a time to a div and using the z-index to display one at a time.
But I want a better way, that lets me use the built in  controls.
Here is a sample of my data:
["http://0.0.0.0:7733/1/2/2018-08-14_18-44-51.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-52.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-53.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-54.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-55.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-56.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-57.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-58.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-44-59.jpg", "http://0.0.0.0:7733/1/2/2018-08-14_18-45-00.jpg"]

A:
Is there a way to play the images as if they were a video?

Not directly, no.  You would have to create a video and either load it via MediaSource Extensions or as a regular Blob.  That's going to require a codec and what not, since your source format is JPEG.

But I want a better way, that lets me use the built in controls.

Emulating controls of a video player is going to be much easier than messing with a video.

using the z-index to display one at a time

I'd use visibility: hidden instead.  If you just have a bunch of images stacked and are changing the z-index, you're likely creating a lot of work for the browser as it's going to put these on different layers and composite them all together later, even if a particular frame isn't seen.  (Check the performance in your developer tools, experiment, and see.)
If you really want to create a video out of these, it is possible but a bit nasty:

*

*Create a canvas element.

*Use CanvasCaptureMediaStream to get a MediaStream from the canvas contents.

*Use MediaRecorder to record that MediaStream into something manageable, like a VP9 video in WebM.

Even after that, you're going to have to hack the resulting WebM a bit to get it to play in-browser, but it will work.


text:
Q: d3js step-after line graph - highlight line between two points on mouseover I am new to D3JS and created step-after line graph as shown below. Now I want to add mouseover effect to the graph. When the user mouseovers horizontal step-line, it should highlight in different color (as shown in green color in image) and also show tool tip.
I have been doing some research on this and so far I have found the examples where it changes dot (at line intersection) color on mouseover. But I have not found any example to highlight step line itself.
I would appreciate if someone can point me in right direction or provide examples. Thank you.
  var line = d3.svg.line()
                .interpolate("step-after")
                .x(function(d) { return x(d.timestamp); })
                .y(function(d) { return y(d.score); });

  svg.append("path")
          .datum(data)
          .attr("class", "lineblue")
          .attr("d", line);

A: Based on @JSBob's comment, I added another line to overlay on top of original step-line on mouseover. Below is final outcome.

  var bisectDate = d3.bisector(function(d) { return d.start; }).left,

   var highlightLine = d3.svg.line()
                        .x(function(d) { return x(d.start); })
                        .y(function(d) { return y(d.score); });

   var highlight = focus.append("g")
                      .style("display", "none");

   var highlightPath = highlight.append("path")
                         .attr("class", "highlightgreen");

   focus.on("mouseover", mouseover)
         .on("mouseout", function() {
                   highlight.style("display", "none");
                    tooltip.style("display", "none");
         });

   var tooltip = d3.select("body").append("div")
                  .attr("class","tooltip")
                   .style("display", "none");
    function mouseover() {
          var highlightData = [];
          var x0 = x.invert(d3.mouse(this)[0]);
          var i = bisectDate(appData, x0, 1);
          var d0 = appData[i - 1];
          highlightData.push({ start: d0.start, score: d0.score});
          highlightData.push({ start: d0.end, score: d0.score});
          highlight.style("display", "block")
                       .select("path")
                           .attr("class", "highlightgreen")
                            .attr("d",highlightLine(highlightData));

         var tooltipX =  (x(d0.end) - x(d0.start))/2 + x(d0.start) + 26;
         var tooltipY = y(d0.score) - 12;
         tooltip.html('Test')
                   .style("left", tooltipX + "px")
                   .style("top", tooltipY + "px")
                   .style("display","block");

      }


text:
Q: Setting Spinner by name can any one tell hw to set a spinner by name..
The scenario is like this,
Spinner contains three elements "one","two","three". After clicking the spinner im storing that  in shard pref say "two"
Now i wan to set to that spinner again to "two", if i open that activity again.
Array of the elements is in values/arrays

A: Rather than storing the string value in your SharedPreferences, store the position within the array as an integer. Then you just call Spinner.setSelection(int position) with that value.


text:
Q: Taskbar and desktop refreshing I have an issue that my HP 650 laptop is doing refreshing of taskbar and desktop in every 2 minutes.
When refreshing the icons from the taskbar are disappearing for 1-2 second and then again shown.
What can be the reason of this problem and how can I solve it?
Thanks.

A: I'd suggest updating the display driver for your laptop but it could be malware as well.  I can suggest malware removal tools but try the display driver(s) first.

A: This is often caused by (surprisingly) Norton AntiVirus installed on the machine by the factory image!
If you:

*

*Start your Windows 8 computer but DON'T click to go to "Desktop" view

*Immediately start typing "Programs and features"

*Open "Programs and features" - so you can see your list of installed programs

*Uninstall anything "Norton" related

*Complete the uninstall by rebooting your computer

*Live a hassle-free life with Windows 8.


text:
Q: Google Maps click event on route I'm trying to draw a circle wherever I click on the route. I looked for a solution on how to make a route clickable and couldn't find anything helpful... Below is my code. I get no errors when I click on the route but no circle is created.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

//direction service request here...

google.maps.event.addListener(directionsDisplay, 'click', function(event) {

var routeClick = new google.maps.Circle({
  center: event.latLng, //center where you click
  radius: 500,
  strokeColor: "#0000FF",
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: "#0000FF",
  fillOpacity: 0.4
});

routeClick.setMap(map);

});

UPDATE:
Working code to create your own directions polyline based on Geocodezip's script http://www.geocodezip.com/v3_directions_custom_iconsC.html and official API example https://developers.google.com/maps/documentation/javascript/examples/elevation-paths
    // Draw the path
    function drawPath(path) {
      // Display a polyline of the elevation path.
      var pathOptions = {
        path: path,
        strokeColor: '#0000CC',
        strokeWeight: 5,
        opacity: 0.4,
        map: map
      }
      routePolyline = new google.maps.Polyline(pathOptions);
    }

then in the directionService request I added
directionService.route(request, function(result, status) {
  var path = result.routes[0].overview_path;
  drawPath(path);
});

A: There is no 'click' event on the DirectionsRenderer
you can render the polyline yourself and add a click event listener to it or add a click listener to the map.
Example of a custom directions renderer
proof of concept fiddle
code snippet:

var infowindow = new google.maps.InfoWindow();
var directions = new google.maps.DirectionsService();
var renderer = new google.maps.DirectionsRenderer({
  suppressPolylines: true,
  infoWindow: infowindow,
});
var map;

function initialize() {
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(40.7482333, -73.8681295),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  google.maps.event.addDomListener(document.getElementById('go'), 'click',
    route);

  var input = document.getElementById('from');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);
  route();
}

function route() {
  var request = {
    origin: document.getElementById('from').value,
    destination: '51 St, New York, NY 10022, USA',
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  var panel = document.getElementById('panel');
  panel.innerHTML = '';
  directions.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      renderer.setDirections(response);
      renderer.setMap(map);
      renderer.setPanel(panel);
      renderDirectionsPolylines(response);
      console.log(renderer.getDirections());
    } else {
      renderer.setMap(null);
      renderer.setPanel(null);
    }

  });

}

var polylineOptions = {
  strokeColor: '#C83939',
  strokeOpacity: 1,
  strokeWeight: 4
};
var polylines = [];
function renderDirectionsPolylines(response) {
  for (var i=0; i<polylines.length; i++) {
    polylines[i].setMap(null);
  }
  var legs = response.routes[0].legs;
  for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      var stepPolyline = new google.maps.Polyline(polylineOptions);
      for (k = 0; k < nextSegment.length; k++) {
        stepPolyline.getPath().push(nextSegment[k]);
      }
      polylines.push(stepPolyline);
      stepPolyline.setMap(map);
      // route click listeners, different one on each step
      google.maps.event.addListener(stepPolyline, 'click', function(evt) {
        infowindow.setContent("you clicked on the route
" + evt.latLng.toUrlValue(6));
        infowindow.setPosition(evt.latLng);
        infowindow.open(map);
      })
    }
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
  color: black;
  font-family: arial, sans-serif;
  font-size: 13px;
}
#map {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 50%;
}
#panel-wpr {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  right: 0;
  overflow: auto;
}
#panel {
  font-family: arial;
  padding: 0 5px;
}
#info {
  padding: 5px;
}
#from {
  width: 90%;
  font-size: 1.2em;
}
.adp-directions {
  width: 100%;
}
.input {
  background-color: white;
  padding-left: 8px;
  border: 1px solid #D9D9D9;
  border-top: 1px solid silver;
  -webkit-border-radius: 1px;
  -moz-border-radius: 1px;
  border-radius: 1px;
}
.time {
  margin: 0;
  height: 17px;
  border: 1px solid;
  border-top-color: #CCC;
  border-right-color: #999;
  border-left-color: #999;
  border-bottom-color: #CCC;
  padding: 2px 15px 1px 1px;
}
button {
  border: 1px solid #3079ED;
  color: white;
  background-color: #4D90FE;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#4D90FE), to(#4787ED));
  background-image: -webkit-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -moz-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -ms-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -o-linear-gradient(top, #4D90FE, #4787ED);
  background-image: linear-gradient(top, #4D90FE, #4787ED);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorStr='#4d90fe', EndColorStr='#4787ed');
  display: inline-block;
  min-width: 54px;
  text-align: center;
  font-weight: bold;
  padding: 0 8px;
  line-height: 27px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  -webkit-transition: all 0.218s;
  -moz-transition: all 0.218s;
  -o-transition: all 0.218s;
  transition: all 0.218s;
}
#info div {
  line-height: 22px;
  font-size: 110%;
}
.btn {} #panel-wpr {
  border-left: 1px solid #e6e6e6;
}
#info {
  border-bottom: 1px solid #E6E6E6;
  margin-bottom: 5px;
}
h2 {
  margin: 0;
  padding: 0;
}

<title>Google Maps JavaScript API v3 Example: Transit</title>

  <button id="transit">Toggle transit layer</button>

      from:
      <input class="input" id="from" value="Grand Central 42, NY">

      to:
      51 St, New York, NY 10022, USA

      <button id="go">Get Directions</button>


text:
Q: Почему не работает изменение и удаление в SQLite? Пишу код на Python и SQLite. В двух функциях мне нужно сделать удаление и обновление данных соответственно. Код на Python отлично работает, а вот алгоритм на SQLite не работает, так как никаких изменений в базе данных не происходит. Можно ли как-то исправить проблему?
def dell(self):
    for y in range(1, self.kol + 1):
        exec('if self.checkBox_{}.isChecked():\n\t'.format(y) +\
             'self.checkBox_{}.setCheckState(False)\n\t'.format(y) +\
             'self.gridLayout_1.removeWidget(' + 'self.widget_{})'.format(y) +\
             'or self.gridLayout_2.removeWidget(' + 'self.widget_{})\n\t'.format(y) + \

             'cur = self.con.cursor()\n\t' + \
             'sql = """DELETE FROM Задачи WHERE Название = ?"""\n\t' +\
             'rezult = cur.execute(sql, ("self.widget_{}".format(y),))\n\t' +\

             'self.widget_{}.hide()\n\t'.format(y) + \

             'self.kol -= 1\n\t' +\
             'self.kol_1 -= 1')

def yes(self):
    for i in range(1, self.kol + 1):
        exec('if self.checkBox_{}.isChecked():\n\t'.format(i) +\
             'self.widget_{}.setStyleSheet(self.green)\n\t'.format(i) +\
             'self.checkBox_{}.setCheckState(False)\n\t'.format(i) +\
             'cur = self.con.cursor()\n\t' +\
             'sql = """UPDATE Задачи SET Статус = ? WHERE ID = ?"""\n\t' +\
             'rezult = cur.execute(sql, (str(self.green), str(i)))')

A: con.commit() забыли
функция сохраняет текущую транзакцию в БД


text:
Q: After upgrade to Django 1.11 site doesn't work in Chrome I face strange problem. When running django development server I cant display pages in Chrome but I can in FireFox and MsEdge. The server returns 200 response, so page should be displayed. I did not touch any options related to security. Chrome stucks on spinning wheel, and no other information is available, no timeout, no errors.
Django 1.11.7 here. Its not just my PC I tested on few others.
Do not hasitate to comment as it could lead us to an answer.
EDIT: Chome devop tools shows following error in console:
net::ERR_CONTENT_LENGTH_MISMATCH

A: The error was related to changes in 1.11 covering CommonMiddleware (see release notes)
It seems like Firefox is just ignoring mismatched Content-Length declarated in header (in opposition to Chrome). I resolved issue by changing order/recreating my middlewares to prevent modifing content after calculation of content-length.
For more info you can visit: https://code.djangoproject.com/ticket/28786


text:
Q: IE ActiveX' FileSystemObject - how to read local file with JS - help I am studying the FileSystemObject... The thing is I couldn't find any code snippets which show some conceptions as

*

*A) JS local File reading as binary stream

*B) encode the stream to base64

*C) images reading examples

So if you know some useful web resources to share links or you can share some code snippets it will be much appreciated :)

A: I have had the desire to do the same thing. :D Your welcome to do this, but unfortunately IE8/IE9 fails to provide realistic access to the file system through activeX.  Theoretically you can enable the option in the settings, but it constantly warns you of inadequate security settings.

WARNING Your browser has ......etc.

As an alternative I would advise using Java.  http://www.tiddlywiki.com/  Has the basis Java -> javascript interaction to mess with the file system.  The code isn't great quality but definitely has the the potential for a good intro.  As an added bonus Java works across OSs.


text:
Q: Bug in python thread I have some raspberry pi running some python code.  Once and a while my devices will fail to check in.  The rest of the python code continues to run perfectly but the code here quits.  I am not sure why?  If the devices can't check in they should reboot but they don't.  Other threads in the python file continue to run correctly.
class reportStatus(Thread):
    def run(self):
        checkInCount = 0
        while 1:
            try:
                if checkInCount < 50:
                    payload = {'d':device,'k':cKey}
                    resp = requests.post(url+'c', json=payload)
                    if resp.status_code == 200:
                        checkInCount = 0
                        time.sleep(1800) #1800
                    else:
                        checkInCount += 1
                        time.sleep(300) # 2.5 min
                else:
                    os.system("sudo reboot")
            except:
                try:
                    checkInCount += 1
                    time.sleep(300)
                except:
                    pass

The devices can run for days and weeks and will check in perfectly every 30 minutes, then out of the blue they will stop.  My linux computers are in read-only and the computer continue to work and run correctly.  My issue is in this thread.  I think they might fail to get a response and this line could be the issue
resp = requests.post(url+'c', json=payload)

I am not sure how to solve this, any help or suggestions would be greatly appreciated.
Thank you

A: Your code basically ignores all exceptions. This is considered a bad thing in Python.
The only reason I can think of for the behavior that you're seeing is that after checkInCount reaches 50, the sudo reboot raises an exception which is then ignored by your program, keeping this thread stuck in the infinite loop.
If you want to see what really happens, add print or loggging.info statements to all the different branches of your code.
Alternatively, remove the blanket try-except clause or replace it by something specific, e.g. except requests.exceptions.RequestException

A: A bare except:pass is a very bad idea.
A much better approach would be to, at the very minimum, log any exceptions:
import traceback

while True:
  try:
    time.sleep(60)
  except:
    with open("exceptions.log", "a") as log:
      log.write("%s: Exception occurred:\n" % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
      traceback.print_exc(file=log)

Then, when you get an exception, you get a log:
2016-12-20 13:28:55: Exception occurred:
Traceback (most recent call last):
  File "./sleepy.py", line 8, in <module>
    time.sleep(60)
KeyboardInterrupt

It is also possible that your code is hanging on sudo reboot or requests.post. You could add additional logging to troubleshoot which issue you have, although given you've seen it do reboots, I suspect it's requests.post, in which case you need to add a timeout (from the linked answer):
import requests
import eventlet
eventlet.monkey_patch()

#...
resp = None
with eventlet.Timeout(10):
    resp = requests.post(url+'c', json=payload)
if resp:
    # your code

A: Because of the answers given I was able to come up with a solution.  I realized requests has a built in time out function.  The timeout will never happen if a timeout is not specified as a parameter.
here is my solution:
resp = requests.post(url+'c', json=payload, timeout=45)

You can tell Requests to stop waiting for a response after a given
  number of seconds with the timeout parameter. Nearly all production
  code should use this parameter in nearly all requests. Failure to do
  so can cause your program to hang indefinitely

The answers provided by TemporalWolf and other helped me alot.  Thank you to all that helped.


text:
Q: Dafny insufficient reads clause to read array element datatype MSG_CMD = Empty| ReqS| ReqE| Inv| InvAck| GntS| GntE
type NODE=nat
type DATA=nat
type boolean=bool
class  class_0  {
var
Data : DATA,
Cmd : MSG_CMD
}

class  class_1  {
var
Data : DATA,
State : CACHE_STATE
}
class TopC{
var Cache : array<class_1 > }

predicate  inv__1(top:TopC,N1:nat,p__Inv0:nat, p__Inv2:nat)
  reads top
  reads top.Cache[p__Inv0]
  eads top.Cache[p__Inv2]
  requires top.Cache.Length ==N1
  requires N1>0
  requires top.Cache.Length ==N1
  requires N1>0
  requires 0<= p__Inv0<N1
  requires 0<= p__Inv2<N1
  {
(!((top.Cache[p__Inv2].State == E) && (!(top.Cache[p__Inv0].State == I))))
}

This is my test code,when i compile it ,find the error:insufficient reads clause to read array element on the line "reads top.Cache[p__Inv0]" ,I don't understand where i do wrong,is the reads annotation can not be used in the array's item?

A: A function (including a predicate, which is a function that returns a bool) must declare the objects on whose state it depends. Predicate inv__1 depends on

*

*the state of object top, because the function uses the .Cache field of that object

*the state of array top.Cache, because the function uses the elements of that array

*the state of the objects top.Cache[p__Inv2] and top.Cache[p__Inv0], because the function uses the .State field of those objects

So, the function needs the following read frame:
reads top
reads top.Cache
reads top.Cache[p__Inv0], top.Cache[p__Inv2]

It's the second one of these that your program is missing.
If you never intend to change the Cache array itself, you can declare it as constant-after-construction:
const Cache: array<class_1>

Then, you don't need to include top.Cache in the read frame.


text:
Q: If array equal array PHP Is possible to make if($array1[0]=>somevalue == $array2[0]=>somevalue){echo true;}else{echo false;}? because I cant make it work, can you help me please,
Example:
    $array1([0] => 'Joe', [2] => 'Pairs');
    $array2([0] => 'info' => array([0] => 'joe'));
foreach($array2->info as $info){
    foreach($array1 as $name){
        if($name == $info[0]){
             echo 'true';
           }
           else{
             echo 'false';
           }
      }
  }

And this is the real code,
The arrays:
 Array
(
[0] => SimpleXMLElement Object
    (
        [companyLocationInfo] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [companyName] => AVIS
                        [name] => NYCC07
                        [line1] => 420 EAST 90TH STREET
                    )
                [2] => SimpleXMLElement Object
                    (
                        [companyName] => AVIS
                        [name] => NYCC06
                        [line1] => 310 EAST 64TH STREET
                    )
                [3] => SimpleXMLElement Object
                    (
                        [companyName] => AVIS
                        [name] => NYCC01
                        [line1] => 68 EAST 11TH STREET
                    )

            )

        [rates] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [pickupDropoffLocations] => Array
                            (
                                [0] => SimpleXMLElement Object
                                    (
                                        [companyName] => AVIS
                                        [name] => NYCC07
                                    )
                            )
                        [vehicleRentalPrefType] => CCAR
                        [rateAmount] => 83.99
                        [rateCurrency] => USD
                    )
                [2] => SimpleXMLElement Object
                    (
                        [pickupDropoffLocations] => Array
                            (
                                [0] => SimpleXMLElement Object
                                    (
                                        [companyName] => AVIS
                                        [name] => NYCC06
                                    )
                            )
                        [vehicleRentalPrefType] => CCAR
                        [rateAmount] => 110.54
                        [rateCurrency] => USD
                    )
                [3] => SimpleXMLElement Object
                    (
                        [pickupDropoffLocations] => Array
                            (
                                [0] => SimpleXMLElement Object
                                    (
                                        [companyName] => AVIS
                                        [name] => NYCC01
                                    )
                            )
                        [vehicleRentalPrefType] => CCAR
                        [rateAmount] => 210.65
                        [rateCurrency] => USD
                    )

            )

    )

)
and this is the code:
$results_array = array();

foreach($result[0]->rates as $rate) {
    foreach($result[0]->companyLocationInfo as $info) {
        if($info->name == $rate->pickupDropoffLocations[0]->name) {
            $results_array[] = array(
                'line1' => $info->line1,
                'name' => $info->locationDetails->name,
                'companyName' => $info->companyName,
                'vehicleRentalPrefType' => $rate->vehicleRentalPrefType
            );
        }
    }
}
print_r($results_array);

Thank you.

A: What you're trying to do should be possible. If the code above is what you're actually trying to run, then your first problem is that you're comparing the values "Joe" and "joe" and those are not the same.
If you want a case-insensitive comparison, use if (strcasecmp($var1, $var2) == 0) (it returns zero if the two strings are the same, without considering case).


text:
Q: Concatenate rows in pandas based on condition I am trying to concatenate the rows that do not start with a specific character ('[') to the closest row that starts with it. I have read the txt file as following:
,
and I expect to get
.

A: Let us do
s=df.groupby(df.text.str.startswith('[').cumsum()).agg(' ',join)

A: You can use str[0] to check for the first character, then cumsum to mark the blocks:
df['text'].groupby(df['text'].str[0].eq('[').cumsum()).agg(' '.join)

Output:
text
1            [aaa] sss
2    [bbb] mmm fff ppp
3        [iii] rrr qqq
4            [ggg] kkk
Name: text, dtype: object


text:
Q: Is it possible to see all the variable and its value stored in browser momory? I would like to know the way to see all the variables and its saved values in google chrome using 'developer tool'. Can anybody help me..

A: It's a little hard to navigate, but if you're using chrome:
F12 -> Elements -> (in the bottom right) Properites shows you all available nodes and their values.

A: I am guessing you mean variables from your JavaScript file?
If yes, you can use debugger.

*

*Open Dev Tools F12

*Select Tab "Sources"

*Find a .js file you want to debug

*Put a breakpoint after a variable declaration

*Refresh and you will see values of declared variables in scope.

More about this:
https://developers.google.com/web/tools/chrome-devtools/debug/breakpoints/?hl=en
https://scotch.io/tutorials/debugging-javascript-with-chrome-devtools-breakpoints


text:
Q: How to put a logo on the left top with float? I want to have my logo (text logo, no image) on the left top in the navigation bar, but I can't make it.. I tried it with float:left and it dosen't work, I dont know why.
CSS code of the Navigation bar and content:
#top, #middle, bottom {width: 100%; position: relative;}
#top {top: 0; background: #171717;}
#nav {width: 900px; color: #fff; position: relative; margin: 0 auto;}
#nav li {display: inline-block; width: 100px; text-align: center; line-height: 50px;}
#middle {min-height: 100px; height: auto;}
#content {width: 800px; position: relative; margin: 0 auto;}

A: I am going to give a basic idea to you. Update your code like below.

Sample

Home

Simplefinite

Root

Now you have to work on the alignment on the logo.

A: #nav {
width: 900px;
color: #fff;
position: relative;
margin: 0 auto;
}

REMOVE width:900px;
 #nav {
color: #fff;
position: relative;
margin: 0 auto;
}

A: try this code
DEMO
HTML

logotext

Home

Simplefinite

Root

                Content

                dimasite.tk made by C0R3G4M3R.

CSS
body, html {
    background: none repeat scroll 0 0 #fff;
    font-family: Tahoma,Arial;
    margin: 0;
    padding: 0;
}
#top, #middle, bottom {
    position: relative;
    width: 100%;
}
#top {
    background: none repeat scroll 0 0 #171717;
    top: 0;
}
.logo {
    position: relative;
  color: #fff;
  width: 150px;
  float:left;
  margin-top:16px;
}
#nav {
    color: #fff;
    margin: 0 auto;
    position: relative;
    width: 900px;
}
#nav li {
    display: inline-block;
    line-height: 50px;
    text-align: center;
    width: 100px;
}
#nav li a {
    color: #fff;
    text-decoration: none;
}
#nav li:hover {
    background: none repeat scroll 0 0 #ff9900;
}
#middle {
    height: auto;
    min-height: 100px;
}
#content {
    margin: 0 auto;
    position: relative;
    width: 800px;
}
#content a {
    color: #000;
    text-decoration: none;
}
#content a:hover {
    color: #ff9900;
}
#bottom {
    background: none repeat scroll 0 0 #ff9900;
    bottom: 0;
    height: auto;
    min-height: 100px;
    top: 5px;
}
#footer {
    color: #fff;
    margin: 0 auto;
    padding: 40px 5px 5px;
    position: relative;
    width: 800px;
}
#footer a {
    color: #fff;
    text-decoration: none;
}
#footer a:hover {
    color: #000;
}


text:
Q: Clang modifies return value in destructor? While trying to write a class that times the duration between calling it's constructor and destructor, I ran into what I think is a bug in clang. (Edit: it's not a bug; it's implementation defined copy elision)
The timer struct below keeps a pointer to the duration object that's passed in as reference and adds the duration of the scope to this.
#include <iostream>
#include <chrono>
struct timer {
    using clock      = std::chrono::high_resolution_clock;
    using time_point = clock::time_point;
    using duration   = clock::duration;
    duration* d_;
    time_point start_;
    timer(duration &d) : d_(&d), start_(clock::now()) {}
    ~timer(){
        auto duration = clock::now() - start_;
        *d_ += duration;
        std::cerr << "duration: " << duration.count() << std::endl;
    }
};

timer::duration f(){
    timer::duration d{};
    timer _(d);
    std::cerr << "some heavy calculation here" << std::endl;
    return d;
}

int main(){
    std::cout << "function: " << f().count() << std::endl;
}

When compiling this with clang 7.0.0, the output is:
some heavy calculation here
duration: 21642
function: 21642

while for g++ 8 the output is
some heavy calculation here
duration: 89747
function: 0

In this case I do like clangs behavior, but from what I've found elsewhere the return value is supposed to be copied before destructors are run.
Is this a bug with Clang? Or does this depend on (implementation defined?) return value optimization?
The behavior is the same independent of whether the duration d in timer is a pointer or a reference.
--
I do realise that the compiler inconsistency can be solved by changing f so that the scope of the timer ends before the return, but that's beside the point here.
timer::duration f(){
    timer::duration d{};
    {
        timer _(d);
        std::cerr << "some heavy calculation here" << std::endl;
    }
    return d;
}

A: Short answer: due to NRVO, the output of the program may be either 0 or the actual duration. Both are valid.

For background, see first:

*

*in C++ which happens first, the copy of a return object or local object's destructors?

*What are copy elision and return value optimization?
Guideline:

*

*Avoid destructors that modify return values.
For example, when we see the following pattern:
T f() {
    T ret;
    A a(ret);   // or similar
    return ret;
}

We need to ask ourselves: does A::~A() modify our return value somehow? If yes, then our program most likely has a bug.
For example:

*

*A type that prints the return value on destruction is fine.

*A type that computes the return value on destruction is not fine.


text:
Q: PHP Abbreviated month name I am trying to use dates with abbreviated months in php. I've already tried d ([.\t-])* m Y found on their documentation but what I am getting is this 20 ([.    -])* 01 2016
How can I use abbreviated months like 10 Jan 2016 in PHP?

A: Today's answer was brought to you by the letter M (capital) and a link to the docs http://php.net/manual/en/function.date.php

A: Here's I found it, even thought it's really late but maybe someone needs it
basic
date('M',strtotime($dateValue))

https://www.w3resource.com/php/function-reference/date.php

A: Just use the substring function:
substr($month,0,3);


text:
Q: Can I use ardent in laravel to validate fields that I don't want it to save? I want Ardent to check that password and password confirmation match...yet, I obviously don't want to store password confirmation in the database.  So how do I get Ardent to do it's stuff and validate but not try to save the password confirmation?
Note:  the validation is failing anyway as it is not seeing the password_confirmation property value.  I imagine it's looking for it under the model attributes, whereas I have just set it as a private property.  If I set it as the model's attribute though, it will try to save this to the database.
public static $rules = array(
        'email' => 'required|email',
        'first_name' => 'required|alphaNum|min:3',
        'surname' => 'required|alphaNum|min:3',
        'password' => 'required|alphaNum|min:6|confirmed',
        'password_confirmation' => 'required'
);

//user object gets populated
$this->save();

A: You give your class a property of
public $autoPurgeRedundantAttributes = true;

And that automatically purges any properties not used in the database, see here.


text:
Q: Spring Framework - Kotlin - Save Entity to XML I would like to create an XML file in the Spring Framework at the push of a button and download it.
This file should be downloaded from an existing entity.
Unfortunately I can't find anything about how this works with Kotlin and the Spring Framework.
Can someone show me an example here?
I have tried https://grokonez.com/kotlin/kotlin-convert-kotlin-object-xml-file-xml-string-jackson but unfortunately it does not work.

A: Jackson-dataformat-xml is a good option.
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.io.File

class XmlMapperTest {
    @Test
    fun serializeToXml() {
        val xmlMapper: XmlMapper = XmlMapper()

        val car1 = Car(-1, "UAZ", CarColor.GREEN)

        val xml: String = xmlMapper.writeValueAsString(car1)

        assertEquals("<Car><id>-1</id><model>UAZ</model><color>GREEN</color></Car>", xml)

        File("F:/car1.xml").writeText(xml)
    }

    data class Car(
            val id: Long,
            val model: String,
            val color: CarColor
    )

    enum class CarColor {
        GREEN, RED
    }
}


text:
Q: How calc intersection plane and line (Unity3d) I try calc intersection plane and line, but I think get wrong result.
try this code (get from http://wiki.unity3d.com/index.php/3d_Math_functions):
public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint)
{
    float length;
    float dotNumerator;
    float dotDenominator;
    Vector3 vector;
    intersection = Vector3.zero;

    //calculate the distance between the linePoint and the line-plane intersection point
    dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal);
    dotDenominator = Vector3.Dot(lineVec, planeNormal);

    if (dotDenominator != 0.0f)
    {
        length = dotNumerator / dotDenominator;

        vector = SetVectorLength(lineVec, length);

        intersection = linePoint + vector;

        return true;
    }

    else
        return false;
}

A:
but I think get wrong result.

Can you be more specific?
The equation you're using seems correct; although I would use lineVec.noramlized * length instead of that weird SetVectorLength function.
The basic equation for the intersection of a line and plane is point x on the line, where the value is x is given by:
a = (point_on_plane - point_on_line) . plane_normal
b = line_direction . plane_normal

if b is 0: the line and plane are parallel
if a is also 0: the line is exactly on the plane
otherwise: x = a / b

Therefore the point of intersection is: x * line_direction + line_point
This is exactly what your code does though... so...?
You can read more details on the wiki page here:
https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection
Edit: Actually, it looks like this code assumes that if the dotDenominator is zero they do not intersect; partially true; if the dotNumerator is also zero the line is exactly on top of the plane, and all points intersect, so take whatever point you want as the intersection (eg. planePoint).


text:
Q: Prime Ideal and Proper Ideal Could someone please explain to me the definition of a prime ideal and a proper ideal. I honestly do not understand this concept.
If possible please explain your version of the definition in the most brain dead way possible. Imagine you are trying to explain this to a little kid, how you would help him understand the concept. I just need a clear and meaningful explanation.
I hope someone will help. Thank you.

A: Here's an answer in the simplest terms I can manage, using the set (ring) $\mathbb{Z}$ of integers as an example. I'll assume you know what an ideal is.
$3 \mathbb{Z} = \{ \ldots -3, 0, 3, 6, \ldots \}$ is an ideal in $\mathbb{Z}$. It's proper because is isn't all of $\mathbb{Z}$. The only ideal of $\mathbb{Z}$ that isn't proper is $\mathbb{Z}$ itself.
For any integer $n$, the set  $n\mathbb{Z}$ of multiples of $n$ is an ideal. It's a proper ideal unless $n = \pm 1$.
The idea of a prime ideal is a little more complicated. The ring of integers is a very nice ring with a very nice property you know about from elementary school: every integer is uniquely the product of prime integers. The proof of that fact depends on a simpler fact: whenever a prime number $p$ divides a product of two numbers it must divide one or the other (or both).
Now let's see what that says about the ideal $p\mathbb{Z}$ when $p$ is a prime number. Suppose $ab \in p\mathbb{Z}$. Then $p$ divides $a$ or $b$ (or both), so $a$ or $b$ (or both) is in $p\mathbb{Z}$.
That's the motiviation for this definition: an ideal $I$ is prime provided that whenever $ab \in I$, one or both of $a$ and $b$ is in $I$.
For the ring of integers, $n\mathbb{Z}$ is a prime ideal just when $n$ is a prime number.
For more general rings, you may not be able to say nice things about prime elements, but can prove theorems about prime ideals. That's why you make that definition.
The wikipedia page https://en.wikipedia.org/wiki/Prime_ideal has examples from other rings.
I don't know whether this explanation would work for a little kid, but I'm pretty sure I could make it make sense for the good sixth graders I hang out with sometimes. I'd have to explain a little first about what a ring was, but they'd like that.

A: First of all $\mathbf Z_3$ is a ring, not an ideal, much less a prime ideal.
A prime ideal is an ideal $P$ (i.e. a subset of a ring that is stable by addition, and by multiplication by an element of the ring), which further has the property that whenever a product $xy\in P$, at least one of the factors $x,y$ lies in $P$. It is the ideal-theoretic version of the number of a prime number, or an irreducible polynomial.
In terms of quotient rings, an ideal $P$ in the ring $A$ is prime if and only if the quotient ring $A/P$ is an integral domain.
As an example, a natural number $p$ is prime if and only if the principal ideal $p\mathbf Z$ is a prime ideal.
A proper ideal is simply an ideal that is different from the whole ring.


text:
Q: Conversion failed when converting the varchar value ' WHILE (' to data type int I have the below transaction:
DECLARE @strsql1 NVARCHAR(MAX);
DECLARE @rows INT, @count INT;
DECLARE @MySource NVARCHAR(30);
DECLARE @Myfield NVARCHAR(30);

SET @rows = 1;
SET @count = 0;

SELECT @strsql1 =
'WHILE ('+@rows+')> 0
BEGIN
BEGIN TRAN
delete top (10000)  from '+@MySource+'
where' +@Myfield+' =''value''
SET '+@rows+' ='+ @@ROWCOUNT+'
SET '+ @count+'  = '+ @count+ @rows +'
RAISERROR(''COUNT %d'', 0, 1, '+ @count+') WITH NOWAIT
COMMIT TRAN
END;'

PRINT @strsql1
EXEC sp_executeSql @strSql1

but I get this error message:

Conversion failed when converting the varchar value ' WHILE (' to data type int.

I have try to use the cast with the two variables (@count and @row) but the problem reside.
Could you please suggest some solution?
Thank you.

A: First thing, when adding the value of an integer variable to a string, you should CAST it, for example:
SELECT @strsql1 = 'WHILE (' + CAST(@rows AS varchar) +') > 0'

However, you don't REALLY want to do that either... because you want to test the variable against the constant zero, it should be more like:
SELECT @strsql1 = 'WHILE (@rows > 0)'

But this line right here is just completely wrong... the result would be SET 2 = 3 or something like that, which makes no sense:
SET ' + @rows + ' =' + @@ROWCOUNT + '

So you have a LOT of problems here.
They key to dynamic SQL is not rushing ahead and executing it... try just PRINTING the string first, and look at the result, and see what's wrong with that (it should be obvious... copy/paste it into a new SSMS query window and you can see right away what's wrong), and then iterate, fixing your dynamic SQL generation until the generated SQL is correct. THEN execute it.
Basically, you need to leave the variable alone in the dynamic SQL, and then pass the variable in via the optional arguments to sp_executesql. There are many examples on-line of how to pass arguments in. But the declarations of @rows should probably go inside your dynamic SQL as well. Remember that dynamic sql executes in its OWN context, not the context of the calling code, so it can't see any variables declared outside. And when building dynamic SQL, you want to only use the things that will change PER CALL outside the string.

A: Maybe something like this will get you started.
declare @MySource sysname = 'YourTableName'
    , @MyField sysname = 'YourFieldName'
    , @strsql1 NVARCHAR(MAX)

SELECT @strsql1 =
'DECLARE @rows INT = 1;
WHILE @rows > 0
BEGIN
    delete top (10000)  from ' + QUOTENAME(@MySource)
    + ' where ' + QuoteName(@Myfield) + '=''value'';
    SET @rows = @@ROWCOUNT;
    print convert(varchar(10), @rows) + '' row(s) affected'';
END;'

PRINT @strsql1
--EXEC sp_executeSql @strSql1


text:
Q: What actually "forces" us to define the operations on $\mathbb{Q}$ the way they are? Given the integers, we have the usual operations which behave the way they are expected to behave. Now suppose we want to create $\mathbb{Q}$ which are pairs $\cfrac{a}{b\neq 0}$. We want that $\mathbb{Q}$ have a copy of $\mathbb{Z}$ that behaves exactly as $\mathbb{Z}$ itself, that is: We want:
$$a_\mathbb{Z}+b_\mathbb{Z}:=a_\mathbb{Q}+b_\mathbb{Q}\quad \quad \quad \quad \quad \quad a_\mathbb{Z}\cdot b_\mathbb{Z}:=a_\mathbb{Q}\cdot b_\mathbb{Q}$$
Which could be defined as:
$$a_\mathbb{Z}+b_\mathbb{Z}:=\cfrac{a}{1}+\cfrac{b}{1}=\cfrac{a+b}{1} \quad\quad \quad \quad a_\mathbb{Z}+b_\mathbb{Z}:=\cfrac{a}{1}\cdot\cfrac{b}{1}=\cfrac{a\cdot b}{1}\tag{$\star$}$$
That is: $\cfrac{a}{1}$ is the representation of $a$ in $\mathbb{Q}$. Given only addition and multiplication, and taking into account the definitions made in $(\star)$, is it possible to define addition and multiplication in $\mathbb{Q}$ in a way that for all $a,b\in \mathbb{Q}$, $(\star)$ is true but the elements $\frac{c}{d\neq 1}$ behave in a way different than we expect for $\mathbb{Q}$?
That is: Could we define it in a way that $1+1=2,\; 2+1=3\; \dots$ but $\cfrac{1}{2}+\cfrac{1}{3}\neq \cfrac{5}{6},\; \cfrac{1}{4}+\cfrac{1}{5}\neq\cfrac{9}{20},\; \dots$?
My intentions: I want to figure out if having only the definition $(\star)$, addition and multiplication forces us to define $\mathbb{Q}$'s operations the way it is defined, that is:

$$\cfrac{a}{b}+\cfrac{c}{d}:=\cfrac{ad+cb }{bd}\quad\quad \quad \cfrac{a}{b}\cdot \cfrac{c}{d}:=\cfrac{a\cdot c}{b\cdot d} $$

Obviously, we could do it in a completely retarded way like saying that $\cfrac{a}{b}+\cfrac{c}{d}:= \cfrac{a+c}{1}$ if $b=d=1$ and $\cfrac{a}{b}+\cfrac{c}{d}:= \cfrac{a^2b^3c^4d^5}{1}$ if $b\neq 1$ or $d\neq 1$ and my original intention is to avoid these but I'm not sure if I described it good enough to really avoid it.

It reminds me of a talk I had with a professor and asked if there are continuous everywhere differentiable nowhere functions other than Weierstrass function. He replied:

*

*Yes, there are infinitely many. Let $W$ be the Weierstrass function, take $f(c)=W+c$. For each $c\neq 0$, you have a different continuous everywhere differentiable nowhere function!

A: NOTE: In order to make this shorter, I will say $\frac a b$ is $ab^{-1}$.
Let's say we want to add division to $\Bbb{Z}$. This means we have to figure out how to add and multiply $ab^{-1}$ and $cd^{-1}$ while still satisfying:

*

*Associative Property of Addition and Multiplication

*Commutative Property of Addition and Multiplication

*Distributive Property of Multiplication over Addition

*Identity of Multiplication: $a\cdot 1=a$

*Division is Same as Multiplying By Reciprocal: $ab^{-1}=a\cdot b^{-1}$

*Dividing Number by the Same Number Cancels: $aa^{-1}=1$

*Distributive Property of Exponents over Multiplication: More specifically, we want $a^{-1}b^{-1}=(ab)^{-1}$ (Technically, this property is redundant because it can be proven from the above properties, but it's still an important property to know.)

Multiplication is actually pretty easy. By Commutative Property, just have:
$$ab^{-1}\cdot cd^{-1}=acb^{-1}d^{-1}=(ac)(bd)^{-1}$$
Now, addition is kind of odd, but the key here is to find common denominator by multiplying $ab^{-1}$ by $dd^{-1}$ and $cd^{-1}$ by $bb^{-1}$:
$$ab^{-1}+cd^{-1}=ab^{-1}\cdot dd^{-1}+cd^{-1}\cdot bb^{-1}=ad(bd)^{-1}+bc(bd)^{-1}=(ad+bc)(bd)^{-1}$$
Thus, by just trying to satisfy the properties listed at the top. Even though it might seem like a lot of assumptions, they are pretty normal, regular properties that come up a lot in abstract algebra, we get these definitions of addition and multiplication for fractions. There are also other important properties that you can check out by looking at the field axioms.

A: A "high-level" explanation was hinted at in the comments already:
If you care about fields and integral domains then you can think of the "process" (functor) of forgetting everything about a field, except that it is an integral domain.
The essentially unique "inverse process" (left-adjoint) takes integral domains to their field of fractions, in particular $\mathbb{Z}$ to $\mathbb{Q}$. That's not just some definition, that's actually a theorem basically telling you that this is "the best you can do" if you want to turn an integral domain into a field.

A: Suppose you want to have the following relatively simple conditions:

*

*$\mathbb{Z}$ embeds into $\mathbb{Q}$, namely that $\frac a1 + \frac b1 = \frac{a+b}1$ and $\frac a1 \times \frac b1 = \frac{a \times b}1$, for any integers $a,b$.

*$\mathbb{Q}$ is closed under $+,\times$ each of which is associative and commutative.

*$\sum_{k=1}^n \frac{m}n \overset{Δ}= \underbrace{\frac{m}n+\frac{m}n+\cdots+\frac{m}n}_\text{$n$ terms} = \frac{m}1$, for any integers $m,n$ such that $n > 0$.

*$\sum_{k=1}^n ( \frac{a}b \times \frac{c}d ) = \frac{a}b \times \sum_{k=1}^n \frac{c}d$, for any integers $a,b,c,d,n$ such that $b,d,n > 0$.

*$\sum_{k=1}^n \frac{a}b = \sum_{k=1}^n \frac{c}d$ implies $\frac{a}b = \frac{c}d$, for any integers $a,b,c,d,n$ such that $b,d,n > 0$.

Then we can obtain the following.
Take any integers $a,b,c,d$ such that $b,d > 0$.
If $a = 0$, then $ad = 0 = a$, and hence $\frac{ad}{bd} = \frac01 = \frac{a}{b}$.
If $a \ne 0$, then $ad \ne 0$ and $bd > 0$ and $\sum_{k=1}^{bd} \frac{ad}{bd} = ad = d \sum_{k=1}^b \frac{a}{b} = \sum_{k=1}^{bd} \frac{a}{b}$, and hence $\frac{ad}{bd} = \frac{a}{b}$.
By symmetry $\frac{cb}{db} = \frac{c}{d}$.
Thus $\frac{a}{b} + \frac{c}{d} = \frac{ad}{bd} + \frac{bc}{bd}$.
Thus $\sum_{k=1}^{bd} ( \frac{a}{b} + \frac{c}{d} ) = d \sum_{k=1}^b \frac{a}{b} + b \sum_{k=1}^d \frac{c}{d} = da + bc = \sum_{k=1}^{bd} \frac{ad+bc}{bd}$, and hence $\frac{a}{b} + \frac{c}{d} = \frac{ad+bc}{bd}$.
Also $\sum_{k=1}^{bd} ( \frac{a}{b} \times \frac{c}{d} ) = \sum_{k=1}^b \sum_{k=1}^d ( \frac{a}{b} \times \frac{c}{d} ) = \sum_{k=1}^b ( \frac{a}{b} \times \sum_{k=1}^d \frac{c}{d} ) = \sum_{k=1}^b ( \frac{a}{b} \times \frac{c}1 )$
$\quad = \sum_{k=1}^b ( \frac{c}1 \times \frac{a}{b} ) = \frac{c}1 \times \sum_{k=1}^b \frac{a}{b} = \frac{c}1 \times \frac{a}1 = \frac{ca}1 = \sum_{k=1}^{bd} \frac{ac}{bd}$, and hence $\frac{a}{b} \times \frac{c}{d} = \frac{ac}{bd}$.

So indeed we are forced to have the usual rules for addition and multiplication of fractions if we want the five conditions listed above. Now I purposely did not state the usual ring/field axioms as the conditions because I wanted to show that 'much less' is already sufficient. Note also that the above does not prove that the fractions form a field. One still needs to show that there is some structure that satisfies the conditions.
But at least the above tells you exactly how to go about constructing such a structure. Namely, you know that a fraction should be equivalent if you divide both numerator and denominator by some common factor. So you might as well enforce that they do not have any common factor, or you could take the alternative route of defining the equivalence relations. Both ways are very well explained in any good textbooks, and the latter is in particular the one to use when constructing fraction fields of general integral domains.


text:
Q: How do I check to see if three points form a straight line? Problem: Create the function mylinecheck(a,b,c,d,e,f) which takes six inputs:
a,b,c,d,e,f which are real numbers, and a,c,e are not equal. The function must check if the three points (a,b), (c,d), and (e,f) all lie on the same line. If so, return a 1. If not, return a 0.
I think what I want to do is tell MATLAB to check if coordinates (c,d) and (e,f) are multiples of (a,b), and then if not I will return a 0. If so, I will return a 1. If this is the right thought process, I'm not sure how to command MATLAB to do so. Any advice would be greatly appreciated.

A: The points (x1,y1), (x2,y2), and (x3,y3) lie on the same line if and only if they satisfy
a x + b y + c = 0

for fixed values of a, b, and c (I cannot get over your notation; sorry for the "confusion"), where a or b are nonzero. Hence they lie on the same line if and only if
a x1 + b y1 + c = 0         [x1 y1 1][a]   [0]
a x2 + b y2 + c = 0   <=>   [x2 y2 1][b] = [0]
a x3 + b y3 + c = 0         [x3 y3 1][c]   [0],

that is, the homogeneous linear system with the matrix
    [x1 y1 1]
X = [x2 y2 1]
    [x3 y3 1]

has a nonzero solution. This is possible only if X is singular. By eliminating the last column of X you can find that X is singular if and only if the matrix
Y = [x2-x1 y2-y1]
    [x3-x1 y3-y1]

is singular.
To reliably check for the singularity of a matrix in Matlab, you can use SVD or, equivalently, the function rank. Hence your function could be implemented as follows:
function [result] = mylinecheck(x1,y1,x2,y2,x3,y3)

result = rank([x2-x1, y2-y1; x3-x1, y3-y1]) < 2;

A: If you want to check if points all fall on the same line (or are collinear), one of the classic methods would be to assume that each point forms a vertex in a triangle.   If the three points make the triangle such that the area is equal to 0, then the points would be collinear or form a line.  This can be done by checking the determinant of the following matrix:
[a b 1]
[c d 1]
[e f 1]

You can read the article on collinearity on Wolfram Mathworld here: http://mathworld.wolfram.com/Collinear.html (I also linked it above).
As such, your function simply needs to be:
function [out] = mylinecheck(a,b,c,d,e,f)

    D = [a b 1; c d 1; e f 1];
    out = det(D) == 0;

However, due to numerical imprecision, you may provide floating point numbers where the points are indeed collinear, but you may get a determinant that isn't equal to 0 (actually, perhaps a small number).  As such, one thing I can suggest is check to see if the determinant is less than a small number.  Something like:
function [out] = mylinecheck(a,b,c,d,e,f)

    D = [a b 1; c d 1; e f 1];
    out = abs(det(D)) < 1e-10;

1e-10 is a small number which is 10^{-10}.  We take the abs to account for both positive and negative determinants, so you would be checking collinearity and is true if:
 -10^{-10} < det(D) < 10^{-10}

However, with the comments made by Pavel, if points fall along the same line, if we decide to scale the coordinates, the determinant value will also increase in value as well.  One suggestion I have is to perhaps be more liberal with the threshold.  Make it larger.... perhaps something like 0.1.


text:
Q: What is this for a character `\ x9d`? While parsing a text file and doing some prints for debug purposes, the print stucks at a point but I didn't get any errors and the script seemed be running further. So I checked the file content and I recognised a rectangle character. I copied it to the python interpreter and the interpreter got stuck as well.
I checked on Unicode Lookup the character definition: osc operating system command and the unicode is \x9d. What does that mean?
This is the character how it looks here:
Edit: After posting I recognised, that the character is invisible. So I did a screenshot from the editing view, so you see the character from the edit mode perspective.


text:
Q: Why am I having several errors from javac not finding any packages from javaFx? I am starting to learn how to make GUI with JavaFx and I was following the basics to run a  simple "hello world" program with the book 'JavaFx 9 by Example' from Carl Dea.
But in the end, even though I just copied the source code and the bash commands, javac doesn't acknowledge the javaFx packages.
This is not the first I code in Java, but it is the first time I am using the terminal in MacOs to compile it and run it.
At the same time I am learning JavaFx, I am also assimilating Bash. I read that MacOs have an old version of it; so I replace the one set up by default with a new version '5.0.7(1)-release'.
I do not know if it matters, but
$ echo "$BASH_VERSION"
5.0.7(1)-release.

and.
$ bash -version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17).

Also, I downloaded and installed the most recent version of Java some days ago
$ java --version
java 12.0.1 2019-04-16
Java(TM) SE Runtime Environment (build 12.0.1+12)
Java HotSpot(TM) 64-Bit Server VM (build 12.0.1+12, mixed mode, sharing)

It may have to do with the Java Path, but if it is that I am not sure how to solve it.
The problem I believe is when importing the javaFx libraries:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

When I compile it, I get several errors.
Some of them are:
$ javac -d classes src/*.java
src/HelloWorld.java:2: error: package javafx.application does not exist.
import javafx.application.Application;
                         ^

Basically, it seems that javac does not recognize or knows the existence of any package from javaFx.
This error mitigates to the Objects that want to be created using this class
symbol: class Application
src/HelloWorld.java:20: error: cannot find symbol
public void start(Stage stage) {
                  ^

Edit:
Thanks for the answers, i finally was able to do a simple application with JavaFx. The only thing that bothers me is the large command prompt needed for compiling this code.
$ javac --module-path $PATH_TO_FX --add-modules javafx.controls HelloWorld.java
$ java --module-path $PATH_TO_FX --add-modules javafx.controls HelloWorld

It does not go away, isn't it?


text:
Q: Initilize an array of struct
Possible Duplicates:
How to initialize array of struct?
Initializing an Array of Structs in C#

C#, Visual studio 2010
I want declare an array of struct and initialize it on the same time but can not get it right
How do i write to default initialize an array consisting of structs ?
The following wont go through the compiler but show the idea of what I want to archive
    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    }

    private PrgStrTrans_t[] PrgStrTrans = { {1, "hello", "there"}, {2, "Fun", thisone"}}

Is it possible at all ?

A: Add a constructor to your struct, and put new PrgStrTrans(...), on each line of the array.
Like this:
private struct PrgStrTrans_t
{
    public int id;
    public string name;
    public string fname;

    public PrgStrTrans_t(int i, string n, string f)
    {
        id = i;
        name = n;
        fname = f;
    }
}

private PrgStrTrans_t[] PrgStrTrans = {
                                          new PrgStrTrans_t(4, "test", "something"),
                                          new PrgStrTrans_t(2, "abcd", "1234")
                                      }

A: private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};

It would be better if you made a constructor, that would avoid typing the property names.


text:
Q: Calculate Fibonacci Method using GUI I'm trying to get a Method using Fibonacci to bind to a button, which will use a slider as the input value and then print the Fibonacci number in a textfield. I am running into trouble passing the value from my Fibonacci method to the textfield. Any help would be appreciated. This is what I've written so far:
public class Main extends Application {

    private static Slider fibSlider = new Slider(0, 10, 0);
    private static Label indexLabel = new Label();
    private static Label fibNumLabel = new Label();
    private static int colIndex = 0;
    private static int rowIndex = 0;
    private static int topIndex = 0;
    private static int rightIndex = 0;
    private static int leftIndex = 0;
    private static int bottomIndex = 0;
    private static TextField tfIndex;
    private static TextField tfFibNum;
    private static Button butCalcFib = new Button();

    @Override
    public void start(Stage primaryStage) {

        fibSlider.setMajorTickUnit(1);
        fibSlider.setMinorTickCount(0);
        fibSlider.setShowTickLabels(true);
        fibSlider.setShowTickMarks(true);
        fibSlider.setSnapToTicks(true);

        fibSlider.valueProperty().addListener(sl -> {
            tfIndex.setText(Double.toString(fibSlider.getValue()));
        });

        indexLabel.setText("Index: ");
        fibNumLabel.setText("Fibonacci #: ");
        butCalcFib.setText("Calculate Fibonacci");
        //tfFibNum.setText(long.toString(ComputeFibonacci()));

        fibSlider.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
                if (newValue == null) {
                    tfIndex.setText("");
                    return;
                }
                tfIndex.setText(Math.round(newValue.intValue()) + "");
            }
        });

        GridPane mainGPane = buildGPane();
        Scene mainScene = new Scene(mainGPane, 500, 200);

        primaryStage.setTitle(" - Fibonacci Calculator");
        primaryStage.setScene(mainScene);
        primaryStage.show();

    }

    private GridPane buildGPane() {
        GridPane gPane = new GridPane();
        gPane.setAlignment(Pos.CENTER);
        gPane.setPadding(new Insets(topIndex = 10, rightIndex = 10,
            bottomIndex = 10, leftIndex = 10));
        gPane.setHgap(2);
        gPane.setVgap(2);
        gPane.add(fibSlider, colIndex = 1, rowIndex = 3);
        gPane.add(indexLabel, colIndex = 1, rowIndex = 5);
        gPane.add(tfIndex, colIndex = 2, rowIndex = 5);
        gPane.add(butCalcFib, colIndex = 1, rowIndex = 6);
        gPane.add(fibNumLabel, colIndex = 1, rowIndex = 7);
        gPane.add(tfFibNum, colIndex = 2, rowIndex = 7);

        return gPane;
    }

    public Main() {
        tfIndex = new TextField();
        tfFibNum = new TextField();
    }

    public static void ComputeFibonacci() {
        double index = fibSlider.getValue();
        // Find and display the Fibonacci number
        fib((long) index);
    }

    /**
     * The method for finding the Fibonacci number
     */
    public static long fib(long index) {
        if (index == 0) // Base case
        {
            return 0;
        } else if (index == 1) // Base case
        {
            return 1;
        } else // Reduction and recursive calls
        {
            return fib(index - 1) + fib(index - 2);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

A: You can simplify your code considerably by letting the slider's listener update both the index and the result fields. Then you only need one slider listener and no button.
    fibSlider.valueProperty().addListener(sl -> {
        long value = (long) fibSlider.getValue();
        tfIndex.setText(Long.toString(value));
        tfFibNum.setText(Long.toString(fib(value)));
    });

See also this Q&A about the observer pattern. In the variation below,

*

*GridPane allows the slider to span two columns.

*Invoking the slider's setBlockIncrement() method lets you change the slider using the arrow keys.

*In the slider's InvalidationListener, you can reference the slider's DoubleProperty value, rather than referencing the enclosing class's fibSlider field.
As tested:
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

/** @see https://stackoverflow.com/a/37068554/230513 */
public class Main extends Application {

    private final Slider fibSlider = new Slider(0, 10, 0);
    private final Label indexLabel = new Label("Index: ");
    private final Label fibNumLabel = new Label("Fibonacci #: ");
    private final TextField tfIndex = new TextField("0");
    private final TextField tfFibNum = new TextField("0");

    @Override
    public void start(Stage primaryStage) {
        fibSlider.setMajorTickUnit(1);
        fibSlider.setMinorTickCount(0);
        fibSlider.setShowTickLabels(true);
        fibSlider.setShowTickMarks(true);
        fibSlider.setSnapToTicks(true);
        fibSlider.setBlockIncrement(1.0);
        fibSlider.valueProperty().addListener(sl -> {
            long value = ((DoubleProperty) sl).longValue();
            tfIndex.setText(Long.toString(value));
            tfFibNum.setText(Long.toString(fib(value)));
        });

        GridPane mainGPane = buildGPane();
        Scene mainScene = new Scene(mainGPane);
        primaryStage.setTitle("Fibonacci Calculator");
        primaryStage.setScene(mainScene);
        primaryStage.show();
    }

    private GridPane buildGPane() {
        GridPane gPane = new GridPane();
        gPane.setAlignment(Pos.CENTER);
        gPane.setPadding(new Insets(10, 10, 10, 10));
        gPane.setHgap(10);
        gPane.setVgap(10);
        gPane.add(fibSlider, 0, 0, 2, 1);
        gPane.add(indexLabel, 0, 1);
        gPane.add(tfIndex, 1, 1);
        gPane.add(fibNumLabel, 0, 2);
        gPane.add(tfFibNum, 1, 2);
        return gPane;
    }

    /**
     * The method for finding the Fibonacci number
     */
    public long fib(long index) {
        if (index == 0) {
            return 0;
        } else if (index == 1) {
            return 1;
        } else {
            return fib(index - 1) + fib(index - 2);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Perl -pi -e cannot substitute lines with asterisk - maybe I'm not escaping properly I've been using the perl pie mentioned in SO without success. What am I doing wrong:
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self

I want the file to end up looking like this after doing perl pie
 * It is generally better to create a new file per style scope.
 *
 *= require iziToast
 *= require_tree .
 *= require_self

I wasted one hour with silly attempts like this:
  828  perl -pi -e 's/  *= require_tree ./  *= Require_tree ./' app/assets/stylesheets/application.css.scss
  832  perl -pi -e 's/require_tree \./Require_tree \./' app/assets/stylesheets/application.css.scss
  837  perl -pi -e 's/  \*\= require_tree \./  \*\= Require_tree \./' app/assets/stylesheets/application.css.scss
  839  perl -pi -e 's/= require_tree \./= Require_tree \./'       864  perl -pi -e 's/\*/\Q*/' app/assets/stylesheets/application.css.scss
  868  perl -pi -e 's/\*/\Q*/' app/assets/stylesheets/application.css.scss
  874  perl -pi -e 's/\*/*/' app/assets/stylesheets/application.css.scss
  876  perl -pi -e 's/\*/\*/' app/assets/stylesheets/application.css.scss
  878  perl -pi -e 's/\*/s/' app/assets/stylesheets/application.css.scss
  898  git checkout app/; perl -pi -e 's/\(\*\)/$1/' app/assets/stylesheets/application.css.scss; git diff
  900  git checkout app/; perl -pi -e 's/(*)/$1/' app/assets/stylesheets/application.css.scss; git diff
  901  git checkout app/; perl -pi -e 's/(\*)/$1/' app/assets/stylesheets/application.css.scss; git diff
  903  git checkout app/; perl -pi -e 's/(\\*)/$1/' app/assets/stylesheets/application.css.scss; git diff
  905  git checkout app/; perl -pi -e 's/\(\*\)/$1/' app/assets/stylesheets/application.css.scss; git diff
  907  git checkout app/; perl -pi -e 's/^(.*)/foo/' app/assets/stylesheets/application.css.scss; git diff
  908  git checkout app/; perl -pi -e 's/^  (.*)/foo/' app/assets/stylesheets/application.css.scss; git diff
  924  git checkout app/; perl -pi -e 's/^(.*)/\1/' app/assets/stylesheets/application.css.scss; git diff
  925  git checkout app/; perl -pi -e 's/^(.*)/\\1/' app/assets/stylesheets/application.css.scss; git diff

System: Mac 10.13.5, bash 3.2, perl 5.18
Notes: A line number based approach is not ideal for me because line numbers are not very future-proof
Since question title mentions perl, looking for a perl answer.

A: * and . are special in regex patterns. You must use \* and \. to match * and ..
perl -i -pe'print " *= require iziToast\n" if /^ \*= require_tree \.$/' file

or
perl -i -pe's/^(?= \*= require_tree \.$)/ *= require iziToast\n/' file

A: I wouldn't even use Perl for this; you can simply use sed.
$ sed '3i\
> \ *= require iziToast
> ' tmp.txt
 * It is generally better to create a new file per style scope.
 *
 *= require iziToast
 *= require_tree .
 *= require_self


text:
Q: Trouble with CSS Grid Layout/Image positioning Having some trouble trying to put together a page where images are placed properly. Screen shot attached of what I currently have in place now. What I am trying to get to would look like the first row of images (1-5) all the way down the page with every other row opposite, if that makes sense. Images 1-8 are set up correctly but 9-10 are on row 3 rather than on row 2 where I would like them. Image 11 should be left side and 12-15 should be right side. And so on..

Current css –
    #grid { float: left; width: 100%; overflow: hidden; }
#grid-inner { float: left; width: 890px; overflow: hidden;  }
.item { float: left; margin: 0 0 10px 0; position: relative; }
.item span { display: none; position: absolute; padding: 0 0 0 0; color: #fff; background: transparent url('../images/back-work.png') 0 0 repeat; }
.item span a { color: #fff; display: block; height: 100%; width: 100%; }
.small { width: 210px; height: 125px; }
.large { width: 420px; height: 260px; }
.small span { width: 210px; height: 125px; padding: 0 0 0 0; }
.large span { width: 420px; height: 260px; padding: 0 0 0 0; }
#project { float: left; width: 100%; }
#project-content { float: left; width: 100%; border-top: 1px solid #ccc; margin: 0 0 0 0; padding: 0 0 0 0; }
#project-content-alpha { float: left; width: 200px; }
#project-content-beta { float: left; width: 410px; }
#project-content-gamma { float: right; width: 200px; text-align: right; }
    #project-content-alpha span.light { color: #999; }
#project-images { float: left; width: 100%; }
#project-images img { float: left; width: 100%; margin: 0 0 0 0; }
#project-pagination { float: left; width: 100%; margin: 0 0 0 0; }
#project-pagination-alpha { float: left; width: 200px; }
#project-pagination-beta { float: right; width: 200px; text-align: right; }

Current markup –

ONE

TWO

THREE

    FOUR

Any help or suggestions on this would be appreciated.
Thanks in advance!

A: CSS floats don't reposition the elements vertically. They only float horizontally.
If you want vertical "floats" (i.e. tiling), you will need to use JavaScript. I recommend the jQuery Masonry Plugin or Vanilla Masonry (jQuery Masonry minus the jQuery).

A: Check out the interface here. Let me know if you need revisions.
EXACTLY WHAT WAS ASKED FOR - http://jsfiddle.net/rxLTG/
HTML

CSS
.wrap {width:650px;}
.wrap img {float:left; width:150px; height:100px;}
.wrap img.lg {width:350px; height:200px;}
.row.odd .lg, .row:nth-child(even) .lg {float:right;}

JS
$(function () {
    $('.row:odd').addClass('odd');
});

A: A better way would be like this - http://jsfiddle.net/rxLTG/2/
HTML

CSS
.wrap {width:500px;}
.wrap img {float:left; width:125px; height:100px;}
.wrap img.lg {width:250px; height:200px;}
.wrap img.lg2 {width:250px; height:200px;float:right;}

Theres no need to define each row inside a div, because they will automatically fit and wrap round.
Also, if you float the large image on each row first (left or right), then the other four will fit into place without any javascript needed.
Every fifth number will then be a large image, (1,6,11,16,21 etc). If you want it to work javascript free, then use this solution. If you want to keep your original numbering system, then use the solution above.

A: You can just look at it as a grid. More markup, but reusable and responsive too.
For the example, you can handle this grid layout with a single class that takes the half of it's container.
first row :
    - 1 column of 1/2 : has 1 large image
    - 1 column of 1/2 : has 4 columns (1/2 each, and each containing a small image)
Second row : just reverse the first 1/2 columns
Columns are floated, so the col 4 and 5 will stack under 1 and 2... Your images, have to be at the right aspect ratio too.
And finally, since you're floating elements, clearfix the group.
Hope it helps.

/* Micro clearfix for the wrapper */
.wrap:before,
.wrap:after {
    content: '';
    display: table
}
.wrap:after {
     clear: both;
}
.wrap { width:650px; }
/* no need for size if you put the right images */
img {
    width:100%;
    height: auto;
    vertical-align: middle; /* removes the gap beneth the image */
}
/* you can go further and create some other columns */
.col-1-2 {
    float: left;
    width: 50%;
}
/* demo purpose only */
img {
    width: 100%;
    height: 100px;
}
img.lg { height: 200px; }


text:
Q: Servlet - close connection but not method I have to implements service (servlet 2.5 or 3) that will send 204 code on every connection but not close the thread.
I need do some stuff with the data I received (like open new connection).
It is possible to close connection but not end method? Or start another method when connection is closing?

A: Well it is unclear in the specs, but it seems to work in Tomcat 7.0.
Extract from the specs for servlet 3.0 :

Closure of Response Object
  When a response is closed, the container must immediately flush all remaining
  content in the response buffer to the client. The following events indicate that the
  servlet has satisfied the request and that the response object is to be closed:
*

*The termination of the service method of the servlet.

*The amount of content specified in the setContentLength method of the response
  has been greater than zero and has been written to the response.

*The sendError method is called.

*The sendRedirect method is called.

*The complete method on AsyncContext is called.

From my tests on a tomcat 7.0.32, the Http connection is closed before the end of the service method of the servlet when ContentLength is set to 0 and the output stream is closed.
So per you requirements, you could try the following in your servlet :
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
response.setContentLength(0);
response.getOutputStream().close();
// continue after connection with client is closed

But BEWARE I could find no confirmation in the specs so it could not work with another container.

A: @Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException {
        //Send 204 back
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        // Continue with you logic here
        .
        .
        .
        .


text:
Q: determine which button clicked inside of a service have a simple service running, and I have some buttons each that do a different thing (I want them too). Im not sure how to let the service know which button was pressed. When I press a button I want a service to start regardless but depending on which button pressed It needs to do something different.
SERVICE CLASS
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    NotificationCompat.Builder mBuilder;
    private int i = 1;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        i++;
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // Do task depend on cliked view
        String clickedView = intent.getStringExtra("clicked_on");
        if ("BUTTON1".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("One Added!");
        } else if ("BUTTON2".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("Two Added!");
        }else if ("BUTTON3".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("One Subtracted!");
        }else{
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("Woo Lets Eat!!");
        }

        Intent resultIntent = new Intent(this, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(i, mBuilder.build());

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

    }
}

MAIN ACTIVITY
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

// Start the  service
public void startNewService(View view) {
    Intent serviceIntent = new Intent(this, MyService.class);
    if (view.getId() == R.id.button1) {
        serviceIntent.putExtra("clicked_on", "BUTTON1");
    } else if (view.getId() == R.id.button2) {
        serviceIntent.putExtra("clicked_on", "BUTTON2");
    } else if (view.getId() == R.id.button3) {
        serviceIntent.putExtra("clicked_on", "BUTTON3");
    } else {
        serviceIntent.putExtra("clicked_on", "BUTTON4");
    }
    startService(serviceIntent);
}

// Stop the  service
public void stopNewService(View view) {
    stopService(new Intent(this, MyService.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
MAIN XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/LightSalmon"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:text="@string/add_one"
        android:textColor="@color/White"
        android:onClick="startNewService"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_two"
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sub_one"
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/make"
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cnt"
        android:layout_marginTop="120dp"
        android:textColor="@color/LightSalmon"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

A: You should use AsynTask instead of Service.
But here is the solution for your current approach (But I would go for AsyncTask)
Modify startNewService which will read the id of button clicked and send to Service into intent extra.
public void startNewService(View view) {

    Intent serviceIntent = new Intent(this, MyService.class);
    // Read id of view and put extra.
    if (view.getId() == R.id.button1) {
        serviceIntent.putExtra("clicked_on", "BUTTON1");
    } else if (view.getId() == R.id.button2) {
        serviceIntent.putExtra("clicked_on", "BUTTON2");
    }
    startService(serviceIntent);
}

Now override onStartCommand of Service which having intent as param. You can read extra and do task depend on that.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // Do task depend on cliked view
    String clickedView = intent.getStringExtra("clicked_on");
    if ("BUTTON1".equals(clickedView)) {
        // Do task for button 1
    } else if ("BUTTON2".equals(clickedView)) {
        // Do task for button 2
    }
    return START_STICKY;
}

A: Consider the following:

*

*Start the service once the app started

*Make the service listen to 2 broadcast action

*On some button click send broadcast to the service with it specific action