text:
Q: GWT DeckLayoutPanel sliding to a NEW (not-rendered-yet) widget? Doesn't work I can't seem to slide to a new, not-rendered-yet widget added to a DeckLayoutPanel, no matter what I try.
It appears without the slide transition if it's never been rendered before.
However, when I do showWidget(...) back and forward to the new widget, then the slide transition works fine.
Has anybody been able to slide to a not-rendered-yet widget in DeckLayoutPanel? If so how?
I need this functionality.

A: You can use the scheduleDeferred comand. This will make sure that your slide command is executed, when the widget is actually shown.

It defers some code until after the browser redraws the page (if needed) and pending events are processed (that is after the mouseup and click if this is done in mousedown)
  Source

Docu
Usage:
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  @Override
  public void execute() {
    Scheduler.get().scheduleDeferred(/*Your silider comand*/); // reschedule
  }
});


text:
Q: Batch rename directories? I have several directories with the format of the year, month, and day followed by a description of the event. For example: "2012 05 26 - EventA", "2012 05 26 - EventB". What I would like to do is rename all these directories so that the spaces between the numbers in the date are replaced with dashes. Thus, "2012 05 26 - EventA" becomes "2012-05-26 - EventA". I know I can do this one folder at a time with the mv command, but is there a way to do this in a batch process with wildcards somehow?

A: Try pyRenamer: http://www.webupd8.org/2010/01/pyrenamer-easy-mass-file-renaming-in.html
or similar: http://alternativeto.net/software/pyrenamer/?platform=linux&license=free

A: You can also use mmv.
sudo aptitude install mmv
#> mmv "201? * * - Event?" "201#1-#2-#3 - Event#4"

A: I wanted to rename multiple directories (folders, not files) and could not figure out if this is possible with pyRenamer. GPRename (http://gprename.sourceforge.net/) does the trick quite nicely though.
Ubuntu users should have GPRename in their reposiories and can run this command to install GPRename:
sudo apt-get install gprename

A: Use rename (with the -n option to test the changes):
rename 'm/(\d{4}) (\d{2}) (.*)/;$_="$1-$2-$3"' *

Rename is provided by perl so you may need to install it (don't know if it's part of the stock Ubuntu install):
sudo apt-get install perl

A: You cannot rename batch files using mv command. You need to write shell scripts, you can get the scripts by doing a google search or you can use the tools mentioned above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I restrict access to a WCF Data Service to a specific user account? I've read so many blog posts and articles that my eyes are getting blurry. I haven't yet found what I need (or I just don't understand what I'm doing, which is most likely).
We have a WCF data service that we want to restrict access to. We want to put the web client in an app pool, and then only the app pool account should be able to use the WCF data service.
If someone hits the WCF service directly from a browser, or from another application, they should not be able to access the data.
How do I set this up? I tried impersonation, but I couldn't seem to get that to work.
Securing WFC data services seems way too difficult, but maybe I am just not looking at it correctly. Any help would be appreciated. Thanks.

A: Consider having a read of the following;
http://msdn.microsoft.com/en-us/library/dd728284.aspx
I would consider something like the following code. OnStartProcessingRequest occurs on every call to WCF Data Services;
   Protected Overrides Sub OnStartProcessingRequest(ByVal args As System.Data.Services.ProcessRequestArgs)
        MyBase.OnStartProcessingRequest(args)
        If HttpContext.Current.User.Identity.Name.ToLower <> "UserName".ToLower Then
            Throw New DataServiceException("Services restricted")
        End If
   End Sub

I'm sure there will be other methods to do this as well. If it's hosted in IIS I would guess it could be restricted the same as any other asp.net web application, but I haven't really looked at it much.


text:
Q: Ionic 2 provider missing boilerplate load() function I am taking baby steps in ionic2. I am following official blog tutorial to hit an api. I ran this command as instructed ionic g provider PeopleService. But the boilerplate code is something like this
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the PeopleServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
@Injectable()
export class PeopleServiceProvider {

  constructor(public http: Http) {
    console.log('Hello PeopleServiceProvider Provider');
  }

}

Insted of this
load() {
  if (this.data) {
    // already loaded data
    return Promise.resolve(this.data);
  }

  // don't have the data yet
  return new Promise(resolve => {
    // We're using Angular HTTP provider to request the data,
    // then on the response, it'll map the JSON data to a parsed JS object.
    // Next, we process the data and resolve the promise with the new data.
    this.http.get('path/to/data.json')
      .map(res => res.json())
      .subscribe(data => {
        // we've got back the raw data, now generate the core schedule data
        // and save the data for later reference
        this.data = data;
        resolve(this.data);
      });
  });
}

as mentioned in tutorial.
What am I doing wrong?


text:
Q: How to let screenshot show a mouse pointer on Mojave and Catalina? I think in Mojave and up, we can press CMD Shift 5 to show a menu of what to capture on screen and the Options.
There are options for a 5 second or 10 second timer, and one to "Show Mouse Pointer".  But if I use a 10 second timer and "Show Mouse Pointer", the mouse pointer is not in the screenshot? (The one I tried was to get a region of the screen). How to make it work?
P.S. I experimented some more. If I do a full screen capture, the mouse pointer was there. But if it is a window or region capture, then the mouse pointer wasn't there.

A: Screenshot under Catalina does not have this problem, went taking timed full screen captures. If only a selected portion or window is needed, then take a screenshot of a selected portion of the full screen image. This can result in a monotonous and time consuming process. However, the Screenshot application includes a record feature, that can be used when many screen captures are needed. You can then playback, pause and capture whole screens, windows or portions. Below is one example.

Example of the Wrong and Right Way to Capture a Window.
The images below were taken using the Grab application from High Sierra.
Grab was used to capture a Finder window. The image is shown below. The problem here is the window does not have focus.

Next, Grap was used to capture a selection which included the Finder window, as shown below. Still no focus.

Finally, a timed capture was taken of the entire screen. The the delay was used to give focus to the Finder window. Next, a selection was captured from this image. The result was the correct image shown below.

Below is an example where the Screenshot application was is used from Catalina.
First, a two captures of a Finder window were taken, as shown below. The first image was taken without a timer. The second was taken with a 5 second timer, so focus could be given to the window. In both cases, neither window has focus.

Next, a capture of a selected portion was taken, which included the window, as shown below. Here the image is correct. So at least Apple has fixed one problem.

Finally, two captures were taken. The first involved the timed full screen, then a portion of the first image. The second image is shown below. You can see this image is also correct.

Below is an example where the Screenshot application is used from Catalina. This time a screen pointer is included
Below is a selected portion taken with a timer. The screen pointer is not included.

Again, two captures were taken. The first involved the timed full screen, then a portion of the first image. The second image is shown below. You can see the image below includes the screen pointer.

Conclusions
The capture portion of Screenshot works for images which do not require inclusion of the screen pointer. When the screen pointer needs to be included, you may still need to resort to the two image approach that Grab required.


text:
Q: Density plots via Map with ggplot2 I have a dataframe df in R. (We can use the example of iris.) I also have simple transformations of iris:
iris0 <- iris
iris1 <- cbind(log(iris[,1:4]),iris[5])
iris2 <- cbind(sqrt(iris[,1:4]),iris[5])

I want to create a list object containing the density distributions of all numerical attributes in iris, for each of these three datasets. (So, in total 4 attributes for each of 3 datasets: 12 density plots in one list object.) I would like the densities from a given dataset (for each attribute) to all be a single colour, i.e. the colour should depend purely on the dataset. Using just base R, I thought Map would be the best way to do it:
datasets=c("iris0","iris1","iris2")
Map(function(.x, .y, df) {
  ggplot(data = get(df), aes(x=.x)) +
  geom_density(aes(fill=df)) + xlab(.y) + ggtitle(label=paste0(.y," Density in ",df," dataset"))}, df[names(df)], names(df), as.character(datasets) )

This seems to run into an error, Error in get(df) : object 'df' not found. I also tried wrapping the df[names(df)] and names(df) with get around each df, but the error persisted.
I can also see other potential problems down the line--I'm not sure fill=df will correctly encode the data-frames as a factor and ensure they are a separate unique colour each (but each remain the same colour for all attributes).
Can anyone help solve this one?
(I would like to do it without using any packages besides base R + ggplot2 and potentially dplyr)

A: Instead of using Map I make use of lapply to first iterate over the datasets and second over the variables via names(get(df))[1:4] At the end I flatten the list of lists using Reduce. I also added a custom palette to fill the density plots by dataset. Try this:
iris0 <- iris
iris1 <- cbind(log(iris[,1:4]),iris[5])
iris2 <- cbind(sqrt(iris[,1:4]),iris[5])

datasets <- c("iris0","iris1","iris2")
palfill <- c("iris0" = "red","iris1" = "green","iris2" = "blue")

library(ggplot2)

# list of lists
plots <- lapply(datasets, function(df) {
  lapply(names(get(df))[1:4], function(.x) {
    ggplot(data = get(df), aes_string(x = .x)) +
      geom_density(aes(fill = df)) +
      scale_fill_manual(values = palfill) +
      xlab(.x) +
      ggtitle(label = paste0(.x, " Density in ", df," dataset"))
  })
})
# flatten
plots <- Reduce(c, plots)

plots[[1]]

Created on 2020-05-16 by the reprex package (v0.3.0)


text:
Q: jQuery Sortable with animation I'm using jQuery and Sortable to arrange my list of items (and this http://dragsort.codeplex.com).
All works perfect.
I'm using a function on dragEnd to arrange the lists in order.
Here is my code:
$("#list1, #list2").dragsort({ dragSelector: "div",
                               dragBetween: true,
                               dragEnd: saveOrder,
                               placeHolderTemplate: "

" });

function saveOrder() {
    var data = $("#list1 li").map(function() { return $(this).children().html(); }).get();
    $("input[name=list1SortOrder]").val(data.join("|"));
};

My question: Is there anyway that I can do an animation while I'm dragging? Or reposition the elements while dragging? I just need it to work on Safari.
One example is this:
http://www.youtube.com/watch?v=U3j7mM_JBNw
Look at the drag/drop (0:30) and you'll see what I'm talking about.
Thanks.

A: While this solution works great to create an initial transition, when the item snaps back, there is no transition.  The solution is easier than I ever expected.  All you need to do is adjust the revert option in .sortable()
Like this:

jQuery UI API: http://api.jqueryui.com/sortable/#option-revert
This makes a nice and smooth transition to the item's new home.
Click here for EXAMPLE on jsFiddle

A: A bit late to the party, but I was determined to get a solution going with jQuery as there was very little help on this topic, especially replicating the functionality that exists on web apps like Facebook and their albums' images dragging and dropping to reorder, and the pretty animations that go along with that...
So I've come up with a solution that seems to work pretty great, and I'll do my best to explain it to the best of my abilities! Here goes...
The biggest problem here was to not only animate the sortables, but to figure out where they needed to animate to - fantastic when it comes to floating elements like images in a gallery! To get around this, I decided to .clone() the original floating LI items, position the clones absolutely under the original LI items using a z-index value that was less than the original LI items, and then when the change event fired from the jQuery sortable I could detect the position of the original LI and animate the absolutely positioned clones to those positions. The rest was to simply show / hide elements appropriately to get the desired effect.
Here's the code, starting with the HTML:

So we have the original items we're trying to sort, and a container for the cloned items. Time for the CSS:
#original_items, #cloned_items {
    list-style: none;
}

#original_items li {
    float: left;
    position: relative;
    z-index: 5;
}

#cloned_items li {
    position: absolute;
    z-index: 1;
}

