text:
Q: TLS 1.2 on the Fleetboard When testing the App it was noticed that it works, but no data readings are passed to the backend.
The error message is an SSLHandshakeException with reference to a version mismatch.
The MQTT Broker in the backend enforced TLS 1.2, in the debugging of app page I noticed, that the MQTT Client only uses TLS 1.0 as "enabled Protocols".
A short research shows that the availability of TLS 1.2 for Android <= 4.4 seems to be a common problem:
https://ankushg.com/posts/tls-1.2-on-android/
The following points must be checked for the solution:

*

*Is TLS 1.2 installed as a protocol on the fleet boards?

*Is the protocol enabled?

*Is the MQTT client compatible?

A: TLS 1.2 should work when using customized clients for http or mqtt.


text:
Q: iPhone app : MPMoviePlayer: PlayVideo in Landscape mode only I have an iPhone app which runs in portrait mode only. But I want to make mpmovieplayer to play video in landscape mode only.
How can I achieve that?
Here is the code.
    NSString *path = [[NSBundle mainBundle] pathForResource:lblVideoName.text ofType:@"mp4" inDirectory:nil];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    NSLog(@"URL== %@",url);
    moviePlayer =  [[MPMoviePlayerController alloc]
                    initWithContentURL:url];

    moviePlayer.controlStyle = MPMovieControlStyleDefault;
    moviePlayer.shouldAutoplay = YES;
    [self.view addSubview:moviePlayer.view];
    [moviePlayer setFullscreen:YES animated:YES];

A: You can present the movie in it's own view controller that's setup for landscape.
// in the VC where the user indicates he wants to see a movie...
- (void)startTheMovie {
    // run a storyboard segue with a modal transition, or ...
    MyMovieVC *movieVC = [[MyMovieVC alloc] initWithNibName:@"MyMovieVC" bundle:nil];
    [self presentModalViewController:movieVC animated:YES];
}

// in MyMovieVC

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
        (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

// and the code that you wrote on view will appear

You can include a dismiss button in this interface, or, the youtube way is to have it dismiss itself.  You can do that by subscribing to the finished notification:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayerFinished:)
name:MPMoviePlayerPlaybackDidFinishNotification object:nil];

then, on the finished message
- (void)moviePlayerFinished:(NSNotification*)notification {
    [self dismissModalViewControllerAnimated:YES];
}

Note, if you're doing this in a tabbed interface, all the tabs - even the ones not visible - need to agree to let the interface turn landscape.  This makes some sense but has caused me heartache in the past.  I don't have a pretty solution to this.  My approach has been a publicly accessible BOOL isLandscapeOK on my AppDelegate.  This MovieVC would set it to YES, and the other tab VCs would answer portrait or landscape if isLandscapeOK==YES.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a csv file in adove xd plugin I am writing a adove XD plugin. I am trying to save some data in a csv file and save it. But my code is not working.
const rows = [
  ["doc1", "layer1", "size1"],
  ["doc1", "layer2", "size2"]
];
const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;

const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()


text:
Q: AWS Codeploy unauthorized when connecting to a Github organization repo Recently, I've started experiencing failures in my deployments in CodeDeploy. This problem is always happening at the Download Bundle phase, which is logging the following error:

Error CodeUnknownError
Script Name
MessageCould not download bundle at
  'https://api.github.com/repos/org_name/repo_name/tarball/commit' after
  3 retries. Server returned codes: 401 'Unauthorized'; 401
  'Unauthorized'; 401 'Unauthorized'; 401 'Unauthorized'.
Log Tail

I already authorized CodeDeploy access for my organization.
Thanks in advance!

A: Do you have access to the private token that Github created and provided to CodeDeploy? Can you confirm that if you use that token you can download from GitHub yourself?
Thanks
-Asaf


text:
Q: Oracle LEAD - return next matching column value I having below data in one table.

And I want to get NEXT out data from OUT column. So used LEAD function in below query.
SELECT ROW_NUMBER,TIMESTAMP,IN,OUT,LEAD(OUT) OVER (PARTITION BY NULL ORDER BY TIMESTAMP) AS NEXT_OUT
FROM MYTABLE;

It gives data as below NEXT_OUT column.

But I need to know the matching next column value in sequential way like DESIRED columns. Please let me know how can i achieve this in Oracle LEAD FUNCTION
THANKS

A: Enumerate in the "in"s and the "out"s and use that information for matching.
select tin.*, tout.out as next_out
from (select t.*,
             count(in) over (order by timestamp) as seqnum_in
      from t
     ) tin left join
      (select t.*,
             count(out) over (order by timestamp) as seqnum_out
      from t
     ) tout
     on tin.in is not null and
        tout.out is not null and
        tin.seqnum_in = tout.seqnum_out;

A: Assign row number to all INs and OUTs separately, sort the results by placing them in a single column and calculate LEADs:
WITH cte AS (
    SELECT t.*
         , CASE WHEN "IN"  IS NOT NULL THEN COUNT("IN")  OVER (ORDER BY "TIMESTAMP") END AS rn1
         , CASE WHEN "OUT" IS NOT NULL THEN COUNT("OUT") OVER (ORDER BY "TIMESTAMP") END AS rn2
    FROM t
)
SELECT cte.*
     , LEAD("OUT") OVER (ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST) AS NEXT_OUT
FROM cte
ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST

Demo on db<>fiddle