With our CSS, we're just removing any list styling, floating our original elements, and setting up the z-index requirements to ensure the cloned items lie underneath the original items. Note the relative position on the original items to make sure they behave as expected. Why underneath you ask? It will (hopefully) become clear with some Javascript:
jQuery(function(){

    // loop through the original items...
    jQuery("#original_items li").each(function(){

        // clone the original items to make their
        // absolute-positioned counterparts...
        var item = jQuery(this);
        var item_clone = item.clone();
        // 'store' the clone for later use...
        item.data("clone", item_clone);

        // set the initial position of the clone
        var position = item.position();
        item_clone.css("left", position.left);
        item_clone.css("top", position.top);

        // append the clone...
        jQuery("#cloned_items").append(item_clone);
    });

    // create our sortable as usual...
    // with some event handler extras...
    jQuery("#original_items").sortable({

        // on sorting start, hide the original items...
        // only adjust the visibility, we still need
        // their float positions..!
        start: function(e, ui){
            // loop through the items, except the one we're
            // currently dragging, and hide it...
            ui.helper.addClass("exclude-me");
            jQuery("#original_items li:not(.exclude-me)")
                .css("visibility", "hidden");

            // get the clone that's under it and hide it...
            ui.helper.data("clone").hide();
        },

        stop: function(e, ui){
            // get the item we were just dragging, and
            // its clone, and adjust accordingly...
            jQuery("#original_items li.exclude-me").each(function(){
                var item = jQuery(this);
                var clone = item.data("clone");
                var position = item.position();

                // move the clone under the item we've just dropped...
                clone.css("left", position.left);
                clone.css("top", position.top);
                clone.show();

                // remove unnecessary class...
                item.removeClass("exclude-me");
            });

            // make sure all our original items are visible again...
            jQuery("#original_items li").css("visibility", "visible");
        },

        // here's where the magic happens...
        change: function(e, ui){
            // get all invisible items that are also not placeholders
            // and process them when ordering changes...
            jQuery("#original_items li:not(.exclude-me, .ui-sortable-placeholder)").each(function(){
                var item = jQuery(this);
                var clone = item.data("clone");

                // stop current clone animations...
                clone.stop(true, false);

                // get the invisible item, which has snapped to a new
                // location, get its position, and animate the visible
                // clone to it...
                var position = item.position();
                clone.animate({
                    left: position.left,
                    top:position.top}, 500);
            });
        }
    });
});

Wow, I really hope this makes sense and helps someone animate their sortable lists, but this is a working example for anyone who's interested! :)

A: Why did not you used Sortable on jqueryui? http://jsfiddle.net/KgNCD/
JS:
$( "#sortable" ).sortable({
    start: function(e, ui){
        $(ui.placeholder).hide(300);
    },
    change: function (e,ui){
        $(ui.placeholder).hide().show(300);
    }
});
$("#sortable").disableSelection();

HTML:

1

2

3

4

5

6

7

8

9

10

11

12

A: For anyone looking for a quick and easy solution to this, here is a plugin that allows you to quickly add sortable animations by specifying the animation length in the sortable parameters:
$('#sortable').sortable({
 animation: 200,
});

Demo: https://egorshar.github.io/jquery-ui-sortable-animation/
Github: https://github.com/egorshar/jquery-ui-sortable-animation

A: Just impleneted what Chris Kempen said:
http://jsfiddle.net/dNfsJ/
jQuery(function(){

// loop through the original items...
jQuery("#original_items li").each(function(){

    // clone the original items to make their
    // absolute-positioned counterparts...
    var item = jQuery(this);
    var item_clone = item.clone();
    // 'store' the clone for later use...
    item.data("clone", item_clone);

    // set the initial position of the clone
    var position = item.position();
    item_clone.css("left", position.left);
    item_clone.css("top", position.top);

    // append the clone...
    jQuery("#cloned_items").append(item_clone);
});

// create our sortable as usual...
// with some event handler extras...
jQuery("#original_items").sortable({

    // on sorting start, hide the original items...
    // only adjust the visibility, we still need
    // their float positions..!
    start: function(e, ui){
        // loop through the items, except the one we're
        // currently dragging, and hide it...
        ui.helper.addClass("exclude-me");
        jQuery("#original_items li:not(.exclude-me)")
            .css("visibility", "hidden");

        // get the clone that's under it and hide it...
        ui.helper.data("clone").hide();
    },

    stop: function(e, ui){
        // get the item we were just dragging, and
        // its clone, and adjust accordingly...
        jQuery("#original_items li.exclude-me").each(function(){
            var item = jQuery(this);
            var clone = item.data("clone");
            var position = item.position();

            // move the clone under the item we've just dropped...
            clone.css("left", position.left);
            clone.css("top", position.top);
            clone.show();

            // remove unnecessary class...
            item.removeClass("exclude-me");
        });

        // make sure all our original items are visible again...
        jQuery("#original_items li").css("visibility", "visible");
    },

    // here's where the magic happens...
    change: function(e, ui){
        // get all invisible items that are also not placeholders
        // and process them when ordering changes...
        jQuery("#original_items li:not(.exclude-me, .ui-sortable-placeholder)").each(function(){
            var item = jQuery(this);
            var clone = item.data("clone");

            // stop current clone animations...
            clone.stop(true, false);

            // get the invisible item, which has snapped to a new
            // location, get its position, and animate the visible
            // clone to it...
            var position = item.position();
            clone.animate({
                left: position.left,
                top:position.top}, 500);
        });
    }
});

A: From the jsfiddle answer above (http://jsfiddle.net/KgNCD/2/):
$( "#sortable" ).sortable({
    start: function(e, ui){
        $(ui.placeholder).hide(300);
    },
    change: function (e,ui){
        $(ui.placeholder).hide().show(300);
    }
});


text:
Q: Get information about audio file in Android I am new to Android and I want load an audio file (wav or mp3) from the file system and display audio information, such as sampling rate etc.
How can I do this? Do you know any examples?

A: You can approximate it by dividing the file size by the length of the audio in seconds, for instance, from a random AAC encoded M4A in my library:
File Size: 10.3MB (87013064 bits)
Length: 5:16 (316 Seconds)
Which gives: 87013064 bits / 316 seconds = 273426.147 bits/sec or ~273kbps
Actual Bitrate: 259kbps

Since most audio files have a known set of valid bitrate levels, you can use that to step the bit rate to the appropriate level for display.
Link to original answer by Jake Basile
Or use this code to get it much more accurate:
MediaExtractor mex = new MediaExtractor();
try {
    mex.setDataSource(path);// the adresss location of the sound on sdcard.
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

MediaFormat mf = mex.getTrackFormat(0);
int bitRate = mf.getInteger(MediaFormat.KEY_BIT_RATE);
int sampleRate = mf.getInteger(MediaFormat.KEY_SAMPLE_RATE);

Link to original answer by architjn


text:
Q: res.redirect does nothing in post response I have made a post request that makes sure the client hasn't altered the HTML or JS to trick the server. If they have I want to redirect them to /logOut so that all the changes they've made are reset, however nothing happens when they are redirected. The client side console will log if the URL isn't valid so the client definitely receives the URL. Any ideas why this is happening?
app.post('/tradeSend', (req, res) => {
    let steamIdValue = req.body[0]
    let steamInventoryApiLink = 'https://steamcommunity.com/profiles/' + steamIdValue + '/inventory/json/730/2'

    function bypassApi() {
        require('request-promise')({
            url: steamInventoryApiLink,
            proxy: 'xxxxxxxxxxxxx'
        }).then(function(data){
            console.log(`SUCCESS: ${steamIdValue}'s inventory has been recieved!`);
            for (let i = 1; i < req.body.length; i++){
                if(!data.includes(req.body[i].assetid)){
                    console.log('False Item!')
                    res.redirect('http://localhost:3000/logOut')
                    break
                }else{
                    console.log('Valid Item!')
                }
            }
        }).catch(function() {
            console.log(`ERROR: ${steamIdValue}'s inventory was not recieved, trying again...`);
            bypassApi()
        })
    }
    bypassApi()
})


text:
Q: TypeError: file() argument 1 must be encoded string without NULL bytes, not str odoo the python version is 2.8.2 and using it in eclipse. I am getting this error when I am trying to execute the following command:
The function is:
@api.one
@api.depends('image')
def _compute_image_details(self):
    if self.image:
        image_content = self.image.decode('base64')
        print type(self.image)
        print type(image_content)

        # File size
        self.size = len(image_content)

        # Camera make and model from EXIF tags
        img = PIL.Image.open(image_content)
        exif_tags = img._getexif()

        # 0x010f is a numeric code for the "make" exif field
        # You can find a list of fields here: exiv2.org/tags.html
        self.camera_maker = exif_tags.get(0x010f)

The error which is raised is:
Traceback (most recent call last):
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 537, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 574, in dispatch
    result = self._call_function(**self.params)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 310, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/service/model.py", line 113, in wrapper
    return f(dbname, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 307, in checked_call
    return self.endpoint(*a, **kw)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 803, in __call__
    return self.method(*args, **kw)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/http.py", line 403, in response_wrap
    response = f(*args, **kw)
  File "/home/next/WORKSPACE/odoo-8.0/addons/web/controllers/main.py", line 944, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/api.py", line 241, in wrapper
    return old_api(self, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/api.py", line 363, in old_api
    result = method(recs, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/models.py", line 5873, in onchange
    newval = record[name]
  File "/home/next/WORKSPACE/odoo-8.0/openerp/models.py", line 5571, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/home/next/WORKSPACE/odoo-8.0/openerp/fields.py", line 820, in __get__
    self.determine_draft_value(record)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/fields.py", line 928, in determine_draft_value
    self._compute_value(record)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/fields.py", line 867, in _compute_value
    self.compute(records)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/api.py", line 239, in wrapper
    return new_api(self, *args, **kwargs)
  File "/home/next/WORKSPACE/odoo-8.0/openerp/api.py", line 397, in new_api
    result = [method(rec, *args, **kwargs) for rec in self]
  File "/home/next/WORKSPACE/odoo-8.0/addons/transform_webservice_example/image_example.py", line 33, in _compute_image_details
    img = PIL.Image.open(image_content)
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1955, in open
    fp = __builtin__.open(fp, "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

Please help me with this issue.
The other references say about the URL of the file. This is different scenario.

A: You're trying to open the base64 decoded contents of the file, you're supposed to open the file itself.
PIL.Image.open(self.image)

take this for example, to reproduce the error you're getting
>>> open('\0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
>>>

the character '\0' is seen as a NullByte which the decoded image contains


text:
Q: Compress paddings of class members Suppose I have two structs:
// sizeof (Bool) == 1
struct Bool {
    bool val;  // 1 bit
               // 7 bits of padding
};

// sizeof (TwoBools) == 2
struct TwoBools {
    Bool b1, b2;  // 16 bits -- 14 of which are paddings!
};

As shown in the previous example, although TwoBools could've taken up only 1 byte (2 bits of bools and 6 bits of padding), the fact that each member Bool has its own padding causes greater space waste. Is it possible in any way to avoid this?
UPDATE: As @Olaf pointed out in the comment, my comments in the original code snippets are incorrect. This should be a correct example (on a specific computer, specific OS, with a specific compiler):
// sizeof (IntChar) == 8
struct IntChar {
    uint32_t i;  // 4 bytes
    char c;      // 1 byte
                 // 3 bytes of padding
};

// sizeof (TwoIntChars) == 16
struct TwoIntChars {
    struct IntChar a, b;  // 6 bytes of padding
};

// sizeof (CompactTwoIntChars) == 12
struct CompactTwoIntChars {
    uint32_t a, b;  // 8 bytes of ints
    char c, d;      // 2 bytes of chars
                    // 2 bytes of padding
};

A: The compiler is allowed to insert padding bytes, for alignment, between variables in a structure.
As far as Boolean variables go, there is a rule about the minimal addressable unit, which on many platform is one byte.
Some compilers may have pragmas that allow structures to be packed.
If you want to pack Boolean types, you may want to use bits instead.

A: There is no padding. The smallest addressable memory unit is one (1) byte. If you have two distinct addressable entities then you must use at least two (2) byte. The sizeof operator will return the size in bytes not in bits.
For your update: No, it is not avoidable within standard C++ (different memory alignment requirements for certain types on different platforms). It is avoidable for specific platforms with #pragma pack.


text:
Q: If I drive an LED whose forward voltage is 2V with a source that's 3.3V limited to 20ma, will I harm the LED? Background: I built a 10x20 LED matrix for use inside a jack-o-lantern. The matrix is driven by 74HC595 shift registers that are connected to an Arduino.
I've attached the Vcc of the shift registers to the 3.3V port of the arduino, so the output pins of the shift registers will be 3.3V when set high.
The datasheet for the shift register says each output pin can source at most 20ma, which is exactly the nominal current of my 3.3mm orange leds.
I know that power supplies can source much more than 20ma, so the use of current limiting resistors are necessary when the voltage is higher than the forward voltage, however is there any harm in exceeding the forward voltage if the current is clamped to the LED's nominal current rating?

A: Unless the output was designed specifically as a current limiter, the source limit specified on the datasheet doesn't mean "I will helpfully keep the current at this level for you," it means "you had better keep the current below this level or bad things will happen."  You need resistors on each output.

A: The 74HC595 isn't going to do what you want and it's not just the fact that the output current might not be carefully controlled.
If you look at the data sheet for the device and find the table that gives absolute maximum ratings you will see that the supply current to the device must not go greater than 70 mA: -

Now, if you are driving LEDs from output pins and using resistors to limit current, you have to face the fact that the total current you can supply to your LEDs (per chip) is less than 70 mA. Given that you might have 8 LEDs (all driven), the current you should be considering limiting at is going to have to be no more than 70mA/8 = 8.75 mA and I personally wouldn't recommend this high a level.
It's also worth noting that the limiting value for current per pin is 35mA and not 20mA. You might have someone else's data sheet that specifies a lower figure of course.


text:
Q: Activate script tags from turbo frames - Rails When we return turbo frames in post request sometimes it is esential run javascript for example if I am calling a resource to update, there are two possible cases

*

*when it saves sucessfully then close the modal

*When it is not saved then show validation messages in modal

In both cases I am sending frame (its intentional not to use redirect or render).
Recently I found this issue & PR in github which is now merged.
https://github.com/hotwired/turbo/pull/192
But it is not documented yet how to use it actually, Need help on that


text:
Q: Evaluation of len(string) that should be False is evaluated as True I read a file and split fields into variables and if I come into a variable which max length should be 32 I do this:
ragionesociale = Trim(Mid$(lineal, 159, 61))
TRF_RASO = ragionesociale
If len(TRF_RASO < 32) Then
    TRF_RASO = TRF_RASO & Space(32 - Len(TRF_RASO))
Else
    TRF_RASO = Left$(TRF_RASO, 32)
End If

When it comes to evaluate the first condition len(TRF_RASO < 32) it evaluates as True, while if in the immediate window I put
    ? len(ragionesociale)
It gives me 38, so only the Else should be evaluated. Why does vb evaluate the first as true?
I hope to be clear when explaining

A: You have:
len(TRF_RASO < 32)

(TRF_RASO < 32) is a False expression which is 5 characters long when coerced to a string & passed to Len(), hence the incorrect result.
Correct to:
if len(TRF_RASO) < 32


text:
Q: Consistency proof in topos logic Is the consistency of classical third-order arithmetic provable in the logic of a topos with natural numbers?
(My guess would be yes, but I haven't seen this anywhere.)
Edit: in the original version I used the name PA$_3$ as an abbreviation for classical third-order arithmetic, and comments have followed suit, but I've since learnt that this name refers to a different theory (the classical theory of third order functions).

A: Let $\Omega_{\neg\neg} = \{p \in \Omega \mid \neg\neg p \Rightarrow p\}$ be the object of $\neg\neg$-stable truth values, and let us write $P_{\neg\neg}(A) = {\Omega_{\neg\neg}}^A$ for the object of $\neg\neg$-stable subobjects of $A$. Observe that $\Omega_{\neg\neg}$ is a complete Boolean algebra, and this fact can be shown in the internal logic of a topos.
Now, it seems to me that one can build a model of $\mathsf{PA}_n$ for each $n$, by interpreting its logic in $\Omega_{\neg\neg}$, and the (higher-order) predicates as elements of the iterates of the $\neg\neg$-powersets ${P_{\neg\neg}}^k(\mathbb{N})$.
Supplemental: I initially claimed we can have a model of $\mathsf{PA}_\infty$, but Paul pointed out I was overstating the case. Indeed, to have a model of $\mathsf{PA}_\infty$ we would need a single object that encompasses all finite iterates $\neg\neg$-powersets ${P_{\neg\neg}}^k(\mathbb{N})$ at once, says something like $\coprod_{n \in \mathbb{N}} {P_{\neg\neg}}^k(\mathbb{N})$. However, in an elementary topos such an object need not exist. A counter-model is the set $V_{\omega + \omega}$ of sets of rank below $\omega + \omega$.


text:
Q: Setting a string to null in C Is setting a string to '\0' the same thing as setting a string to NULL in other languages?
Or... does setting a string to '\0' mean that the string is simply just empty?
char* str = '\0'

I have different functions to use for null strings and empty strings, so I don't want to accidentally call one of my empty string functions on a null string.

A: Your line char *str = '\0'; actually DOES set str to (the equivalent of) NULL. This is because '\0' in C is an integer with value 0, which is a valid null pointer constant. It's extremely obfuscated though :-)
Making str (a pointer to) an empty string is done with str = ""; (or with str = "\0";, which will make str point to an array of two zero bytes).
Note: do not confuse your declaration with the statement in line 3 here
char *str;
/* ... allocate storage for str here ... */
*str = '\0'; /* Same as *str = 0; */

which does something entirely different: it sets the first character of the string that str points to to a zero byte, effectively making str point to the empty string.
Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings.
Pointers, however, are the only objects in C that can be NULL.
And don't confuse the NULL macro with the NUL character :-)

A: No, in this case you're pointing to a real (non-null) string with a length of 0. You can simply do the following to set it to actual null:
char* str = NULL;


text:
Q: Translations of field operators in QFT A question in the book QFT of Srednicki: This concerns the relativistic QFT generalization
$$\tag{2.21} {{e}^{-i\hat{P}x/\hbar}}\psi (0){{e}^{i\hat{P}x/\hbar}}~=~\psi (x)$$
of the formula
$$\tag{2.20} {{e}^{i\hat{H}t/\hbar}}\psi (\vec{x},0){{e}^{-i\hat{H}t/\hbar}}~=~\psi (\vec{x},t)$$
from non-relativistic QM.
How can we prove this two formula just use Poincare algebra? $\psi (x)$ is an field operator. About the second formula we can use Schrodinger equation to prove. I think there is a proof just using the Poincare algebra. I just have no idea about this.

A: The formula $e^{-i\hat{P}a/\hbar}\hat\psi(x)e^{i\hat{P}a/\hbar}=\hat\psi(x+a)$ is just the finite transformation version of infinitesimal transformation version formula $[\hat{P},\hat{\psi}(x)]=i\hbar\partial_x\hat{\psi}(x)$ as mentioned by DaniH and Argopulos above. $e^{-i\hat{P}a/\hbar}$ is a finite transformation operator acting on the Hilbert space, while $x\rightarrow x+a$ is the finite transformation acting on the field space. The infinitesimal transformations or the generator of the Lie group is given by $\hat P$ and $i\hbar\partial_x$ accordingly.
Finite transformation can be derived from infinitesimal transformation as followed:
$e^{-i\hat{P}a/\hbar}\hat\psi(x)e^{i\hat{P}a/\hbar}=e^{-i(a/\hbar)[\hat{P},\cdot]}\hat\psi(x)=e^{-i(a/\hbar)(i\hbar\partial_x)}\hat\psi(x)=e^{a\partial_x}\hat\psi(x)=\hat\psi(x+a)$.

A: Taylor expand the right-hand side, and you will see that it matches, order by order in $x$, with the left-hand side. You just need to know the definition of $\hat{P}$, i.e. $[\hat{P},\hat{\psi}(x)]=i \hat{\psi}'(x)$, where the prime denotes derivative with respect to the coordinate associated to $\hat{P}$. Of course, you need to remember that the momenta all commute among each other (and in fact derivatives do commute). Back to your original intuition, you need to know in practice only the abelian subalgebra of the Poincaré algebra.

A: In the answer of Argopulos, one must assume that the Taylor series converges. This is never done, and maybe physicists don't care.
From a mathematical perspective, (2.20) is in fact the definition of the dynamics, and the commutator relation follows simply by differentiating both sides. No special assumption is needed to get this.

A: Symmetry group of the space time$^1$ on which QFT is defined is usually required to have a representation on the space of states.
Quantum mechanics is just QFT in one dimensions. The spacetime in this case is the time line $\mathbb R$. Fields are $X(t)$, and $P(t)$. Symmetry group is group of translations $t\rightarrow t+b$ of  $\mathbb R$. Infinitesimal form of (Hermitian) time translation operator is Hamiltonian $H=i\partial/\partial t$. One requires that Hilbert space of states have a representation of this group, which in Heisenberg picture is given as $$exp(iHt)X(0)exp(-iHt)=X(t),\:exp(iHt)P(0)exp(-iHt)=P(t)$$
The case of QFT on Minkowski space is similar. We again require the symmetry group (which is Poincare group in this case) to have a representation on the space of states. In particular for the subgroup of Poincare group generated by four translation operators $P_0,P_1,P_2,P_3$  we require
$$exp(iP_0x^0)\psi(0)exp(-iP_0x^0)=\psi(x^0,0,0,0)$$ $$exp(iP_1x^1)\psi(0)exp(-iP_1x^1)=\psi(0,x^1,0,0)$$ $$exp(iP_2x^2)\psi(0)exp(-iP_2x^2)=\psi(0,0,x^2,0)$$ $$exp(iP_3x^3)\psi(0)exp(-iP_3x^3)=\psi(0,0,0,x^3)$$ Since $P_\mu$'s commute with each other these conditions can be collectively written as :
$$exp(iPx)\psi(0)exp(-iPx)=\psi(x)$$  where $P=(P^\mu), \: P^\mu=\eta^{\mu\nu}P_\nu$ and $\eta=diag(1,-1,-1,-1)$. Sredniki's sign convention is different i think.

*

*For example if space time is a manifold with metric $\eta$ then symmetry group is group of transfomations which preserve $\eta$.


text:
Q: Memcached::increment() increases value by 2 in PHP for appengine The following code prints a number incremented by 2 every time I reload the page.
<?php
    //Memcahce
    $memcache = new Memcached;
    $memcache->increment('hits');
    echo "hitcount = ".$memcache->get('hits');

output
hitcount = 2

Expected : It should increment by 1.
I tried setting it to 2 and 5 but still it increments by 4 and 10 respectively.


text:
Q: How to connect to a RDS instance in a different AWS region I have an EC2 instance in one region, N.California. I have an RDS instance in EU/Ireland. I am not able to connect to the RDS instance from the EC2 instance, the connection times out. This tutorial by aws says that I would need to use the Public IP of the RDS instance in order to connect to it. But this public IP is not available on the AWS console, I'm not even sure if we're supposed to be using any other than RDS endpoints. We're also disallowed from adding a security group from one region to the security group of another.
I am really unsure about how to proceed.

A: I am answering my own question because my own solution worked, and it might be of use to someone else considering that the AWS tutorial is wrong.
To connect, add a custom tcp rule over port 3306 in the security group Ingress Rules for the RDS instance, with the EIP of your EC2 instance as the allowed host. Voila.


text:
Q: Execution plan changed for existing query - high CPU usage So few weeks ago we had an alert on our production MySQL database due to a CPU usage spike. We identified the issue as a query that had been there for several months that suddenly was misbehaving. The execution plan of that query is:
    +----+-------------+------------+------------+------+----------------------------------------------------------+----------------------------+---------+----------------------------+------+----------+----------------------------------------------+
    | id | select_type | table      | partitions | type | possible_keys                                            | key                        | key_len | ref                        | rows | filtered | Extra                                        |
    +----+-------------+------------+------------+------+----------------------------------------------------------+----------------------------+---------+----------------------------+------+----------+----------------------------------------------+
    |  1 | PRIMARY     | <derived2> | NULL       | ALL  | NULL                                                     | NULL                       | NULL    | NULL                       | 2485 |   100.00 | NULL                                         |
    |  2 | DERIVED     | c          | NULL       | ALL  | PRIMARY                                                  | NULL                       | NULL    | NULL                       | 7420 |    10.00 | Using where; Using temporary; Using filesort |
    |  2 | DERIVED     | app        | NULL       | ref  | applications_status_ix,applications_ibfk_3               | applications_ibfk_3        | 4       | prod_v3.c.id               |  750 |     0.41 | Using where                                  |
    |  2 | DERIVED     | inv        | NULL       | ref  | app_id                                                   | app_id                     | 4       | ref.app.app_id             |    1 |   100.00 | NULL                                         |
    +----+-------------+------------+------------+------+----------------------------------------------------------+----------------------------+---------+----------------------------+------+----------+----------------------------------------------+

What we did was to add an index hint to use applications_status_ix and then the query performance went back to normal and the CPU usage went down:
+----+-------------+------------+------------+--------+-------------------------------+-------------------------------+---------+----------------------------+--------+----------+---------------------------------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys                 | key                           | key_len | ref                        | rows   | filtered | Extra                                                               |
+----+-------------+------------+------------+--------+-------------------------------+-------------------------------+---------+----------------------------+--------+----------+---------------------------------------------------------------------+
|  1 | PRIMARY     | <derived2> | NULL       | ALL    | NULL                          | NULL                          | NULL    | NULL                       |   5077 |   100.00 | NULL                                                                |
|  2 | DERIVED     | app        | NULL       | range  | applications_status_ix        | applications_status_ix        | 1       | NULL                       | 464405 |    10.00 | Using index condition; Using where; Using temporary; Using filesort |
|  2 | DERIVED     | c          | NULL       | eq_ref | PRIMARY                       | PRIMARY                       | 4       | app.company_id             |      1 |    10.00 | Using where                                                         |
|  2 | DERIVED     | inv        | NULL       | ref    | app_id                        | app_id                        | 4       | app_id                     |      1 |   100.00 | NULL                                                                |
+----+-------------+------------+------------+--------+-------------------------------+-------------------------------+---------+----------------------------+--------+----------+---------------------------------------------------------------------+

Basically on the query we want certain application status that have a minimum appearance on the table. That's why is better using that index even with this cardinality:
+---------------------+------------+---------------------------------+--------------+-------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table               | Non_unique | Key_name                        | Seq_in_index | Column_name       | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------------------+------------+---------------------------------+--------------+-------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| applications        |          1 | applications_status_ix          |            1 | status            | A         |           9 |     NULL | NULL   |      | BTREE      |         |               |
| applications        |          1 | applications_ibfk_3             |            1 | company_id        | A         |       16240 |     NULL | NULL   |      | BTREE      |         |               |
+---------------------+------------+---------------------------------+--------------+-------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

So I have two questions:

*

*Why would the query planner suddenly decided use a different execution plan on a query that has been in use for a while? I do not have hard proof, but I really doubt the cardinality changed materially from what we have now.

*Trying to find a solution we found a about Histograms (values distribution is called on other DBMS). But unfortunately they are only available on MySQL 8 and we are still using version 5.7. Do you happen to know any other workaround on our MySQL versions?

EDIT1:
So the query being executed is
SELECT sum((CASE
                WHEN `alias_50656806`.`status` = 'CAPTURED' THEN `alias_50656806`.`amount`
                ELSE `alias_50656806`.`due_by` END - `alias_50656806`.`recovered_amount`))
FROM (SELECT `app`.`app_id`,
             `app`.`status`,
             `app`.`amount`,
             `app`.`purchases`,
             `app`.`due_by`,
             sum(CASE
                     WHEN (`inv`.`paid_at` IS NULL AND DATEDIFF(current_date(), `inv`.`created_at`) < 10) THEN 0
                     ELSE IFNULL(`inv`.`amount_due`, 0) END) AS `recovered_amount`
      FROM `applications` AS `app`
               JOIN `companies` AS `c` ON `app`.`company_id` = `c`.`id`
               LEFT OUTER JOIN `application_invoices` AS `inv` USING (`app_id`)
      WHERE (NOT (`app`.`repurchases`) AND
             `app`.`status` IN ('CAPTURED', 'LOCKED', 'ERROR') AND `c`.`is_test` = FALSE AND 1 = 1)
      GROUP BY `app`.`credit_app_id`, `app`.`status`, `app`.`credit_amount`, `app`.`cashless_repurchases`,
               `app`.`due_by`) AS `alias_50656806`;

An the table sizes are:

*

*applications has 12701431 records.

*companies has 7500 records

*the status distributions is

STATUS          COUNT (*)
RECOVER_FUNDS   46400
ERROR           18792
LOCKED          3
CAPTURED        151854

And applications table DDL is
CREATE TABLE `applications` (
  `app_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updated_at` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  `status` enum('PREAPPROVED','INCOMPLETE','DENIED','PENDING_DATA','PENDING_CC','FAILED_DATA','ERROR','READY','CAPTURED','EXPIRED','SETTLED','LOCKED','OPTED_OUT','RECOVER_FUNDS','EXCLUDED','ABANDONED','BAD_OPT') COLLATE utf8_bin NOT NULL,
  `account_code` enum('REF','NO_REF') COLLATE utf8_bin NOT NULL,
  `amount` int(10) unsigned NOT NULL,
  `customer_id` int(11) unsigned NOT NULL,
  `company_id` int(11) unsigned NOT NULL,
  `flow_id` int(11) unsigned NOT NULL,
  `app_ext_id` varchar(20) COLLATE utf8_bin NOT NULL,
  `cashless_repurchases` tinyint(1) NOT NULL DEFAULT '0',
  `random_no` float unsigned NOT NULL DEFAULT '0.5',
  `breakage_amount` int(11) DEFAULT NULL,
  `first_repurch` timestamp(3) NULL DEFAULT NULL,
  `last_repurch` timestamp(3) NULL DEFAULT NULL,
  `repurch_count` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `total_repurch_amount` int(10) unsigned NOT NULL DEFAULT '0',
  `due_by` int(10) unsigned DEFAULT NULL,
  `due_by_customer` int(10) unsigned DEFAULT NULL,
  `last_modified_by` varchar(64) COLLATE utf8_bin DEFAULT NULL,
  `app_user_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`app_id`),
  UNIQUE KEY `flow_id` (`flow_id`),
  UNIQUE KEY `app_ext_id` (`app_ext_id`),
  KEY `applications_customer_ix` (`customer_id`),
  KEY `applications_status_ix` (`status`),
  KEY `applications_ibfk_3` (`company_id`),
  CONSTRAINT `applications_ibfk_1` FOREIGN KEY (`flow_id`) REFERENCES `flow_entries` (`id`),
  CONSTRAINT `applications_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`),
  CONSTRAINT `applications_ibfk_3` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`),
  CONSTRAINT `applications_ibfk_4` FOREIGN KEY (`status`) REFERENCES `application_statuses` (`status`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=12709869 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

A: The values in filtered column in both execution plans look pretty off target. Maybe it would help to disable condition_fanout_filter optimizer switch in the session executing these multi-join queries (see more about condition filtering).

Why would the query planner suddenly decided use a different execution plan on a query that has been in use for a while? I do not have hard proof, but I really doubt the cardinality changed ...

It probably takes the growing applications table size into account even if the number of records to select is mostly constant. Maybe an optimizer switch to make it prefer larger tables as leading would help to reduce the probability of similar failures in other queries (somewhat like Oracle's DB_FILE_MULTIBLOCK_READ_COUNT). But I don't see any such feature in MySQL.

Do you happen to know any other workaround

Query optimizer is somehow able to estimate the number of selected rows in applications : 464405 . But that's at least twice as more as the actual count from "table sizes" section. Maybe just ANALYZE TABLE applications may help to reduce the estimate and get the better execution plan without hints?

A:
Why would the query planner suddenly decided use a different execution plan on a query that has been in use for a while?

Change in data sizes or patterns - as things grow you can go over set limit (or a ratio between cardinalities between two objects) that causes a plan to look worse. This is why it can be important to test with realistic data sizes (including expected growth over some years, plus a bit in case things grow faster) during QA and even in dev environments.
If you look at your forced index plan, it expects to need to touch nearly half a million rows instead of the ten-thousand-ish for the other plan. I'm not sure why it would flip now and not sooner, perhaps there was a middle-ground plan it was using before (if you have a backup from before the issue became apparent, you could perhaps restore to another DB/server to check that).

the status distributions is...

That is a lot less in total than the ~12.7Mrows in the table. Are there other values you've filtered from that list, or are the rest of the rows NULL in that column?

Do you happen to know any other workaround on our MySQL versions?

Not specific for that version (this can be true non-mysql DBs too, even): it will only be able to use one index per object, and in this query you are joining on company_id and filtering on status & others. In such circumstances a compound index (i.e. on company_id, status, and perhaps the others you are filtering on to avoid extra lookups so company_id, status, repurchases, is_test) can help a lot at the expense of a little disk space & memory due to the larger index.
In other DBs (MS SQL Server, Prosgres, ...) you can reduce the space hit by removing any index you have on just company_id and the compound index will be used instead (assuming company_id is the first column in the compound key) where that would be needed, but that is not an option with mysql as this is implicitly created by the existence of the FK.


text:
Q: How to input a list of websites, and it output list of IP's? Does anyone know of a way to simply output a website's IP address, that could be input in an excel sheet?
Ex.
www.cnn.com
www.google.com
www.superuser.com
IP1
IP2
IP3
Something in cmd would be fantastic.

A: NirSoft's FastResolver tool seems to do exactly what you want.
Type in a list of hostnames you want to get IPs for:

It will return the resolved IPs for the hostnames:

You can then copy & paste the returned data directly into Excel, or you can get an HTML report (in a table) for it.

You can also save the results in a variety of formats using the Save Items option:

You could save as CSV and open that with Excel, saving it in the format you desire.
It also works the other way (convert IP to hostname). You can also search a range of IPs and it will resolve the hostnames for those as well (useful for a local network!).

A: echo off
cls
set /p input= Website:
for /f "tokens=1,2 delims=[]" %%A in ('ping /n 1 /w 1 %input% ^| find "Pinging"') do set ipaddress=%%B
cls
echo %ipaddress%
pause > nul

to loop the script, just do this:
echo off

:loop
cls
set /p input= Website:
for /f "tokens=1,2 delims=[]" %%A in ('ping /n 1 /w 1 %input% ^| find "Pinging"') do set ipaddress=%%B
cls
echo %ipaddress%
pause

goto loop

Also, 'grep' should work for pulling a list of domains from a .txt. Just capture each line as a workable variable:
set site1=www.google.com
set site2=www.whatever.com

for /f "tokens=1,2 delims=[]" %%A in ('ping /n 1 /w 1 %site1% ^| find "Pinging"') do set ipaddress=%%B

You'll have to play around with your script a little bit..


text:
Q: "SCRIPT5: access denied" Message in Microsoft Edge I'm receiving the following error in Microsoft Edge (version 20.10240.16384.0):
SCRIPT5: access denied message in edge

Here is my code:
function getFrame( width, height ) {
    document.getElementById( this.contentid ).style.display = "none";
    this.frame = eval( this.editorid );
    return this.frame;
}

function init( width, height ) {
    this.frame = this.getFrame( width, height );
    this.doc = this.frame.document;  // <-- error
    // ~~~
}

The parent and child domains are both the same. Also, Edge doesn't appear to support eval.

A: The access denied message here is because you are trying to acccess the iframe.


text:
Q: Ajax Get call to ASP.NET MVC controller is treated as "NO 'Access-Control-Allow-Origin' error I am having a ajax call in view script. From this ajax call i am trying to get the data from controller action in same website. This is triggered as Cross No 'Access-Control-Allow-Origin' problem.
Java script code looks like
function displaydata(id) {
$.ajax({
    type: "GET",
    async: true,
    url: '@Url.Action("GetSomeData", "MyData")',
    contentType: "application/json; charset=utf-8",
    data: "id=" + id,
    dataType: "json",
    error: function (request, error) {

    },
    success: function (response) {
      alert(response);
    }
  });

My MyDataController.cs looks like
public class MyDataController : Controller
{
    [HttpGet]
    public string GetSomeData(int id)
    {
        // converted object to json string e.g. into jsonString
        return jsonString;
    }
}

This is working fine on local machine but after deployment actual site does not work. I receive the error No 'Access-control-allow-origin' found in header.
My question is that I am calling same server controller from which page is served so how it becomes the candidate for CORS issue?
And how to solve it?
as a technology I have website built in ASP.NET MVC razor view with Ajax and jquery.
I did some more tests and found that if I deploy the WebSite in IIS in One of the VM it's working. When I deploy it to cloud Web Apps then I get the same issue.

A: This helped me, although I don't do why some request from the same domain were getting blocked, just like yours.
if (Request.UserHostName == "127.0.0.1")
{
    Response.AddHeader("Access-Control-Allow-Origin", "*");
}

A: Add this lines into your web config file...
 And if it doesn't work let me know
 <system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="*" />
            <add name="Access-Control-Allow-Headers" value="*" />
        </customHeaders>
    </httpProtocol>
    <validation validateIntegratedModeConfiguration="false" />
   <modules runAllManagedModulesForAllRequests="true">
       <remove name="WebDAVModule" />
  </modules>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.5" />
        <add name="ExtensionlessUrlHandler-Integrated-4.5" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.5" />
        <remove name="WebDAV" />
    </handlers>
</system.webServer>


text:
Q: php or javascript Auto Print I want my application to print directly to the default printer without the Windows select printer dialog coming up and
I really dont need to display the screen. All the user wants is a printout, receipt.

A: No, you cannot do it.
You can only do window.print() with javascript and it displays the window.
Why you cannot: because safety.

A: No I'm afraid this is not possible. You could just run millions of print tasks at the time, and it wouldn't be good for user

A: yes, you can. In Firefox about:config you can make property print.always_print_silent equal to true.Then Firefox will print without prompt.
And using "JS Print setup" you can adjust some printer parameters directly from javascript

A: Short answer: you can't do that with JavaScript.


text: Q: By using a string like 'List', how can I get its class, just like classForName("List")? I want to execute a method by using reflect, the method has a parameter which is a List type, and the list type is not stable, maybe List《String》, List《someClass》. ect.


text:
Q: The correct CMakeLists.txt file to call a MAXON libarary in a Python script using pybind11 I'm very new to the whole CMake. Following this and this posts, now I want to call a MAXON function inside Python, using pybind11. What I have done so far:

*

*The library can be downloaded from this page (direct download link).

wget https://www.maxongroup.com/medias/sys_master/root/8837358518302/EPOS-Linux-Library-En.zip

*

*unzip:

unzip EPOS-Linux-Library-En.zip

*

*make the install shell script executable and run it:

chmod +x ./install.sh
sudo ./install.sh

*

*Then going to the example folder:

cd /opt/EposCmdLib_6.6.1.0/examples/HelloEposCmd/

*

*Now combining the CMakeLists.txt files from here:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8.12)
project (HelloEposCmd)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall")

set(CMAKE_POSITION_INDEPENDENT_CODE ON)

find_package(pybind11 REQUIRED)
pybind11_add_module(${PROJECT_NAME} HelloEposCmd.cpp)

add_executable(${PROJECT_NAME} HelloEposCmd.cpp)

target_link_libraries(${PROJECT_NAME} -lEposCmd)

*

*and the HelloEposCmd.cpp this line is added right after other header files:

#include <pybind11/pybind11.h>

the main function is renamed to:
int run(int argc, char** argv)

and the pybind11 syntax to add the module is written at the end:
PYBIND11_MODULE(HelloEposCmd, m) {

    m.def("run", &run, "runs the HelloEposCmd");
}

However, When I run the cmake . I get the error:

CMake Error at CMakeLists.txt:13 (add_executable):
add_executable can not create target "HelloEposCmd" because another target with the same name already exists. The existing target is a module library created in source directory "/opt/EposCmdLib_6.6.1.0/examples/HelloEposCmd" See documentation for policy CMP0002 for more details.
...

I was wondering if you could be kind to help me get the right CMakeList.txt file. Ideally, I should be able to call the compiled module in python:
# HelloEposCmd.py

import HelloEposCmd

HelloEposCmd.run()

Thanks for your support in advance.

A: pybind11_add_module already creates a target for you. So you don't need add_executable anymore. Just remove that line and when you will build you will get a library with the name HelloEposCmd
add_executable is needed if you are building an executable (.exe), which I believe is not what you want.
Documenation of pybind11 says.

This function behaves very much like CMake's builtin add_library (in fact, it's a wrapper function around that command).

A: Thanks to abhilb post and his kind followup in the comments I was able to figure the problem out. well, at least find a temporary workaround:

*

*According to this post, the last two lines of the CMakeLists.txt file should change to

# this line can be removed
# add_executable(${PROJECT_NAME} HelloEposCmd.cpp)

target_link_libraries(${PROJECT_NAME} PRIVATE -lEposCmd)

*

*and then because according to this post pybind11 doesn't support double pointers we change the run function to:

int run() {

    int argc = 1;
    char* argv[] = {"./HelloEposCmd"};

...
}

which I suppose to be a horrible workaround (inspired by information from this page). Now running cmake ., make and python3 HelloEposCmd.py should work properly (except a small c++ warning!).
P.S.1. Maybe someone could use std::vector<std::string> as suggested here. This idea was proposed here and there are already some answers worth investigating.
P.S.2. Following this discussion, another workaround could be something like:
#include <stdio.h>
#include <stdlib.h>

void myFunc(int argc, char* argv[]) {
    for (int i = 0; i < argc; ++i) {
        printf("%s\n", argv[i]);
    }
}

int run(int argc, long* argv_) {

    char** argv = (char**)malloc(argc * sizeof(char*));

    for (int i = 0; i < argc; ++i) {
        argv[i] = (char*)(argv_[i]);
    }

    myFunc(argc, argv);

    free(argv);

    return 0;
}


text:
Q: Can Clock with direct QueryPerformanceCounter value be conforming to C++ Standard? Assuming I want to create Clock with direct QueryPerformanceCounter Windows API result. QueryPerformanceCounter Windows API returns some counter that should be divided by QueryPerformanceFrequency result, thus producing time in seconds.
Usually Clock based on QueryPerformanceCounter would immediately convert result to some units by multiplying by some period and dividing by QueryPerformanceFrequency. This is how steady_clock could be implemented on Windows.
But suppose that for performance reasons I want to avoid division until really needed. So time_point is direct QueryPerformanceCounter value, and duration is the difference of such. And I can perform arithmetic and comparison on those values most of the time, converting to some normal duration or time_point only the final result.
I'm sure it is possible. My question is: will such Clock be fully compatible with standard Clock.

A: It won't be fully compatible with the standard Clock Requirements.  But it will compile and do what you want, most of the time.  The part that doesn't conform is that you will have to specify something for the period that your time_point is based on.  And that something won't necessarily correspond to physical time units.
This won't matter until you subtract two of these time_points, get a duration, and then compare that duration with something that does represent physical time.  Then you'll get run-time garbage.
Also if you use such a time_point in sleep_until, or wait_until, then your program won't sleep or wait for the intended time.
Here is an example chrono clock based on QueryPerformanceCounter that does nail down the physical units with QueryPerformanceFrequency:  https://stackoverflow.com/a/15755865/576911

A: Clock with redefined time_point and duration that do not correspond to the period known at compile time do no meet Clock requirements, as Howard Hinnant explained.

Using a class emulating an arithmetic type to hide additional implementation details does not work.
As Standard does not define what is this emulation, the opportunity of using emulating type is only available to the clocks provided by standard implementation. As a practical proof, std::chrono and boost::chrono do not work well with boost::rational.

However, the general task to avoid divison on each time query has at least two practical solutions.
First solution is to follow the intention to delay division until needed, but not redefining time_point and duration. Define standard-conforming clock, and, as an extension, define the interface for raw timestamp. So, clock may have raw_now() method, returning raw_time_point type, difference of such is raw_duration type. raw_time_point may be implicitly convertible to time_point and raw_duration to duration.

Second solution is to calculate standard-conforming time_point for each time query, but use libdivide library that performs fast division without division operation.
The library takes divisor and processes it so that each division using processed divisor is done using fast operations. Sure, it takes time to process divisor, but for repeated division with the same divisor it is one-time overhead. So this library looks like an ideal match for this task. (Note that the library is not useful for constants known at compile time, since in this case compiler avoids division by itself, but QueryPerformanceFrequency result is run-time constant).


text:
Q: What is the Razor syntax to dynamically require an Html.TextBoxFor based on specified conditions? I've got a form where a description field will be required in some situations, and not required in others.  Originally, it was always required and I had the required attribute in the model, like so:
[DisplayName("Description")]
[Required(ErrorMessage = "Please enter a description.", AllowEmptyStrings = false)]
public string PaymentDescription { get; set; }

Now we only want this to be required only under some circumstances.  So I removed the required data annotation from the model. And I tried a few things, including this:
@if (isDescriptionRequired)
{
    @Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
    @Html.ValidationMessageFor(m => m.PaymentDescription, "Please enter a description.")
}
else
{
    @Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
}

But that's not working.  What is the most appropriate way to dynamically set the required attribute for a model property based on some data condition?  I'm open to other approaches outside sticking the logic in the view. The bottom line is I need that field to be required sometimes, and not required other times. Thanks for your help.
=== Edit 8/21/2015 at 8:00 am CST ===
After investigating MVC Foolproof Validation, and some other [RequiredIf] extensions, I opted for something simpler. It's unclear to me if foolproof works with MVC 4, and other solutions seemed unnecessarily complex, lacked client-side validation, or lacked sufficient cross-browser testing for the client-validation scripts.
Stick 2 properties in the Model to represent a single property:
// Property 1 of 2 to represent Description.  Work around for requiring Description in special cases.
[DisplayName("Description")]
public string PaymentDescription { get; set; }

// Property 2 of 2 to represent Description. Work around for requiring Description in special cases.
[DisplayName("Description")]
[Required(ErrorMessage = "Payment description is required.", AllowEmptyStrings = false)]
public string PaymentDescriptionRequired { get; set; }

In the View conditionally display the controls for the relevant property.
if (Model.RequirePaymentApproval)
{
    @Html.LabelFor(m => m.PaymentDescriptionRequired, new { @class = "control-label" })
    @Html.TextBoxFor(m => m.PaymentDescriptionRequired, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
    @Html.ValidationMessageFor(m => m.PaymentDescriptionRequired)
}
else
{
    @Html.LabelFor(m => m.PaymentDescription, new { @class = "control-label" })
    @Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
    @Html.ValidationMessageFor(m => m.PaymentDescription)
}

Then in the Controller post evaluate the conditional property bool (RequirePaymentApproval), and assign the required value to the non-required property, or remove the required property from ModelState.
if (model.RequirePaymentApproval)
{
    model.PaymentDescription = model.PaymentDescriptionRequired;
}
else
{
    ModelState.Remove("PaymentDescriptionRequired");
}

if (ModelState.IsValid) {
    // Save changes
}

This approach has the benefit of being able to use the built in Microsoft data annotation validation code, which has a proven record of being cross-browser compliant. And it's relatively easy to follow. What I don't like is that it seems verbose, and I dislike sticking the conditional validation logic in both the view and the controller.
Perhaps Microsoft will extend the data annotation library in the future to handle more real-world scenarios like this.
I'm leaving this open for now because better developers than I will likely have more elegant recommendations. Thanks.
Related Research:

*

*http://forums.asp.net/t/1924941.aspx?Conditional+Validation+using+DataAnnotation

*http://foolproof.codeplex.com/

*http://andrewtwest.com/2011/01/10/conditional-validation-with-data-annotations-in-asp-net-mvc/

*http://www.compiledthoughts.com/2011/02/aspnet-mvc-excluding-model-validation.html

*http://blogs.msdn.com/b/stuartleeks/archive/2011/10/06/flexible-conditional-validation-with-asp-net-mvc-3.aspx

*Is it correct way to use ModelState.Remove to deal with ModelState?


text:
Q: Using Google Maps in fragments with compatibility android support libs for android I want to use google maps as one of the fragments of many. I found no other way then the one mentioned in the following way...
https://stackoverflow.com/a/8126287
and I was successful
But now I have 2 problems

*

*I want to call a public method of the MyMapActicity(MyMapActivity is created as mentioned in the link given above) from another fragment. i.e. e.g. if I have fragmentA as some other fragment and MapFragment as a fragment related to MyMapActivity(created with help of above link) then I want to call a method from MyMapActivity from FragmentA. How do I do this.

*I also want to resume the fragment with it is called...

A: I got my answer at:
https://stackoverflow.com/a/8126287
The link also provides a very nice example to follow. As I have only one activity this worked for me.

A: Have you tried using Action Bar Sherlock?  http://actionbarsherlock.com/


text:
Q: How can the Therns change their physical bodies? I have read that the Therns are like any normal Martian, but how can they change their physical bodies? Is it like a disguise?

A: In the book, the Therns do not have any form of shapeshifting powers (they live hidden from the rest of the world, at the end of the Ys river, posing as gods).
In the movie, this appears to be a function of their medallions and bracelets rather than a natural ability: While changing appearance, the Therns eyes glow with a pale blue light also present in all other applications of the Ninth ray shown in the movie (as a weapon or powering their strange pyramidal structure).


text:
Q: After so much travel and research, why did Newt Scamander write such a simple book which lacks details? Newt Scamander has researched a lot on magical creatures and yet if you compare his book Fantastic Beasts and Where to Find Them with Darwin's books, it'd look nothing.
Why did Newt Scamander write such a simple book which doesn't even have those details which Newt Scamander knew in Fantastic Beasts movie series?

A: The version we see is written for Muggles.
The two versions of Fantastic Beasts and Where to Find Them available for purchase are both written for Muggles.

"This edition, however, has a loftier purpose than the instruction of the wizarding community. For the first time in the history of the noble publishing house of Obscurus, one of its titles is to be made available to Muggles." - Fantastic Beasts and Where to Find Them

They're for Muggles to read while still having the Muggles believe that the creatures described in it are fictional, so presumably the Muggle editions would be less detailed than the editions sold exclusively to wizards and never seen by Muggles.

"I would like to take this opportunity to reassure Muggle purchasers that the amusing creatures described hereafter are fictional and cannot hurt you. To wizards, I say merely: Draco dormiens nunquam titillandus." - Fantastic Beasts and Where to Find Them

Since Muggles are still supposed to not believe in the creatures written about, it's very likely certain details would be left out, and the descriptions wouldn't be as in-depth as in the editions for wizards. It'd be wise to leave out any ways of catching these creatures or particularly specific locations where any of them are found, lest any curious Muggles try to find them, leading to violations of Clause 73 of the International Code of Wizarding Secrecy.

"In 1750, Clause 73 was inserted in the International Code of Wizarding Secrecy, to which wizard ministries worldwide conform today:
Each wizarding governing body will be responsible for the concealment, care, and control of all magical beasts, beings, and spirits dwelling within its territory's borders. Should any such creature cause harm to, or draw the notice of, the Muggle community, that nation's wizarding governing body will be subject to discipline by the International Confederation of Wizards." - Fantastic Beasts and Where to Find Them

It's logical that the version of this wizarding book that's made available to Muggles would include less information than the wizards' editions, since giving Muggles too much knowledge about magical creatures would be a danger to magic remaining secret. As Valorum mentions in the comments, the copies of Fantastic Beasts and Where to Find Them seen at Newt's book launch are at least double the size of the Muggle version.

The version seen at Newt's book launch is also clearly shown to be much larger than the Muggle editions in the Flourish and Blotts advertisement for it.

Therefore, it seems clear that the versions of Fantastic Beasts and Where to Find Them that's sold exclusively to wizards contains more information than the Muggle editions.


text:
Q: append multiple dataframes in a single df using the index position in python I have a multiple dataframes in the below format. 0 and 1 represents the index within a single DF in a sequential order(For example column name emp_number has length as 55 from the below sample)
0 Tablename
1 xyz
0 Tablename
1 xyz

0  colName
1   emp_number
0 colName
1 Organization_unit

0 ColumnLen
1 55
0 ColumnLen
1 60

I need the output in the following format
TableName  ColumnName         ColumnLen

xyz        emp_number          55
xyz        Organization_unit   45
xyz        pos_unit            60

I tried this code
      for row in df.index:
            print(row)
 for value in df.index.values:
            print(value)

but I am getting output as 0 and 1 only , not the actual values
I want to merge  all the DF and put in a single huge DF which can used for running SQL on the DF
My Sample input Data contains which is a result of some other process
data = ('tablename', 'xyz') ('tablename','xyz') ('columnname', 'emp_number')('columnname', 'Organization_unit')('columnlen', 55)('columnlen', 60)

post which I have added my DF like this
df = pd.DataFrame.from_dict(data)

After which I got the out
[2022-05-17T09:27:01.162Z] 0       columnName
[2022-05-17T09:27:01.163Z] 1       emp_number
[2022-05-17T09:27:01.163Z]                  0
[2022-05-17T09:27:01.164Z] 0       columnName
[2022-05-17T09:27:01.164Z] 1        Organization_unit
[2022-05-17T09:27:01.217Z] 0        columnlen
[2022-05-17T09:27:01.218Z] 1             55
[2022-05-17T09:27:01.218Z]               0
[2022-05-17T09:27:01.217Z] 0        columnlen
[2022-05-17T09:27:01.218Z] 1             60
[2022-05-17T09:27:01.218Z]               0

and I want a dynamically generated from a DF because I dont know how many small dfs that are created as a result of previous process.

A: Input

### assuming this is your data
data = ('tablename', 'xyz'),('tablename','xyz'),('columnname', 'emp_number'),('columnname', 'Organization_unit'),('columnlen', 55),('columnlen', 60),('edge_cases','so edgy')

### create empty lists that will be your columns in your final df
TableName_list = []
ColumnName_list = []
ColumnLen_list = []

### iterate over tuples looking at what first element (x[0]) is
### and checking it for values of interest and appending to corresponding lists
for x in data:
    if x[0] == 'tablename':
        TableName_list.append(x[1])
    elif x[0] == 'columnname':
        ColumnName_list.append(x[1])
    elif x[0] == 'columnlen':
        ColumnLen_list.append(x[1])

    ### check if there are some other / unexpected values and print them out
    else:
        f"you have some other data here too like this one where first element == {x[0]}"
        f"`````````````````````````````````````````````````````````"

### create your final dataframe from lists above
final_df = pd.DataFrame({'TableName':TableName_list,
                         'ColumnName':ColumnName_list,
                         'ColumnLen':ColumnLen_list
                        })

final_df

Output


text:
Q: c++ call superclass constructor with calculated arguments probably it's super easy, but can someone tell me how I can call the superclass' constructor with arguments calculated in the subclass' constructor? something like this:
class A{
  A(int i, int j);
};

class B : A{
  B(int i);
};

B::B(int i){
  int complex_calculation_a= i*5;
  int complex_calculation_b= i+complex_calculation_a;
  A(complex_calculation_a, complex_calculation_b);
}

//edit: i edited the example so that the superclass takes two arguments which have a relation to each other

A: If you cannot express your calculation in a single-line expression, add a static function, and call it in the way you normally call the constructor of the superclass:
class B : A{
public:
    B(int i) : A(calc(i)) {};
private:
    static int calc(int i) {
        int res = 1;
        while (i) {
            res *= i--;
        }
        return res;
    }
};

EDIT Multiple-argument case:
class B : A{
public:
    B(int i) : A(calc_a(i), calc_b(i)) {};
private:
    static int calc_a(int i) {
        int res = 1;
        while (i) {
            res *= i--;
        }
        return res;
    }
    static int calc_b(int i) {
        int complex_a = calc_a(i);
        return complex_a+10;
    }
};

A: B::B(int i)
    : A(i * 5)
{}

With C++11, a more complex way is
B::B(int i)
    : A(([](int x) { return 5 * x; })(i))
{}

For complex cases, a protected init function is more readable.

A: Only like this:
class A{
  A(int i);
};

class B : A{
  B(int i);
};

B::B(int i) : A(i*5) {
}

The call to the parent's constructor can only come in the initialization list. Which means, that whatever you're calculating must be known before B is fully constructed (i.e.: you can't call a B member function, unless its static, but only to rely on the parameters passed to B)

A: struct A
{
    A(int);
};

struct B : public A
{
    B()
        : A(5) // "initialisation list"
    {}
};

You have to do this inside the list, but you can use a function.
Edit: If you use a function, you probably want to make it a private static member of B.

A: class A
{
public:
   A(int i){}
};

class B : public A
{
public:
    B(int i):A(i*5){}
};


text:
Q: Minecraft command: villager trading adventure mode items Can someone tell me why this command doesn't work?
/summon Villager ~ ~1 ~ {CustomName:Jerry,CustomNameVisible:0,NoAI:1,Offers:{Recipes:[{maxUses:10,buy:{id:lever,Count:1,Damage:#},buyB:{id:cooked_porkchop,Count:30,Damage:#},sell:{id:lever 1 0 {CanPlaceOn:["minecraft:diamond_ore"]},Count:1,Damage:#}}]}}

the villager isn't selling adventure mode item

A: Your id value for the sell compound is incorrect. It appears you may have copy/pasted a /give command into NBT data. The entire line "lever 1 0 {CanPlaceOn:["minecraft:diamond_ore"]}" is seen as the item's ID, which is invalid.
Any tags that are not the root id, Damage, Count, and Slot must be placed within a single tag compound.
Fixed command:
/summon Villager ~ ~1 ~ {CustomName:Jerry,CustomNameVisible:0,NoAI:1,Offers:{Recipes:[{maxUses:10,buy:{id:lever,Count:1,Damage:0},buyB:{id:cooked_porkchop,Count:30,Damage:0},sell:{id:lever,Count:1,Damage:0,tag:{CanPlaceOn:["minecraft:diamond_ore"]}}}]}}


text:
Q: OpenCV: Failed to correctly use LineIterator, gives meaningless values I am experiencing a very strange behavior in my following program. I am basically iterating through 2 points on an image and collecting all the pixel values in a variable linePixels.
I pass the two points from main() correctly, since I verified before passing to IterateLine() and inside IterateLine(). I saw both are equal.
But The linePixels I always get as 114.
But If I hardcode the points (start and end ), inside IterateLine(), then I get meaningful values.
I am not able to understand what wrong here ? Something is there which I am missing.
Please help.
void IterateLine( const Mat& image, vector<ushort>& linePixels, Point p2, Point p1, int *count1 )
{
     //Am I getting correct image?
    cout<<"Pixel values in image in IterateLine"<<endl;

    cout<<Mat(image)<<endl; //Yes this shows meaningful values indeed

 //hard coding pixel coordinates for debugging. Prints meaningful pixel values at end
p1.x=32;
p1.y=66;

p2.x=230;
p2.y=86;

//but If I do not use hard coded values as above, then it always prints 114

//Am I getting correct pixel coordinates? Let us print
cout<<"First coordinates received in IterateLine()  are given below"<<endl;
cout<<p1.x<<'\t'<<p1.y<<endl;

cout<<"Second coordinates received in IterateLine()  are given below"<<endl;
cout<<p2.y<<'\t'<<p2.y<<endl;

//The above indeed prints meaningful coordinates, but only when pixel values are hard coded

    LineIterator it(image, p2,p1, 8);

    for(int i = 0; i < it.count; i++, it++){
        linePixels.push_back(image.at<ushort>(it.pos()));
    }

   *count1=it.count;

    cout<<"No. of pixels in IterateLLine"<<endl;

    cout<<count1[0]<<endl;

cout<<"pixel values in  IterateLine are"<<endl;

    for(int i=0;i<count1[0];i++)

    {

        cout<<linePixels[i]<<endl;
    }

}

Output when pixel coordinates are hard coded:
First coordinates passed to IterateLine() in main() are given below
  10     15
Second coordinates passed to IterateLine() in main() are given below
  200    150
First coordinates received in IterateLine()  are given below
32      66
Second coordinates received in IterateLine()  are given below
230     86
No. of pixels in IterateLLine
199
pixel values in  IterateLine are
42405
41634
36237
34952
43947
26471
26985
27756
29555
35723
23901
24415
38807
25186
25186
42662
29041
29812
42405
34438
35209
42148
35980
36751
38807
28013

Output when pixel coordinates are not hardcoded
First coordinates passed to IterateLine() in main() are given below
96      56
Second coordinates passed to IterateLine() in main() are given below
192     160
First coordinates received in IterateLine()  are given below
 96      56
Second coordinates received in IterateLine()  are given below
 192     160
No. of pixels in IterateLLine
204
pixel values in  IterateLine are
114
114
114
114
114
114
114
114
114
114
114
114
114

My main() is as shown below:
int main()

{

     Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);

 vector<Point> points1;

 vector<ushort>linePixels;

 //Draw the line, and collect end and final point coordinates in points1

      drawline(img, points1);

//now check the collected points

cout<<"First coordinates passed to IterateLine() in main() are given below"<<endl;
cout<<points1[0].x<<'\t'<<points1[0].y<<endl;

cout<<"Second coordinates passed to IterateLine() in main() are given below"<<endl;
cout<<points1[1].x<<'\t'<<points1[1].y<<endl;

IterateLine( img, linePixels, points1[1], points1[0], t );

return 0 ;
}

Update
This is my drawline()
void drawline( Mat image, std::vector<Point>& points )

{

cv::namedWindow("Output Window");

cv::setMouseCallback("Output Window", onMouse, (void*)&points);
int X1=0, Y1=0, X2=0, Y2=0;

while(1)
{
    cv::imshow("Output Window", image);

    if (points.size() > 1) //we have 2 points
    {

        for (auto it = points.begin(); it != points.end(); ++it)
        {

        }

        break;
    }
    waitKey(10);

}

 X1=points[0].x;
X2=points[1].x;

Y1=points[0].y;
Y2=points[1].y;

     //   Draw a line

line(image,  Point(X1, Y1), Point(X2, Y2), 'r',  2, 8 );

cv::imshow("Output Window", image);

//exit image window
while(true)
    {
        char c = cv::waitKey(10);
        if(c == 'q')
            break;
    }

destroyWindow("Output Window");

}

Update 2
As pointed out by @berak actually I am iterating over the line that I have drawn. This line has a single color and that is why I get 114. So I must make the line transparent to IterateLine() (but visible to human beings). Any suggestions how to achieve this?
Update 3
I solved this my reading a the original image once again in a new Mat object img1:
    Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    drawline(img, points1);
    Mat img1 = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    IterateLine( img1, linePixels, points1[1], points1[0], t );

But this is not very efficient method, so I am still looking for best way of doing this.