text:
Q: Prediction only single class I implement transfer learning using VGG16 to classify the diabetic retinopathy disease binary classification. Even after balancing the classes my model predicts only the single class. why does this happens. Below is my code
base_model=VGG16(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(1,activation='softmax')(x) #final layer with softmax activation
vgg=Model(inputs=base_model.input,outputs=preds)

A: It seems like you're using a softmax activation function on your output. Softmax is typically used when you are classifying an input with multiple possible classes, as it outputs a probability distribution (i.e. all elements sum to 1). It does so by first exponentiating each element, and then dividing each by the sum of all elements.
However, if you only have one output unit, it will then have to always output 1, as it will be calculating exp(x_1) / exp(x_1) = 1
For a binary classification task as you're doing, I would recommend using a sigmoid output activation function instead:
base_model=VGG16(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(1,activation='sigmoid')(x) #final layer with softmax activation
vgg=Model(inputs=base_model.input,outputs=preds)

This assumes that the labels in your training dataset are 0 and 1.


text:
Q: Multiple Tag Filtering I am writing a theme for Wordpress and I need a tag filter tool for posts, that can filter by multiple tags simultaneously, without a submit button, no checkboxes, no radio's, and a show all posts button. (See image)
What would be the best way to come at this problem? or can anyone recommend any suitable plugins?

A: I recently wrote a bit of code which filters by one tag at a time only, but it would be pretty easy to modify it to 'toggle' the status of each tag so that you could filter by multiple tags simultaneously. You can see it working here: http://sadcookbook.recipes/sad/ . It uses the following PHP to render the tag links,
Show only:
<?php
$tags = get_tags();
foreach ($tags as $tag) {
        $taglinks[] = "slug."\">".$tag->name."";
}
echo join($taglinks, " - ");`

Then it uses this jquery together with masonry to display posts depending on which tags have been clicked
jQuery('.filter-tag').click(function() {

    showAll();
    var $grid = jQuery('#grid-container');
    tag = 'tag-' + jQuery(this).attr('id').substring(7)
    classSelector = '.' + tag
    elementsToRemove = jQuery('#gridcontainer').children().children().not(classSelector).parent()

    elementsToRemove.clone().appendTo('#grid-hidden')
    $grid.masonry('remove', elementsToRemove)
    $grid.masonry('layout')

    // Save the elements removed so they can be put back later
    elementsToRemove.each(function (index) {
            id = jQuery(this).attr('id');
            if (!putBack.includes(id))
                    putBack.push(id)
    });

});


text:
Q: Xtermjs 4.0.0, not working in my react in app I am working on an react terminal app using xtermjs 3.14 before, and it's working ok. But when I want to update it to xtermjs 4.1.0 and add new addons, it's broken and reply different types errors. I follow the steps from the release notes.
import {Terminal} from 'xterm';
import {FitAddon} from 'xterm-addon-fit';

var term = new Terminal({cursorBlink: true});
var fitAddon = new FitAddon();
term.loadAddon(fitAddon)

class TerminalPage extends Component {
   componentDidMount(){
      term.open(document.getElementById('terminal'));
   }
}

terminalapp startup failed TypeError: R.on is not a function
or
x is not defined


text:
Q: application crached on uploading file more than 300M I have problem my app crashed when I select 400M file to upload , less than 300M is uploading fine
I changed this
int maxBufferSize =  10 * 10241 * 1024;

to
int maxBufferSize =   10241 * 1024;

still same problem
Did i miss somthing?
protected String doInBackground(String... urls) {

    String upLoadServerUri = upApi.uploadUrl;
    String fileName = this.file_path;
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize =  10 * 10241 * 1024;
    File sourceFile = new File(fileName);
    int sentBytes = 0;
    long fileSize = sourceFile.length();

    try
    {
        FileInputStream fileInputStream = new FileInputStream(new File(fileName));

        URL url = new URL(upLoadServerUri);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setChunkedStreamingMode(1024);
        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type",     "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream(     connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"file[]\";filename=\""+ fileName + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        buffer = new byte[maxBufferSize];

        while (true)
        {
            int bytesToRead = Math.min(maxBufferSize, fileInputStream.available());

            // Break if complete
            if(bytesToRead == 0){ break; }

            // Read bytes
            bytesRead = fileInputStream.read(buffer, 0, bytesToRead);

            // Write bytes
            outputStream.write(buffer, 0, bytesRead);

            // Update progress dialog
            sentBytes += bytesRead;

            // Publish progress
            double progress = (double)sentBytes / fileSize;
            publishProgress((int)progress);
        }

04-04 23:11:24.664: E/OMX-VDEC-1080P(217): ION: alloc_data: handle(0xE4904BC0), len(368640), align(8192), flags(0x2000100), fd_data: handle(0xe4904bc0), fd(0x46)
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): Allocate done for all i/p buffers
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): Allocate done for all o/p buffers
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): OMX_CommandStateSet complete, m_state = 2
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): send_command: Recieved a Command from Client
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): send_command_proxy(): cmd = 0, Current State 2, Expected State 3
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): send_command_proxy(): OMX_CommandStateSet issued
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): Current State 2, Expected State 3
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): send_command_proxy(): Idle-->Executing
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): send_command: Command Processed
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): Rxd OMX_COMPONENT_GENERATE_START_DONE
04-04 23:11:24.664: E/OMX-VDEC-1080P(217): Rxd i/p EOS, Notify Driver that EOS has been reached
04-04 23:11:24.694: E/OMX-VDEC-1080P(217): Output EOS has been reached
04-04 23:11:24.694: E/OMX-VDEC-1080P(217): Rxd OMX_COMPONENT_GENERATE_EOS_DONE
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command: Recieved a Command from Client
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): cmd = 0, Current State 3, Expected State 2
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): OMX_CommandStateSet issued
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Current State 3, Expected State 2
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Command Recieved in OMX_StateExecuting
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): Executing --> Idle
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Driver flush i/p Port complete
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Initiate Input Flush
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Reset all the variables before flusing
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Initialize parser
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): OMX flush i/p Port complete PenBuf(0)
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Driver flush o/p Port complete
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Initiate Output Flush
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): OMX flush o/p Port complete PenBuf(0)
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Rxd OMX_COMPONENT_GENERATE_STOP_DONE
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command: Command Processed
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command: Recieved a Command from Client
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): cmd = 0, Current State 2, Expected State 1
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): OMX_CommandStateSet issued
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): Current State 2, Expected State 1
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command_proxy(): Idle-->Loaded-Pending
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): send_command: Command Processed
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): ION: free: handle(0xEB8C3D00), len(2097152), fd(0x41)
04-04 23:11:24.704: E/OMXNodeInstance(217): OMX_FreeBuffer for buffer header 0x43f34670 successful
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): ION: free: handle(0xDCAB0D00), len(2097152), fd(0x3f)
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): ALL input buffers are freed/released
04-04 23:11:24.704: E/OMXNodeInstance(217): OMX_FreeBuffer for buffer header 0x43f34620 successful
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): ION: free: handle(0xE4904BC0), len(368640), fd(0x46)
04-04 23:11:24.704: E/OMX-VDEC-1080P(217): ION: free: handle(0xD31AE040), len(73728), fd(0x44)
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): ALL output buffers are freed/released
04-04 23:11:24.784: E/OMXNodeInstance(217): OMX_FreeBuffer for buffer header 0x43f348f8 successful
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): OMX_CommandStateSet complete, m_state = 1
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): Playback Ended - PASSED
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): ALL output buffers are freed/released
04-04 23:11:24.784: E/OMX-VDEC-1080P(217):  Error in ioctl read next msg
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): omx_vdec: Async thread stop
04-04 23:11:24.784: E/OMX-VDEC-1080P(217): Close the driver instance
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): omx_vdec::component_deinit() complete
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): In OMX vdec Destructor
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): omx_vdec: message thread stop
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): Waiting on OMX Msg Thread exit
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): Waiting on OMX Async Thread exit
04-04 23:11:24.804: E/OMX-VDEC-1080P(217): Exit OMX vdec Destructor

A: You're trying to allocate too large a buffer (10 * 10241 * 1024 = 104867840 bytes). Even 10241 * 1024 is too large (10486784 bytes). Try reducing it to 1024 * 1024 (1048576) or smaller; it's doubtful you'll be able to transfer it fast enough over your network connection to need a buffer that large anyway.


text:
Q: C pointers, inserting elements to HEAD of linked list I am working on a problem in the K&R book (#6.3) where the user inputs a sequence of words, and you have to create a list of these words along with the lines that each one appears on. It's supposed to involve structures so these are the ones I have right now:
struct entry {
    int line;
    int count;
    struct entry *next;
};

struct word {
    char *str;
    struct entry *lines;
    struct word *next;
};

static struct word *wordlist = NULL;    // GLOBAL WORDLIST

However when I input something and the program tries to add a new entry to the structure (which is somewhat like a linked list), there is a problem and the program terminates with no error message. Code for that:
void add_entry(char *word, int line)
{
    if (word == NULL || line <= 0 || is_blocked_word(word))
        return;

    struct word *w;
    for (w = wordlist; w != NULL && w->next != NULL && !strcmp(w->str, word); w = w->next);

    // If word is found in the wordlist, then update the entry
    if (w != NULL) {
        struct entry *v;
        for (v = w->lines; v != NULL && v->next != NULL && v->line != line; v = v->next);

        if (v == NULL) {
            struct entry *new = (struct entry*) malloc(sizeof(struct entry));
            new->line = line;
            new->count = 1;
            new->next = NULL;

            if (w->lines == NULL)
                w->lines = new;
            else
                v->next = new;
        }
        else v->count++;
    }

    // If word is not found in the word list, then create a new entry for it
    else {
        struct word *new = (struct word*) malloc(sizeof(struct word));
        new->lines = (struct entry*) malloc(sizeof(struct entry));
        new->next = NULL;
        new->str = (char*) malloc(sizeof(char) * strlen(word));
        new->lines->line = line;
        new->lines->count = 1;
        new->lines->next = NULL;
        strcpy(new->str, word);

        // If the word list is empty, then populate head first before populating the "next" entry
        if (wordlist == NULL)
            wordlist = new;
        else
            w->next = new;
    }
}

The program terminates even after adding just the first word to wordlist. This is on the line that says if (wordlist == NULL) wordlist = new; where new contains the pointer to a valid structure that I malloc'ed. How can this be possible?
As far as I know it's a problem with my pointer usage but I'm not sure where exactly it lies. Can someone help?

A: Some fairly evident, and some not-so-evident things.
The for-loop limit for w stops one short
for (w = wordlist; w != NULL && w->next != NULL && !strcmp(w->str, word); w = w->next);

This will start with the first and continue until

*

*We have run out of nodes

*We have almost (one short) run out of nodes.

*The word in the current node does NOT match

Almost the same problem, different for-loop
for (v = w->lines; v != NULL && v->next != NULL && v->line != line; v = v->next);

As above, this has similar attributes (but not the third option, as this correctly continues so long as the line numbers do not match. The prior loop broke as soon as any word did not match.
And that is in the first ten lines of this function.
String allocation size fails to account for the nulchar terminator
This falls short by one char of the allocation size needed for a zero-terminated string:
malloc(sizeof(char) * strlen(word))

You always need space for the terminator. The easiest way to remember that is to consider how many chars are needed for a zero-length C string? Answer: one, because the terminator needs to go somewhere. After that is simply length+1

One possible way to do this is via a pointer-to-pointer approach, shown below:
void add_entry(const char *word, int line)
{
    if (word == NULL || line <= 0 || is_blocked_word(word))
        return;

    struct word **pp = &wordlist;
    for (; *pp && strcmp((*pp)->str, word); pp = &(*pp)->next);
    if (*pp)
    {
        // search for matching line number
        struct entry **vv = &(*pp)->lines;
        for (; *vv && (*vv)->line != line; vv = &(*vv)->next);
        if (!*vv)
        {
            *vv = malloc(sizeof(**vv));
            if (!*vv)
            {
                perror("Failed to allocate line entry.");
                exit(EXIT_FAILURE);
            }
            (*vv)->count = 1;
            (*vv)->line = line;
            (*vv)->next = NULL;
        }
        else
        {   // found an entry. increment count.
            (*vv)->count++;
        }
    }
    else
    {   // no matching word. create a new word with a new line entry
        size_t len = strlen(word);
        *pp = malloc(sizeof(**pp));
        if (!*pp)
        {
            perror("Failed to allocate word entry.");
            exit(EXIT_FAILURE);
        }

        (*pp)->lines = malloc(sizeof(*(*pp)->lines));
        if (!(*pp)->lines)
        {
            perror("Failed to allocate line count entry.");
            exit(EXIT_FAILURE);
        }

        (*pp)->str = malloc(len + 1);
        if (!(*pp)->str)
        {
            perror("Failed to allocate word string entry.");
            exit(EXIT_FAILURE);
        }

        (*pp)->lines->count = 1;
        (*pp)->lines->line = line;
        (*pp)->lines->next = NULL;
        (*pp)->next = NULL;
        memcpy((*pp)->str, word, len+1);
    }
}

How It Works
In both cases, we use a pointer-to-pointer. They are a most-hand construct when the desire is to perform tail-end insertion on a linked list without having to keep a "one-back" or "previous" pointer. Just like any pointer, they hold an address. Unlike a regular pointer-to-something, a pointer-to-pointer-to-something holds the address of another pointer. With it we can "loop" by initially setting it to the address of the head pointer, the entering the search.
struct word **pp = &wordlist;
for (; *pp && strcmp((*pp)->str, word); pp = &(*pp)->next);

Here we start with the address of our head pointer. the loop will terminate if the pointer at the address held in pp is NULL, or if the word actually matches. Otherwise it sets the address of (not the address in) the next pointer of the current node.If we run out of words and never find a match the loop will break, but with a most-handy consequence: pp contains the address of the pointer that we need to set to the new allocation. If the list were initially empty, it contains the address of the head pointer.
With that, we can then do this:
if (*pp)
{
    // search for matching line number
    struct entry **vv = &(*pp)->lines;
    for (; *vv && (*vv)->line != line; vv = &(*vv)->next);

Notice we use the same idea on the line-entry list. Either we're going to find an entry, or the loop will exit with *vv being NULL, and vv contains the address of the next pointer we want to set to our new allocation.
I strongly urge you to step through this code in a debugger line-by-line, and understand how it works. utilizing this technique has many redeeming qualities, among them the incredibly brief method of populating a forward-linked list in O(n) complexity without having to check for a head pointer or walking the list for each insertion and retaining the original order (as opposed to reversing the order as a stack-like solution would result):
struct node *head = NULL;

struct node **pp = &head;
while (get-data-for-our-list)
{
    *pp = malloc(sizeof(**pp));
    // TODO: populate (*pp)->members here
    pp = &(*pp)->next;
}
*pp = NULL;


text:
Q: Appropriate usage of "Take" and "Give" What is the correct verb to be used in the following places?

1) Teacher Mary A s tuition. Therefore she would take the fees.
2) A student B s tuition.
3) An Exam is "taken" by a student, not "given", but a teacher C s the exam.

In all the places (A,B,C) what should the verb be with respect to the context? "Take" or "Give"?
Also I want to know is there any other such word where "take" and "give" is very hard to guess?

A: I wouldn't use take when talking about a tuition payment. Instead, I would use collect:

The bursar collected Mary's tuition.

I wouldn't use give, either, I would use pay:

Mary paid her tuition at the bursar's office.

Although it's worth noting that give and take can indeed be used with regards to money:

Paula gave $3000 to various charities last year.
Sam took $50 out of his checking account before he went to the movies.

For exams, though, give and take are often used:

The professor gave her exam on Monday. Joe was absent, though, so he will take the exam on Friday.

but this is just one meaning of the word take, out of several dozen. OneLook lists, among its many definition's of the word take, this one:

to do an examination in a particular subject

When dealing with flexible words like give and take, it's best to study all the definitions of the word, which is a task that might require you to look in more than one dictionary to complete. OneLook and Wordnik are two great places to start, because they provide links to, or take definitions from, more than one online dictionary.


text:
Q: What are apple's app store guidelines for the big icon (512x512) I want to distribute an iPhone app to the store and cannot find any guidelines for the iTunesArtwork icon. I heard it has to be jpg, but

*

*can it also be .png?

*do they add the rounded corners?

*do they add shine?

*...

A: The information is all in the iTunes Connect part of the Apple website.  Look for the "Download the Developer Guide" PDF in:
https://itunesconnect.apple.com
You can put the same image into your Ad Hoc distribution (in the .ipa bundle) if you want it to appear in iTunes when doing Ad Hoc testing.
Update: removed old broken link, see comments for the new link.

A: They say the image has to be JPG or TIF, but they sometimes accept PNGs. You can try submitting it with a PNG, but I'm not sure it's worth the risk given how much time it takes for them to review submissions. If they do reject it for that reason alone, you'll just have to resubmit and keep waiting.
They'll add the rounded corners and highlights for you, though.

A: PNG's work but make sure they are at least 24 bit as this caused me a lot of trouble.  Apple accepted the 8 bit file but it looked horrible scaled down.


text:
Q: Kalman filter and state space model As a beginner to modelling systems, it is a little unclear to me.
A state space model can be described as:
x' = Ax+Bu
In a kalman filter, the state will be described as:
x = Fx+Bu
Is A and F the same ?
I am trying to implement a kalman filter in python on a zero-order system for simplicity.
The best result I get is when F is [1] - does this make sense ?
Assuming I calculated my state space model parameters correctly, F should be bigger than 1.
Can anyone try to explain the theory ?


text:
Q: Cython - dictionary keys and values static type definition I want to use Cython to compile a Python module that works with a dictionary of which all keys are of type, say, integer (or no matter what other static and known type), and all values of type unicode (or other static and known).
Now, to speed it up, I can declare
cdef dict Dict

and also
cdef int k
cdef unicode v

But, can I make a static declaration of the whole "dict int->unicode" structure?
Thanks,

A: I think the short answer is no. Cython is still using the built-in Python dictionary. It can take advantage of some optimisations if you declare the object as dict, but ultimately the dict has to be able to store objects of different types, and so you cannot specify the key or value types at compile-time. But you should check first to make sure that this is a bottleneck. Python dictionaries are fairly good.


text:
Q: How can I write a database like query in excel using just functions? I have some data that's structured in a table like this:
.
I have another tab on my spreadsheet where I eliminate any duplicate category entries and want to concatenate the data to look like this:

I need to create this using a function and not a macro or Visual Basic.  I've already written the function to eliminate any of the duplicate category entries and now I need to figure out how to take each of those unique categories and append the data behind it.  Any ideas?

A: Assuming the first image comes from Sheet1 and the second Sheet2, here's a way to do it. You need to add at least one calculated column to Sheet1 and optionally two calculated rows to Sheet2.

*

*Uniquely identify each row on Sheet1. Add a new column A with the formula =B3&COUNTIF($B$3:B3,B3) in A3 and fill down. You'll have first1 in A3, first2 in A4 and so on.

*Identify each block of columns on Sheet2. Add a new row 6 with the formula =COUNTIF($B$2:B2,B2) in B6 and fill across. The values will be 1,1,1,2,2,2,3,3,3. You can type these in manually if you like but it won't scale as easily.

*Work out the column of each data item in Sheet1 and put in the columns for Sheet2. Add a new row 7 to Sheet2 with the formula =MATCH(B2,Sheet1!$A$2:$E$2,0) and fill across. The values will be 3,4,5,3,4,5,3,4,5. We now know, for each cell in Sheet2, which instance of the category we have and in which column the data variable comes from.

*Use VLOOKUP to find first1 and return data column 3 within the data table. On Sheet2, set cell B3 to =VLOOKUP($A3&B$6,Sheet1!$A$2:$E$8,B$7,FALSE) and fill down and across.

*You'll have a number of #N/A errors (e.g. cell E4). If you have a newer version of Excel, you can use IFERROR() to escape this; otherwise, use =IF(ISNULL(<formula>), "", <formula>) where <formula> is the formula in step 4.

To summarise:

*

*Create a unique, sequential, calculable row ID for each row in the source.

*Determine which instance of that sequence is used by each column in the destination. This is appended to the end of the category to determine the row IDs formed in the previous step.

*Determine which column contains the data for each column in the destination.

*Look up the row with the calculated row ID and find the relevant column for this data item.

*Format the results appropriately.


text:
Q: Add shipping on subtotal after discount I want to add freeshipping on subtotal but after discount i already have tried with
if ($request->getFreeShipping()
|| $request->getPackageValueWithDiscount() >= $this->getConfigData('free_shipping_subtotal')) {
    ...
}

But this only takes subtotal not and discount did anyone know how can I get subtotal after discount.
Thanks

A: As long as your collectTotals order is to calculate discount first then using $request->getPackageValueWithDiscount() will be the discounted total.
See Mage_Sales_Model_Quote_Address:
 $packageValueWithDiscount = $item
        ? $item->getBaseRowTotal() - $item->getBaseDiscountAmount()
        : $this->getBaseSubtotalWithDiscount();
    $request->setPackageValueWithDiscount($packageValueWithDiscount);


text:
Q: Better alternatives For Loop R I am storing a value in column c based on this criteria. There are 4million rows in my dataframe and this takes 2 days to finish.
for ( i in 1:NROW(df)) {
  df$c[i+1] <- df$a[i] + df$b[i] - df$a[i+1]
  print(i)
}

Are there any alternatives to this for loop that can accomplish what I am doing much faster. Thanks in advance.

A: First off, it's always best to provide some sample data and matching expected output to illustrate what you like to achieve. That will make it a lot easier for the SO community to help.
That aside, you could use dplyr::lag
library(dplyr)
df <- mutate(df, c = lag(a) + lag(b) - a)

Here is an example based on sample data I created
# Sample data
df <- data.frame(
    a = 1:10,
    b = 11:20)

df <- mutate(df, c = lag(a) + lag(b) - a)
df
#    a  b  c
#1   1 11 NA
#2   2 12 10
#3   3 13 11
#4   4 14 12
#5   5 15 13
#6   6 16 14
#7   7 17 15
#8   8 18 16
#9   9 19 17
#10 10 20 18

You can confirm that indeed c[i+1] = a[i] + b[i] - a[i+1].

Benchmark analysis
Let's compare the following three methods in terms of performance/runtime

*

*using dplyr::lag and dplyr::mutate

*using base R (thanks @nicola),

*using data.table::shift
We use sample data consisting of 10^6 entries for a and b.
set.seed(2017)
df <- data.frame(
    a = sample(100, 10^6, replace = T),
    b = sample(100, 10^6, replace = T))

library(microbenchark)
res <- microbenchmark(
    method_lag = {
        df <- mutate(df, c = lag(a) + lag(b) - a)
    },
    method_base = {
        df$c <- NA
        df$c[-1] <- df$a[-nrow(df)] + df$b[-nrow(df)] - df$a[-1]
    },
    method_shift = {
        df$c <- shift(df$a) + shift(df$b) - df$a
    })
#Unit: milliseconds
#         expr      min       lq     mean   median        uq       max neval cld
#   method_lag 19.88495 21.81414 29.30085 23.83718  26.61746 107.04355   100  b
#  method_base 51.00888 56.29822 90.05291 60.65321 128.79227 208.80537   100   c
# method_shift 10.86351 12.51993 18.34094 14.24705  16.88488  92.83246   100 a

autoplot(res)

A: loops in high level programing languages are always an issue for large operations. in addition to Maurits answer if you are familiar with C++ you can use rcpp package to compile c++ codes for R which are much more faster.
In addition print (as a progress shower) in C++ is much more optimum than pure R printing. See Example
You can Also cast R (Numeric Vector and Matrix)  to C++11 std <std> vectors and use parallel processing (if your hardware support it) for much better usage of hardware.


text:
Q: How to auto Enable/Dissable Developer Options Stay awake setting as I connect/disconnect ADB? So I'm getting quite annoyed at always having to go into settings -> Developer options and enable the 'Stay awake' setting while I'm deving and then having to remember to go in and disable when I'm done... I'd love this to happen automatically, I have searched the play store for any apps that will do this and I have found one or two that claim to do achieve this through using a wake-lock but none of them have actually worked for me.
Any suggestions?

A: So after coming up empty, I decided, I am a developer so I should just make it myself, and that is what I did.
The code is available open-source here: ABD-Stay_Awake


text:
Q: Adding an annotation to mkmap, but want to remove part of the annotation but it won't remove I create an annotation, which contains several elements textbubble and pin. I turn the bubble on when I show annotation, but later I want to shut the bubble off and leave the annotation.
Here are my two methods.  The add subview works, but remove subview does not.
-(void)hideETACountdown {
self.etaView.hidden = YES;
[self.etaView removeFromSuperview];
}

-(void)showETACountdown {

self.etaView = [[UIView alloc] initWithFrame:CGRectMake(-34, -97, 89, 59)];
UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"WaitBubble_backgroundandshadow.png"]];
[self.etaView addSubview:bg];
UILabel *minLabel = [[UILabel alloc] initWithFrame:CGRectMake(7, 24, 42, 21)];
minLabel.text = @"min";
minLabel.textAlignment = UITextAlignmentCenter;
minLabel.font = [UIFont systemFontOfSize:10];

self.etaLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 4, 30, 27)];
self.etaLabel.font = [UIFont boldSystemFontOfSize:22];
self.etaLabel.textAlignment = UITextAlignmentCenter;
self.etaLabel.text = @"";

[self.etaView addSubview:minLabel];
[self.etaView addSubview:self.etaLabel];

[self addSubview:self.etaView];

self.etaView.hidden = NO;
}

- (id) initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]) {

    self.canShowCallout = YES;
    self.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    self.innerImage = [[UIImageView alloc] initWithImage:nil];
    self.innerImage.frame = CGRectMake(-15, -38, 32, 39);

    [self addSubview:self.innerImage];

    if(self.showETA) {

        [NSNotificationCenter addUniqueObserver:self
                                       selector:@selector(handleEtaTimeUpdate:)
                                           name:kEtaUpdate
                                         object:nil];
        [self showETACountdown];

    }

}
return self;
}

// UPDATE /////
There seems to be some confusion. This code above is not in the viewController that holds my mkmap, but rather the code inside my custom annotation. Further, I don't want to hide or show the entire annotation based on selecting or deselecting. The self.etaView is custom view which is just part of the annotation. My annotation consists of a custom map pin and an eta bubble. Once the ETA is counted down to 0, I want to remove the bubble (aka self.etaView), but the annotation (map pin) needs to stay on the map the entire time. I just want to hide the ETA bubble.
I am using the proper addAnnotation methods, in the proper way, in my viewController that holds my mkmap. Again, this code above is inside my custom annotation and I want my custom annotation to be responsible for removing its own elements, NOT removing itself from the map.

A: Come on, why using this weird logics with addSubView and removeFromSuperView. MKMapView is built to support "datasource" for pins. I dunno what kind of view you are trying to acheive but this CGRectMake(-34, -97, 89, 59) looks awful.  So please, use method:
-(MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id<MKAnnotation>)annotation

This way you will have no difficulties managing the annotation using method
- (void)deselectAnnotation:(id < MKAnnotation >)annotation animated:(BOOL)animated

For example:
[mapView deselectAnnotation:[mapView.selectedAnnotations objectAtIndex:0] animated:YES];

A: The method to remove the bubble was getting called, but it just wasn't getting removed?  So what I have done is create notification listener on my annotation and post a notification when I want it removed and it removes it.  Not sure why it doesn't just work by calling an instance method?
Anyway, notifications solved it. Need to move on so I can launch the app.


text:
Q: Isn't POP3 Download and Keep similar to IMAP I recently read about POP3 and IMAP.. There I read that POP3 can either download and delete or download and keep . However, isn't download and keep somewhat similar to IMAP where you are keeping a copy of your messages in the mail server in place of a remote server on IMAP ?
Thanks in advance.

A: No.  With IMAP, changes that you make using any of your mail clients are synced by the server.  For example, if you mark a message as read using one of your mail clients, this change is synced by the server, so that all of your other mail clients show that the message is read.  This is not the case with POP3.


text:
Q: How to create .ko files in Linux I have written one driver for one device in Linux. How can I create (using gcc) a .ko file so that I can insert it into the kernel?

A: Short answer: you can't.
A .ko file is more than just a compiled version of your driver source.
The kernel build system includes some extra information for instance (compiler version, module dependencies, ...).
You can probably dig through the kernel build system to find all required operations, but you shouldn't. It will almost certainly break with the next kernel release, or the one after that. You should use the makefile ephemient supplied.

A: Create a Makefile like this.
ifneq ($(KERNELRELEASE),)
obj-m   := mymodule.o
else
KDIR    := /lib/modules/$(shell uname -r)/build
PWD     := $(shell pwd)
all:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
install:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules_install
%:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) $@
endif

Assuming your module's source is in mymodule.c, running make will create mymodule.ko.


text:
Q: Is there any explanation provided by the franchise behind the name Death Star? I mean this always bugged me. You have a thing that destroys stars, but is clearly not a Star itself. It's way too small to be considered a star and its also not bright, so why call it that. The "death moon" or something like that would at least have some kind of relation (even if it doesn't sound as cool though). And why are star destroyers called star destroyers? They don't do any star destroying business? Has this ever been explained why these things are named the way they are (extended counts too)?
Note: Also, why would you name your giant spacestation deathstar, if you actually want supporters of your empire and not be seen as evil to the outside. I mean that highly increases the chance of a rebelion doesnt it?

A: Consider that the word star is indeed used in British English and American English for anything that you can, let's say, "see in the sky" (even if it has literally nothing to do with A Sun).
Great examples are words like "Telstar" and "OnStar" ...
So, it's commonplace to have sentences such as "What's that star - actually that's the space shuttle" or indeed just "that star there is Jupiter". Indeed, consider, before modern times every "point of light" in the sky was a star - whether actually a galaxy, planet, "shooting star", actually a Sun, or anything else.
(The term "shooting star" particularly gives the feel of the more archaic, poetic, meaning of "star".)
I appreciate that the death star is a large object (more like a moon) when seen from relatively close - but then, a Sun, or indeed a GPS satellite, is "large" when seen from a certain point. You can easily imagine the Death Star being a twinkling point from another planet in it's construction system - So, picture this, we're on Earth and it's a slowly-growing "new moon of Jupiter" - quite ominous; a death star indeed.
Consider too that simply, in the very title "Star Wars" the word "Star" doesn't literally mean the hot burning balls of gas - if you think it through, it more means "planetary systems": it's literally the planets (the dwellers thereon) warring, it's not literally the Suns or anyone living on the surface of the Suns, warring!
"Planet Wars" or perhaps "planetary-system wars!" would "make more sense" but doesn't sound as good!
Thus, an excellent answer to your question is this:
Canonically, "star" in "Death Star" is being used in exactly same poetic, somewhat archaic way, as: in the very title of the series.
And that's pretty canon, right?!  :)

A: Wookieepedia states the Death Star had an optimum range of 2,000,000 kilometers. To put that in perspective the distance of the moon from the Earth is 384,400 km.
Now consider that the first Death Star was stated to be 87 mi (140 km) in diameter with a volume of 220,781 cubic miles, or (to give perspective) approx. 1/25 the size of our Moon.
Given the size and optimum distance from target and with the light catching it just right, it would look very much like a large-ish, bright star in the night sky (possibly the day time as well).
A star that brings death. Hence the name.

A: Mention was made in the Legends material (formerly the EU) that the Death Star's official designation was "DS-1" or "DS-1 Platform". It's unclear whether the designation or the name came first - if the designation came first, it may have given the idea for the more poetic name.
Also in Legends, there is mention that the cover story for the construction of the Death Star was that it was a planetary ore-extractor, designed to blow apart uninhabited worlds to more easily extract minerals from their core. Obviously that's untrue, but it would suggest that the DS-1 designation came first - it wasn't built under the name "Death Star".
As for why it's called "Death Star" when it's not a star - the name works in a number of ways. First, there's the fact that "star" is often used symbolically to refer to space in this series - see Star Destroyers, Star Dreadnoughts, Star Cruisers, Starfighters. Second, there's the idea that the DS-1 is a 'star' of death, in the metaphorical sense of "being really good at it". Third, if it's in high orbit it would likely be seen as just another star in the sky, as any point of light is.
Hopefully, the upcoming Rogue One will give us some more information and back story about the name.


text:
Q: How can I override a Nix derivative without throwing `cannot coerce a set to a string`? Or, the goal: How can I take a single package from Nix unstable in a declarative manner?
I'm new to NixOS and currently trying to install a newer version of Consul than the default 0.5.2 of my NixOS version (latest stable). I'm attempting this by overriding the derivative in my /etc/nix/configuration.nix.
I'd like to keep running stable, but I found unstable had the version of Consul that I wanted (0.7.0) already, and so I decided to use this package's attributes as a starting point to override https://github.com/NixOS/nixpkgs/blob/master/pkgs/servers/consul/default.nix
I copied it for most part into my configuration.nix, here are the relevant sections:
nixpkgs.config.packageOverrides = pkgs: rec {
  consul = pkgs.lib.overrideDerivation pkgs.consul (attrs: rec {
    version = "0.7.0";
    name = "consul-${version}";
    rev = "v${version}";

    goPackagePath = "github.com/hashicorp/consul";

    src = pkgs.fetchFromGitHub {
      owner = "hashicorp";
      repo = "consul";
      inherit rev;
      sha256 = "04h5y5vixjh9np9lsrk02ypbqwcq855h7l1jlnl1vmfq3sfqjds7";
    };

    # Keep consul.ui for backward compatability
    passthru.ui = pkgs.consul-ui;
  });
};

environment.systemPackages = with pkgs; [
  vim
  which
  telnet
  consul-ui
  consul-alerts
  consul-template
  consul
];

I'm running nix-build (Nix) 1.11.2 which throws:
$ nixos-rebuild switch
building Nix...
building the system configuration...
error: cannot coerce a set to a string, at /etc/nixos/configuration.nix:19:7
(use '--show-trace' to show detailed location information)

When I look at line 19 it's where name is set to "consul-${version}".
Why there is type-coercion going on here? Any tips will be greatly appreciated!
I'm also wondering if there is a better way to run just a single package in unstable, yet doing so declaratively from configuration.nix, rather than imperatively?

A: To add to what Rok said:

Which should point you that an error actually happens at passthru, line. If you comment it out it will probably build. I'm assuming some recursive calls are at play here and error occurs when it tries to evaluate consul/consul-ui packages.

If you're just starting out, you can safely ignore what follows and perhaps come back to it if/when you're curious about the nitty-gritty.
The problem here is that overrideDerivation is a kind of low-level approach to overriding things. Behind stdenv.mkDerivation, we have a much smaller primitive function called derivation. The derivation function takes some attributes and (more or less -- see the docs for the finer details) just passes those attributes as environment variables during the build. The stdenv.mkDerivation function, on the other hand, has a whole bunch of smarts layered on top that massages the attributes given to it before passing them onto derivation -- and in some cases, as is the case with passthru, it doesn't pass the attribute to derivation at all.
Back to overrideDerivation: it takes the final, tweaked attributes that stdenv.mkDerivation would pass to derivation, and just before that happens it allows you to override those attributes with the function you give it (e.g. that implies that, at that point, passthru has already been removed). When your function adds a passthru, that makes its way into derivation, which then wants to coerce the value of passthru into a string so it can make passthru an environment variable during the build; however, because passthru now points at a attribute-set, and such coercion isn't supported, Nix then complains.
So this sort of puts us in an odd situation. To illustrate, I'll copy the source for the consul package here:
{ stdenv, lib, buildGoPackage, consul-ui, fetchFromGitHub }:

buildGoPackage rec {
  name = "consul-${version}";
  version = "0.6.4";
  rev = "v${version}";

  goPackagePath = "github.com/hashicorp/consul";

  src = fetchFromGitHub {
    owner = "hashicorp";
    repo = "consul";
    inherit rev;
    sha256 = "0p6m2rl0d30w418n4fzc4vymqs3vzfa468czmy4znkjmxdl5vp5a";
  };

  # Keep consul.ui for backward compatability
  passthru.ui = consul-ui;
}

(Note that buildGoPackage is a wrapper around stdenv.mkDerivation.)
You might be familiar with e.g. consul.override, which allows you to supply different inputs (e.g. maybe a different version of consul-ui, or buildGoPackage), but it doesn't allow you to override things that aren't inputs (e.g. src, passthru, etc). Meanwhile, overrideDerivation allows you to modify the attrs given to derivation, but not the ones given to stdenv.mkDerivation. Ideally there would be something in-between, that would allow for manipulating the attrs given to stdenv.mkDerivation, and it so happens that there's a PR open to address this:
https://github.com/NixOS/nixpkgs/pull/18660

A: Welcome to Nix/NixOS :)
Whenever you need to know more about the error you can use --show-trace and that would give you more verbose error. In your case you would see something like
error: while evaluating the attribute 'passthru' of the derivation 'consul-0.7.0' at /home/rok/tmp/consul.nix:6:3:
cannot coerce a set to a string, at /home/rok/tmp/consul.nix:6:3

Which should point you that an error actually happens at passthru, line. If you comment it out it will probably build. I'm assuming some recursive calls are at play here and error occurs when it tries to evaluate consul/consul-ui packages.
As for overriding only one package from unstable channel something like this is needed
let
  unstable_pkgs = import ./path/to/unstabe/nixpkgs {};
  # or
  # unstable_pkgs = import (pkgs.fetchFromGitHub {...}) {};
in {
  ...
  nixpkgs.config.packageOverrides = pkgs: rec {
    consul = unstable_pkgs.consul;
  };
  ...
}

I haven't try the above, but I'm assuming it will work.


text:
Q: Stop IE from caching iframe opened via jquery modal dialog UPDATED: Found answer.  Cannot submit my own answer for 7 more hours...  See comments.
I'm opening a dialog as follows:
url = 'edit/MyPage.aspx?appid=3&value=4&' + date.getTime();
$('#modalIFrame').attr('src', url);
$('#modalDiv').dialog('open');

The iframe has a form with a few fields (checkboxes, dropdowns, textareas).  In Chrome, everything is working flawelessly.  In IE it caches very persistently and annoyingly.  Even shift+refresh doesn't help.  So if I open the dialog, make changes, hit submit, then refresh the page all the data looks right.  However, when I click the edit button to open the dialog, it's the previous data (The data is pulled using an ajax call to a WCF service)  I've even waited a couple hours for my session to expire, no luck.
As you can see above, I tried a trick I found here to trick IE into thinking it's a new page.  This doesn't work.  I also added the following code to the Page_Load of the page in the iframe:
Response.Cache.SetCacheability(HttpCacheability.NoCache)

and the following meta tags to the HTML:
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="0">

I'm completely lost here, any ideas would be appreciated.

A: Okay I discovered it was the WCF service that was being cached in IE (doesn't make sense to me, but whatever).  I added a timestamp to the ajax call and now it works!
data: { "appid": appid, "serverid": serverid, "timestamp": date.getTime() },


text:
Q: Why is Redux throwing a null error when I try to log out a user with Firebase? To give a quick rundown of my app, it's an app where you can take tests, score yourself, and record your scores. It uses Firebase Auth and Firestore and Redux to help do all this. I'm having a problem when it comes to signing out of the user's account.
redux/actions/index.js:
import { USER_STATE_CHANGE, CLEAR_DATA, USER_TESTS_COMPLETED_STATE_CHANGE } from '../constants/index'
import firebase from 'firebase'

export function clearData() {
    return ((dispatch) => {
        dispatch({type: CLEAR_DATA})
    })
}

export function fetchUser(){
    return((dispatch) => {
        firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).get().then((snapshot) => {
            if(snapshot.exists){
                dispatch({type : USER_STATE_CHANGE, currentUser: snapshot.data()})
            } else {
                console.log("user data does not exist");
            }
        })
    })
}

export function fetchUserCompletedTests(){
    return((dispatch) => {
        firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).collection("scores").orderBy("testScore", "desc").get().then((snapshot) => {
            let completedTests = snapshot.docs.map(doc => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data }
            })
            dispatch({ type: USER_TESTS_COMPLETED_STATE_CHANGE, completedTests})
        })
    })
}

redux/constants/index.js:
export const USER_STATE_CHANGE = 'USER_STATE_CHANGE'
export const USER_TESTS_COMPLETED_STATE_CHANGE = 'USER_TESTS_COMPLETED_STATE_CHANGE'
export const CLEAR_DATA = 'CLEAR_DATA'

redux/reducers/index.js:
import { combineReducers } from 'redux'
import { user } from './user'

const Reducers = combineReducers({
    userState: user
})

export default Reducers

redux/reducers/user.js:
import { USER_STATE_CHANGE, CLEAR_DATA, USER_TESTS_COMPLETED_STATE_CHANGE } from "../constants"

const initialState = {
    currentUser: null,
    completedTests: [],
}

export const user = (state = initialState, action) => {
    switch (action.type) {
        case USER_STATE_CHANGE:
            return {
                ...state,
                currentUser: action.currentUser
            }
        case CLEAR_DATA:
            return initialState
        case USER_TESTS_COMPLETED_STATE_CHANGE:
            return {
                ...state,
                completedTests: action.completedTests
            }
        default:
            return state;
    }
}

For logged-in users, the app starts in this partially-recreated Main.js:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchUser, clearData, fetchUserCompletedTests } from '../redux/actions/index'

export class Main extends Component {
    componentDidMount() {
        this.props.clearData();
        this.props.fetchUser();
        this.props.fetchUserCompletedTests();
    }
    render() {
        // bottom tab navigation buttons - between Home.js, Study.js, and Profile.js
    }
}

const mapStateToProps = (store) => ({
    currentUser: store.userState.currentUser
})
const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser, clearData, fetchUserCompletedTests}, dispatch)
export default connect(mapStateToProps, mapDispatchProps)(Main);

If it helps you, my Profile.js file has this code to sign out the user:
function Profile(props) {

import { connect } from 'react-redux'
    import { bindActionCreators } from 'redux'
    import { fetchUser } from '../../redux/actions/index'

    ...

    const onLogout = () => {
            firebase.auth().signOut().then(() => {

            }).catch((error) => {
                console.log(error);
            })
        }

    ...
}

    const mapStateToProps = (store) => ({
        currentUser: store.userState.currentUser,
    })
    const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch)
    export default connect(mapStateToProps, mapDispatchProps)(Profile);

The problem started when I implemented this code into Home.js:
import React, { useState, useEffect } from 'react'
import { View, Text, FlatList } from 'react-native'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchUser, fetchUserCompletedTests } from '../../redux/actions/index'

function Home(props) {

    useEffect(() => {
        props.fetchUser();
    }, [props.currentUser] )

    useEffect(() => {
        props.fetchUserCompletedTests();
    }, [props.completedTests] )

    const { currentUser } = props;

    return (
        <View style={{flex: 1}}>
                <Text>Welcome back, {currentUser.name}!</Text>
                 // FlatList that shows the data stored from calling fetchUserCompletedTests()
        </View>
    )
}

const mapStateToProps = (store) => ({
    currentUser: store.userState.currentUser,
    completedTests: store.userState.completedTests
})
const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser, fetchUserCompletedTests}, dispatch)
export default connect(mapStateToProps, mapDispatchProps)(Home);

(I used fetchUser() and fetchUserCompletedTests() again in Home.js in order to reflect any local changes in the app whenever the user navigates to home - such as the user taking a test and then the data pertaining to that test is stored in Firebase)
The problem occurs when I try to log out, which returns this error:

null is not an object (evaluating'_firebase.default.auth().currentUser.uid')

If I reload the app after receiving the error, I am then logged out. This error did not appear prior to me using useEffect in Home.js to grab all the data everytime the user navigates to it. What am I doing wrong in my setup that causes this error when I try to log out?

A: Just looking at your code you only dereference uid once, here: firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).get().then((snapshot) => {
So I would imagine this line where you're dereferencing firebase.auth() is probably where you're getting a null at.
I mean, after you call firebase.auth().signOut(), do you expect props.currentUser to change? Also if fetchUser would trigger after logout, then what do you expect firebase.auth().currentUser.uid to actually be if not null?
Is your goal to NOT call fetchUser after logout? If so, then maybe your props.currentUser should have an if() block around it to make sure it doesn't call fetchUser() if props.currentUser is null, for example.
If you can sort that sequence of events out, I think you'll be set.


text:
Q: Why can I not use my BSNL USB Modem(LW273) ? I have BSNL USB Modem LW273 7.2MBPs data card. I had used it on windows 7. Now I use Ubuntu 12.10. But I am unable to use this USB modem on Ubuntu.

A: You should try wvdial, it should be available in the synaptics, it makes the setup process for datacards much easier. You can also install it by running the following in the terminal:
sudo apt-get install wvdial

Also, do explore the network applet and check the settings before you are confirmed. I think you didn't do the latter thoroughly.


text:
Q: Node.JS + Express parse CSV file on server Essentially, what I have is a form where a user will upload a CSV file.
<form action="/upload" method="POST" enctype="multipart/form-data">

        <input type="file" class="custom-file-input" id="customFile" name="file" required>
        Choose file

    <input type="submit" class="btn btn-primary btn-block">
</form>

FYI: I'm using getbootstrap.com as my style sheet.
Now, the form sends a POST request to /upload which is where my node.js code is. What I need is for the server to parse this CSV file and extract the data. I've got no idea what to do as all the different NPM packages such as Multer are using a system where the save the file locally and then parse it.
Edit: Forgot to mention this, but temporary local CSV hosting is not an option.
I need the client to upload server to process it and push to a DB, can't save the file locally anywhere.
Edit 2: I've used multer and the memory processing option and have gotten the following.
const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(req, res) {
  response.sendFile(__dirname + "/views/index.html");
});
app.post("/upload", upload.single('file'), async (req, res) => {
  res.send(req.file)
});
const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});

Now once I upload the file, I'm getting the following response (this is what req.file is).
{"fieldname":"file","originalname":"tech.csv","encoding":"7bit","mimetype":"application/octet-stream","buffer":{"type":"Buffer","data":[67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101]},"size":56}

So It's pretty clear that our data happens to be
67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101

but how do I process that? The csv file data was
CLASS ID,TECH #,FIRST NAME,LAST NAME
6O,6O01,Anish,Anne

So how do I go from the information provided in the buffer data attribute to the actual data?

A: All you have to use is Multer. Multer will return a buffer object which you can then make a string with the .toString() attribute.
Code:
const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(request, response) {
  response.sendFile(__dirname + "/views/index.html");
});

app.post("/upload", upload.single('file'), async (req, res) => {
  var b = req.file["buffer"]
  console.log(b.toString())
  res.send(b.toString())
});

const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});


text:
Q: Novice LED questions I'm hoping that you friendly and knowledgeable folk can help me finally figure out how I should be wiring up my LEDs in my panels.
Just a short history...
Many years ago I took over a panel building department which was in a dire state. I have managed to turn it around now having correct wiring diagrams, CE conformity, etc, etc.
I build 3 phase panels for use in the chain hoist industry and each panel has a 'handset' which controls the hoists. Each 'channel' on the handset has a toggle switch and bi-colour LED to show the direction chosen, green for up and red for down. Now ever since the dawn of time, we have fitted an AC transformer in the panel which sends 24v AC and a 0v down to the handset which goes to the toggle switches and also the LEDs.
On each toggle switch, we solder a resistor which then feeds both legs of the LED.
Now my question....
As far as I am aware it's unusual to power LEDs with an AC supply.  Primarily they prefer DC. I am assuming the use of the AC power supply was because of the very long distances these handsets have been used in (some over 100 meters) and thus the AC works better.
I wish to ditch the AC transformer and fit a DIN mounted 5amp DC unit.
My question is though, will I still have to fit the resistors? I know they should be needed to smooth out the current going to each LED but just wanted to check.
Below are links to the LEDs and resistors I use in case anyone wants to check the specs.
LEDs
Resistors
I hope you can help me gain more of an understanding of LEDs.

A:
Now ever since the dawn of time, we have fitted an AC transformer in the panel which sends 24v AC and a 0v down to the handset which goes to the toggle switches and also the LEDS.

This is probably because when the system was designed at the dawn of time,

*

*They might have used 24 V incandescent lamps instead of LEDs.

*A 24 V transformer was probably lower cost than a DC supply.

I wish to ditch the AC transformer and fit a din mounted 5amp DC unit. My question is though, will I still have to fit the resistors? I know they should be needed to smooth out the current going to each LED but just wanted to check.

You will still need to fit the resistors. These limit the current through the LED so it doesn't blow up. You will probably need a different resistor value to get the same brightness from your lamps, when you switch from 24 V AC to some other DC voltage.
You can also buy LEDs or LED lamps with the resistors built in, which could save you having to assemble the resistors yourself.

A: The LEDs from the link use indeed DC (afaik all LEDs do, but I don't have that much experience with different kind of leds).
Since those LEDs have 3 legs, these are two colored LEDs.
You will need resistors. It is not a normal lamp where the resistance is part of the lamp itself.
The resistors you use are way too much, if you use them, most of the power will go into heating up the resistors, which is not necessary.
As a basic rule, use:
V = I * R

Mostly those LEDs can have a continuous current of 20 mA, so if you use a 5 V DC power adapter, you need a resistor of V - Vfd = I * R <=> (5 - 2.2 = 0.02 * R) <=> R = 110 ohm. To be safe, use 120 ohm. 2.2 V is the so called 'forward voltage' and needs to be reduced (similar like a diode, a LED 'is' a specific type of diode).
The power through those resistors will be P = V * I = 5 * 0.02 = 0.1 W, which most through hole resistors can handle.
If you use a 5V adapter, you also can put two LEDs in series (with one resistor), than you will get V - Vfd = I * R <=> 5 - 2 * 2.2 = 0.02 * R <=> R = 30 R. However, since not every diode is equal, to use a slightly larger resistor. This gives you less power loss.
Also note, that LEDs have two different sides, so make sure you put the anode and cathode side correctly.
Update
First, I'm not experienced with LED chains myself.
For a 24 V supply, using 1200 R resistors, you will have:
V = I * R <=> 24 = I * 1200 <=> I = 20 mA

This is exactly the max current a LED can get so you are ok.
The power is:
P = V * I = 24 * 0.02 = 480 mW, which is just below 0.5W

So yes, one 1200 R resistors fit with one LED (or actually, one per color), but if you want to have less resistors you can put multiple LEDs in series with one resistor, and also you lose less power in resistors (heating).
E.g. Assume you want to use max 1/8 W resistors (default through hole), assuming 6 LED colors per chain:
0.125 = V * 6 * 0.02 = 1 V

This is the voltage through the resistor, this means the resistor should be:
V - Vfd = I * R <=> 24 - 6 * 2.2 = 6 * 0.02 * R <=> 10.8 = 0.12 * R <=> R = 90 R
Remember your bi color LEDs use 0.04 A per full led, and you might take some safety margin, e.g. the power should be 0.11 W instead of 0.125 what I used above.
But this way you save a lot of heat and number of resistors. Make sure the resistance is not almost 0, as the forward voltage might change slightly because of temperature, same as each resistor has a tolerance.

A: In fact you should stop using AC for this task immediately. When you look up the datasheet of the LED you may notice that the LEDs have a maximaum reverse voltage of only 5 V. This is exceeded by your current setup.
I recommend 150 Ohms resistor for 5V supply. You can't put the LEDs in series as they have a common cathode.

A:
As far as I am aware it's unusual to power LED's with an AC supply?

Yes.

Primarily they prefer DC?

It's not so much that they prefer DC, as that LED's don't like having current shoved through them in reverse.  And, in fact, if these are wired the way I suspect they are (just the resistor in series with the LED) then every half-cycle of AC they're seeing just about as much reverse current as they're seeing forward current during the other half cycle.  I'm surprised you don't have aging problems with them.

I am assuming the use of the AC power supply was because of the very long distances these handsets have been used in, some over 100mtrs! and thus the AC works better.

A simple transformer would have been less expensive than a converter.  I'm not sure at what point the cost would have reached parity for industrial stuff, but it was about ten years ago for wall-warts.

I wish to ditch the AC transformer and fit a din mounted 5amp DC unit.

5A is way more than you need for a few itty bitty LEDs.  24V / 1.2k\$\Omega\$ = 20mA.  If all you're doing is powering the lights, you need 20mA per light.

My question is though, will I still have to fit the resistors? I know they should be needed to smooth out the current going to each LED but just wanted to check.

It's not to smooth out the current, it's to limit the current.  A bare LED (which is what you have) drops a fairly constant voltage.  If you try to supply a constant voltage, then there will always be some mismatch, and you'll either get too little current or too much.  So you need resistors; those resistors are about right for a 24V supply, but you'll need to scale them for different supplies.

A: It has to be DC since this gives a stable current without flicker. Also, since a diode is a semiconductor, it will only allow current in one direction, unlike a bulb. If fed too much reverse voltage, it will break.
All LEDs have a rated current used for writing down the specification - 20mA is the industry standard for that. Absolute maximum rating is somewhere >25mA. Higher currents than that and the LED will blow up. Thus you need a current limiting resistor in series.
Forget about using 20mA though, you might need that much for crap-off-the-shelf LEDs like the one you linked. But you should go for a high intensity one instead, they cost the same but need far less current to produce the same light. Buying brighter LEDs ~200-300mcd for the same price means that you can cut the current consumption at least 20 times. Kingbright and others have these.
The next thing you need to note is that LEDs of different colors often have different forward voltage. Using Ohm's law is an over-simplification, the correct formula is (Vin - Vforward) / Iforward. So if you have 24VDC, a forward voltage of 2.5V for a certain color, and aim to get around 5mA, you should pick
(24-2.5)/(5*10^-3) = 4k3 ohm

4k7 might be a more sensible value, standard E series value.

And finally, you mention CE marking. To CE mark a control panel for hoists must conform to mandatory harmonized standards for electrical equipment. Namely EN 60204-32 regarding electronics for hoisting machines, which is harmonized under the Machinery Directive. This standard states which colors that should be used for certain situations (10.3.2). Red is reserved for emergencies and hazardous situations.
In order to dodge this text in the standard, you would need to raise a strong argument why red light is suitable for your product - for example if your customer has addressed this in their risk assessment. Which they probably haven't. So this is something that machinery inspection from any government is likely to leave remarks about.
In addition, it is very common that men have trouble distinguishing between the colors red and green in particular (women don't have this problem, but operators in traditional industry are mostly men still).
I would therefore recommend to use a different color than red. Green + yellow or green + white, something like that. You might have to use RGB diodes instead of bi-color.

A: Since you say you've never had a failure in the LEDs driven by 24VAC, I would think the old adage "never touch a running system" applies.
From the description, though, you are operating the LEDs in a way that could cause failure.  The LEDs you linked to have a maximum reverse voltage of 5V.  You are subjecting them to way lots more than that.
Your description sounds like you have this:

simulate this circuit – Schematic created using CircuitLab
If you are concerned about the LEDs being exposed to the high reverse voltage, then you could do this:

simulate this circuit
D3 conducts during the half cycle of the AC when the LEDs would normally be exposed to the high reverse voltage.  It prevents the reverse voltage from getting above about 0.7V.  When the LEDs light up, they are only exposed to their normal forward voltage.
If you do that, you will want to change R1 from a 1 watt part to may a 2 or 3 watt part because it will be conducting current for a larger part of the time.  You'll also want to use something like a 1N4002 - it is rated for higher voltage and current than required so you won't have reliability problems.

In the end, though, I suggest you consult an engineer locally.  He could look at your circuits and tell you if you need to worry about the LEDs - or, more importantly, worry about and fix something that you may not have thought of.


text:
Q: Is it possible to setup React Native devleopment environment inside docker? Let me first mention that we have three dockers for development and they are awesome.
One for React, One for Nextjs, and one for .NET.
All a developer in our team has to do, is to install linux (we force OS), git and nginx and docker, VS Code, and our shell scripts. That's it. And asides from Linux, the rest is totally automated. He only installs Linux, and then runs one script that takes care of everything.
Then he can run our own shell script commands and start developing any application he wants.
In other words, there is no need to install .NET, Node, SQL Server, etc.
Now, based on these experiences, we wanted to start coding React Native.
And to our shock, it seems that installing and configuring it inside a docker container is not possible.
But I wanted to ask the community, because this first step is very crucial in our success. We did a lot of work to reduce development environment setup for our tech stack, and if we are forced to leave it for React Native, then that's a fail for us.
Can we develop react inside a docker container? Can we at least build it inside a container and do not install Android Studio and XCode on each developer's machine?


text:
Q: Nontype template parameter I'm having trouble with nontype(int variable) template parameter.
Why can't I pass a constant int variable to a function and let the function instantiate the template?
template<int size>
class MyTemplate
{
  // do something with size
};

void run(const int j)
{
  MyTemplate<j> b; // not fine
}
void main()
{
  const int i = 3;
  MyTemplate<i> a; // fine;
  run(i); // not fine
}

not fine : compiler says, error: 'j' cannot appear in constant-expression

*

*EDIT

This is what I ended up with.
Maybe someone might use it, someone might suggest better way.
enum PRE_SIZE
{
    PRE_SIZE_256 = 256,
    PRE_SIZE_512 = 512,
    PRE_SIZE_1024 = 1024,
};

template<int size>
    class SizedPool : public Singleton< SizedPool<size> >
{
public:
    SizedPool()
        : mPool(size)
    {
    }
    void* Malloc()
    {
        return mPool.malloc();
    }

    void Free(void* memoryPtr)
    {
        mPool.free(memoryPtr);
    }

private:
    boost::pool<>       mPool;
};

template<int size>
    void* SizedPoolMalloc()
    {
        return SizedPool<size>::GetInstance()->Malloc();
    }

template<int size>
    void SizedPoolFree(void* memoryPtr)
    {
        SizedPool<size>::GetInstance()->Free(memoryPtr);
    }

void* SizedPoolMalloc(int size)
{
    if (size <= PRE_SIZE_256)
        return SizedPoolMalloc<PRE_SIZE_256>();
    else if (size <= PRE_SIZE_512)
        return SizedPoolMalloc<PRE_SIZE_512>();
}

void toRun(const int j)
{
    SizedPoolMalloc(j);
}
void Test17()
{
    const int i = 3;
    toRun(i);
}

A: Basically, C++ has two kinds of constants:
const int a = 5;
MyTemplate<a> foo; // OK

const int b = rand();
MyTemplate<b> foo; // Not OK.

The first example is a compile-time constant. In C++ standard speak, it's an Integral Constant Expression (ICE). The second example is a run-time constant. It has the same C++ type (const int) but it's not an ICE.
Your function void run(const int j) is a run-time constant. You could even pass in user input. Therefore it's not a valid template argument.
The reason for the rule is that the compiler must generate code based on the template argument value. It can't do so if it doesn't have a compile-time constant.

A: Because non-type template parameters require values at compile-time. Remember that templates are a compile-time mechanism; templates do not exist in the final executable. Also remember that functions and the passing of arguments to functions are runtime mechanisms. The value of the j parameter in run() will not be known until the program actually runs and invokes the run() function, well past after the compilation stage.
void run(const int j)
{
    // The compiler can't know what j is until the program actually runs!
    MyTemplate<j> b;
}

const int i = 3;
run(i);

That's why the compiler complains says "'j' cannot appear in constant-expression".
On the other hand, this is fine because the value of i is known at compile-time.
const int i = 3;
// The compiler knows i has the value 3 at this point,
// so we can actually compile this.
MyTemplate<i> a;

You can pass compile-time values to run-time constructs, but not the other way around.
However, you can have your run() function accept a non-type template parameter the same way your MyTemplate template class accepts a non-type template parameter:
template<int j>
void run()
{
    MyTemplate<j> b;
}

const int i = 3;
run<i>();

A: Because j should be known at compile time. In your example it is not.


text:
Q: Ignoring/Clearing Extra integers from user input I am stuck on this part of a program where the user enters multiple integers and only the first is selected. In my current code, the output is this.
There are 10 sticks on the board.
Jerry: How many sticks do you take (1-3)? *1 3 4 2*
There are 9 sticks on the board.
Sherry: How many sticks do you take (1-3)? There are 6 sticks on the board.
Jerry: How many sticks do you take (1-3)? Please enter a number between 1 and 3.
Jerry: How many sticks do you take (1-3)? There are 4 sticks on the board.
Sherry: How many sticks do you take (1-3)?

While in the given example, the output is this.
Jerry: How many sticks do you take (1-3)? *1 3 4 2*
There are 8 sticks on the board.
Pat: How many sticks do you take (1-3)? *3*
There are 5 sticks on the board.

It seems that the extra integers are queued up and waiting for the next scanner input command. In the given example, the extra integers are cleared away. How is this being done? Is there a command to clear all current user input or are all of the integers read in with .hasNextInt and any past the first one are simply tossed away? Also, where does hasNextInt look in the input? After resulting true or false, will the next hasNextInt command look in the same input location if no new input has been added?
(The text enclosed by ** is user input.)

A: If you can't be sure the user will enter the input correctly, you can do it by accepting Strings instead of ints. Like so:
Scanner s = new Scanner(System.in);
System.out.print("How many?: ");
int many = Integer.parseInt(s.nextLine().trim().split(" ")[0]);
System.out.println(many);

This will even handle inputs like "   2   5 6 5" as well as the examples you have by taking the entire input string, trimming off any leading and trailing " "s, splitting the string into an array of Strings around " "s, and returning the first one (the one you want) at index 0.
What it doesn't do, as written, is take care of inputs like " foo bar 42" or any other inputs where the first index of the split string is not able to be parsed as an integer. Trying to do so will result in a NumberFormatException.


text:
Q: test for read-only property vs. set/get key -- obj-c / cocoa If all i have is a list of keys, is there an elegant way to test an object for read-only vs. read/write properties? I realize I could string-bang the key:
NSString *setterString = [@"set" stringByAppendingString:[someKeyString capitalizedString]];
BOOL isReadWrite = [myObject respondsToSelector:NSSelectorFromString(setterString)];

Or better yet try to set a value for the key and check for an NSUndefinedKeyException - but using exceptions for non-exceptional behavior seems like poor form.
To be clear, i'd like to programmatically audit an object's properties and tell the difference between, for instance,
@property (readonly) NSString *someReadOnlyKey
@property NSString *someReadWriteProperty

edit: To be more clear, it shouldn't matter if the keys are implemented as @propertys or manual getter/setter. Only concerned about public interface. And thanks for asking what I'm trying to accomplish - that's probably more important to get right in the first place.
I'm trying to sketch out some code that generates graphic representations of an object's keys. All the keys are known beforehand - but I won't always know which keys will be sett-able (it's up to the particular subclass to implement)

A: You have two valid approaches:

*

*the respondsToSelector: method

*the runtime "trick" as exposed in Tommy's answer

I'll try to summarize the implication of both approaches, along with their drawbacks. You can then choose the approach more suitable to your needs.
Case 1
//MyClass.h

@property (readonly) NSString *someReadOnlyKey;

*

*runtime => readonly

*respondsToSelector => NO
Ok, everything works as expected.
Case 2
//MyClass.h

@property (readonly) NSString *someReadOnlyKey;

///////////////////////////////////////////////////////////////////////////

//MyClass.m

@property (readwrite) NSString *someReadOnlyKey;

*

*runtime => readwrite

*respondsToSelector => YES
If the property definition has been overridden, you'll get the actual property attribute being used. It doesn't matter whether you query about it from where the setter is visible, i.e. inside the class definition, or from outside. You will get the actual definition that has been used to synthesize the accessor methods.
Case 3
//MyClass.h

@property (setter=myCoolSetter) NSString *someReadOnlyKey;

*

*runtime => readwrite

*respondsToSelector => NO
With a custom setter name, the respondsToSelector trick won't work anymore, whereas the runtime is still providing the correct information.
Case 4
//MyClass.h

@property (readonly) NSString *someReadOnlyKey;

///////////////////////////////////////////////////////////////////////////

//MyClass.m

- (void)setSomeReadOnlyKey:(NSString *)someReadOnlyKey {
    _someReadOnlyKey = someReadOnlyKey;
}

*

*runtime => readonly

*respondsToSelector => YES
This time the runtime is failing, since the setter is there, but the property definition "doesn't know" about it.

A: Assuming you're fine with asking the metaclass (ie, you don't want to allow for potential instance-specific patches to the dispatch table), you can get property attributes from the runtime. Specifically:
// get the property; yes: that's a C string. This can see only things
// declared as @property
objc_property_t property =
    class_getProperty([instance class], "propertyName");

/* check property for NULL here */

// get the property attributes.
const char *propertyAttributes = property_getAttributes(property);

You can then check those attributes for read-only:
NSArray *attributes =
    [[NSString stringWithUTF8String:propertyAttributes]
        componentsSeparatedByString:@","];

return [attributes containsObject:@"R"];

If you want to be completely thorough, you should also check protocols via class_copyProtocolList and protocol_getProperty, in order to catch any @propertys that are incorporated into the class that way and — as noted below by Gabriele — some caveats apply around class extensions.

A: This might be one of the few times I might consider the exception route - that is of course if you need handle KVC.
The reason being that just checking for a set<key>: style method name is not really enough to determine if something is really settable, especially when you bring KVC into it.
KVC has well defined search patterns for when you try to set values, which can be seen in the Key Value Coding Programming Guide. This search path has many stops and even allows objects a last chance "are you sure you don't want to handle this setter" method with setValue:forUndefinedKey:, which can be used to prevent the NSUndefinedKeyException exception being thrown

A: You can use the following:
if ([obj respondsToSelector:@selector(setSomeReadOnlyKey:someReadOnlyKey:)]) {
   // Not a readonly property
}
else
   // Readonly property

This should work. Essentially, I am checking if the setter method exists.


text:
Q: Retrieving table headers from PHP function using jQuery I have a php function called getDay which returns the day of the week. That function is the following:
    function getDay($value){
        $start_date = date("w");
        $is_now = time();
        $number_of_secs_since_sunday = 86400 * $start_date;
        $result = $is_now - $number_of_secs_since_sunday + (86400 * $value);
        $day = date('Y-m-d', $result);
        return $day;
    }

That is then placed into the following PHP loop:
for($i = 0; $i < 7; $i++){
    echo "".getDay($i)."	";
}

This will return the current days of the week, always starting on Sunday.
Now in my actual 's I have a form per  where the user can submit data. The following is what I currently have:

I would like to use jQuery (because it seems the most straightforward route) to return the table header (aka that specific date) per text field, so that when I submit the text in a text field (ie, going to post.php) the date in the  will be passed.
For example, if you're in the row Total Jobs and the column 2015-07-12 and enter some data in that text field, when you submit the form, the date of 2015-07-12 will be posted to a MySQL database. Not worried about the MySQL part here, just getting the correct table header to be passed to each text field (when that particular form is submitted).
This is what I have currently for the jQuery, but it always returns the first day of the week (in this case 2015-07-12):
$('.table').on('click', '.btn-submit', function () {
    var th = $('.table th').eq($(this).index());
    alert(th.text());
});

Any help on the matter is greatly appreciated, as I think I'm making this more difficult than it has to be.

A: $(this).index() refers to the index of .btn-submit button but you need the index of the td so $(this).closest('td').index() should do it.
$('.table').on('click', '.btn-submit', function () {
    var th = $('.table th').eq($(this).closest('td').index());
    alert(th.text());
});

A: You are finding index of the button,while you need it for the .
Also i am assuming the button and the textbox are in the same ,since image is not very clear.
So try this,
$('.table').on('click', '.btn-submit', function () {
    var th = $('.table th').eq($(this).parent().index());
    alert(th.text());
});


text:
Q: How to move a div after another using animations I'm currently moving a div from one location to another, but I want to do it with some animations. Just have it slide to place and push the other divs down. How would I go about doing this?
Here is what I have so far.

var row = $('
Another row inserted
');
$('.container').append(row);

$('.button').click(function() {
 $('.row').addClass('row-changed');
 $('.container > div:nth-child(2)').after(row);
});
.row {
  color: blue;
}
.row-changed {
  color: red;
}

  <button class='button'>Move</button>

Row here

Row here

Row here

Row here

Row here

A: try this one

var row = $('
Another row inserted
');
$('.container').append(row.hide().slideDown());

$('.button').click(function() {
    $('.row').addClass('row-changed');

    var clone = row.clone().css("position", "absolute");
    $('.container').append(clone);
    row.css("visibility", "hidden");

    var sel = $('.container > div:nth-child(2)');
    sel.after(row.hide().slideDown());
    var position = sel.next().position();

    clone.animate({
        left: position.left,
        top: position.top
    }, 400, function() {
        clone.remove();
        row.css("visibility", "visible");
    });
});
.row {
  color: blue;
}
.row-changed {
  color: red;
}

  <button class='button'>Move</button>

Row here

Row here

Row here

Row here

Row here


text:
Q: Reading a double/float value on GUI text field I'm trying to build a GUI on NetBeans that calculates the mean of a set of values. Currently it works with whole number values, but when I try to input decimal values into the text field it only reads the part before the decimal point before moving on to the next value in the array (e.g. if I input 1.4, 2.5, 3.6 it reads it as 1, 2, 3 and calculates the mean as 2 instead of 2.5)
How do I get the computer to register the entire value?
    private void getMeanButtonActionPerformed(java.awt.event.ActionEvent evt) {

    String[] stringValues = valuesTextField.getText().split(",");
    double[] values = new double[stringValues.length];

  for(int i = 0; i < stringValues.length; i++)
    {
        values[i] = Double.parseDouble(stringValues[i]);
    }

    int sum = 0;
for (int i = 0; i < values.length; i++)
{
        sum += values[i];
}

    double mean = 0;
    mean = (double)sum / (double)values.length;

    JOptionPane.showMessageDialog(null, mean);
}

By the way, I've checked the stringValues array and all is good there-- the entire value is registered. Something seems to be going wrong in the parsing.

A: Problem is you have defined your sum as an int and not double
...
double sum;
for (int i = 0; i < values.length; i++)
{
    sum += values[i];
}


text:
Q: Core Data migration failing with error: Failed to save new store after first pass of migration In the past I had already implemented successfully automatic migration from version 1 of my data model to version 2. Now, using SDK 3.1.3, migrating from version 2 to version 3 fails with the following error:
Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 UserInfo=0x5363360 "Operation could not be completed. (Cocoa error 134110.)", {
    NSUnderlyingError = Error Domain=NSCocoaErrorDomain Code=256 UserInfo=0x53622b0 "Operation could not be completed. (Cocoa error 256.)";
    reason = "Failed to save new store after first pass of migration.";
}
I have tried automatic migration using NSMigratePersistentStoresAutomaticallyOption and NSInferMappingModelAutomaticallyOption and also migration using only NSMigratePersistentStoresAutomaticallyOption, providing a mapping model from v2 to v3.
I see the above error logged, and no object is available in the application. However, if I quit the application and reopen it, everything is in place and working.
The Core Data methods I am using are the following ones
- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil) {
        return managedObjectModel;
    }

    NSString *path = [[NSBundle mainBundle] pathForResource:@"MYAPP" ofType:@"momd"];
    NSURL *momURL = [NSURL fileURLWithPath:path];
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

    return managedObjectModel;

}
- (NSManagedObjectContext *) managedObjectContext {

    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MYAPP.sqlite"]];

  NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
  [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

  NSError *error = nil;
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
   if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
        // Handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
   }

return persistentStoreCoordinator;

}

In the simulator, I see that this generates a MYAPP~.sqlite files and a MYAPP.sqlite file. I tried to remove the MYAPP~.sqlite file, but
BOOL oldExists = [[NSFileManager defaultManager] fileExistsAtPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MYAPP~.sqlite"]];

always returns NO. Any clue? Am I doing something wrong?
Thank you in advance.

A: I ran into this as well and after reading as much Apple docs and web postings as I could find there didn't seem to be an answer.  In my case the manual migration was working as well but when I went to open up a new coordinator it would give the same error you had.  I finally decided to go back to my last working version of the data model and do a series of small changes/versions and see where it broke the auto-migration capabilities to drill further into it and it turned out it didn't. Now I can add entities, attributes and relationships without issue and they auto-migrate.  Any chance you deleted an interim version of the datamodel?

A: For what it's worth, the Magical Record Core Data utility package includes this hack:
[coordinator MR_addAutoMigratingSqliteStoreNamed:storeFileName];

//HACK: lame solution to fix automigration error "Migration failed after first pass"
if ([[coordinator persistentStores] count] == 0)
{
    [coordinator performSelector:@selector(MR_addAutoMigratingSqliteStoreNamed:) withObject:storeFileName afterDelay:0.5];
}

You might try something similar.  I have been unable to find an explanation of what the problem is, though, or why just retrying it would work.