text:
Q: Cant seem to get my ifstream and ofstream to work properley when using getline() and Ignore() functions Cant Use Loops or Arrays ect I cant read in the integers after my getline() reads in the string. I have to read in the whole entire name from a data file, then read in the pay rate, then the number of dependants, and then the percentage of gross. I can use Arrays loops vectors or anything of that sort. I can only use the getline() and Ignore() functions or something similar to that. So my question is where am I going wrong here?
Here is what the data file looks like (I only coded for it to read in one person):

John W. Smith
12.55
3
5
Mary Anderson
11.75
1
8
Brad W. Baker
11.75
0
0
Heather Johnson
13.25
2
10

Here is my code so far:
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream indata;
    ofstream outdata;
    string fname, lname;
    int hours;
    hours = 0;
    outdata.open("Weeklypay.dat");
    double payrate;
    double gross;
    double taxes;
    double ssecurity;
    int dependants;
    double retirement;
    double net;
    double percgross;
    int insurance;

    indata.open("Pay.dat");
    getline(indata, fname);

    cout << "Please enter the total hours worked for " << fname << endl;
    cin >> hours;
    indata >> payrate >> insurance;
    gross = payrate * hours;
    taxes = 0.23 * gross;
    ssecurity = 0.08 * gross;
    dependants = 12 * insurance;
    indata >> percgross;
    retirement = percgross * gross / 100;
    net = gross - taxes - ssecurity - dependants - retirement;

    cout << fname << "'s net pay is: $" << net << endl;
    outdata << fname << endl;
    outdata << "Gross Pay: $" << gross << endl;
    outdata << "Taxes: $" << taxes << endl;
    outdata << "Social Security: $" << ssecurity << endl;
    outdata << "Insurance: $" << dependants << endl;
    outdata << "Retirement: $" << retirement << endl;
    outdata << endl << endl;
    outdata << "Net Pay: $" << net << endl;
    outdata << endl << endl;

    // Next person here:

    cin.ignore(10, '\n');
    getline(indata, fname);

    cout << "Please enter the total hours worked for " << fname << lname << endl;
    cin >> hours;

    indata >> payrate;
    gross = payrate * hours;
    taxes = 0.23 * gross;
    ssecurity = 0.08 * gross;
    indata >> insurance;
    dependants = 12 * insurance;
    indata >> percgross;
    retirement =  percgross * gross / 100;
    net = gross - taxes - ssecurity - dependants - retirement;

    cout << fname << lname << "'s net pay is: $" << net << endl;
    outdata << fname << lname << endl;
    outdata << "Gross Pay: $" << gross << endl;
    outdata << "Taxes: $" << taxes << endl;
    outdata << "Social Security: $" << ssecurity << endl;
    outdata << "Insurance: $" << dependants << endl;
    outdata << "Retirement: $" << retirement << endl;
    outdata << endl << endl;
    outdata << "Net Pay: $" << net << endl;
    outdata << endl << endl;

     indata.close();
     outdata.close();

     return 0;
}

A: change retirement = percgross * gross; to retirement = percgross * gross / 100; You read in the percentage  of gross, and multiply it directly, then the retirement is bigger than gross.
EDIT:
for the multiple persons scenario, use a loop statement.
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream indata;
    ofstream outdata;
    string fname, lname;
    int hours;
    hours = 0;
    outdata.open("Weeklypay.dat");
    double payrate;
    double gross;
    double taxes;
    double ssecurity;
    int dependants;
    double retirement;
    double net;
    double percgross;
    int insurance;

    indata.open("Pay.dat");

    while(getline(indata, fname) )
    {
        if(fname.empty() )
            continue;
        cout << "Please enter the total hours worked for " << fname << endl;
        cin >> hours;
        indata >> payrate >> insurance;
        gross = payrate * hours; //690.25
        taxes = 0.23 * gross;//158.75
        ssecurity = 0.08 * gross;//51.7
        dependants = 12 * insurance;//3
        indata >> percgross;
        retirement = percgross * gross / 100;//34.51
        net = gross - taxes - ssecurity - dependants - retirement;

        cout << fname << "'s net pay is: $" << net << endl;
        outdata << fname << endl;
        outdata << "Gross Pay: $" << gross << endl;
        outdata << "Taxes: $" << taxes << endl;
        outdata << "Social Security: $" << ssecurity << endl;
        outdata << "Insurance: $" << dependants << endl;
        outdata << "Retirement: $" << retirement << endl;
        outdata << endl << endl;
        outdata << "Net Pay: $" << net << endl;
        outdata << endl << endl;

    }

    indata.close();
    outdata.close();

    return 0;
}


text:
Q: Trying to filter strings in list in Reactjs This code works, but NOT as expected. For example, typing: red displays "Red Hot Chili Peppers", but continuing with red hot, and it disappears. I am not sure, how a new RegExp should be applied in this code. I managed to come this far with the filtering.
query = "red hot";
const matches = [
    "Red Hot Chili Peppers",
    "Dua Lipa",
    "X&Y",
    "Viva la Vida or Death and All His Friends"
];

const lowercasedFilter = query.toLowerCase();
  const filtered = matches.filter(item => {
    return Object.keys(item).some(key =>
      typeof item[key] === "string" && item[key].toLowerCase().includes(lowercasedFilter)
    )
});

EDIT: I am sorry, my bad. I have a list of objects.

An object:
0: {…}
external_urls: Object { spotify: "https://open.spotify.com/artist/0L8ExT028jH3ddEcZwqJJ5" }
followers: Object { href: null, total: 14620829 }
genres: Array(5) [ "alternative rock", "funk metal", "funk rock", … ]
href: "https://api.spotify.com/v1/artists/0L8ExT028jH3ddEcZwqJJ5"
id: "0L8ExT028jH3ddEcZwqJJ5"
images: Array(3) [ {…}, {…}, {…} ]
name: "Red Hot Chili Peppers"
popularity: 86
type: "artist"
uri: "spotify:artist:0L8ExT028jH3ddEcZwqJJ5"
<prototype>: Object { … }

EDIT: This comes close, but doesn't work as expected:
 const filtered = matches.filter(match => {
        const regex = new RegExp(`^${query}`, 'gi');
        return match.name.match(regex);
      });

Doesn't work: red hot chili peppers.

A: As commented:

No need for this: Object.keys(item) and item[key] === "string" as its an array of string

Your structure is an array of string. So you can directly consume the value and use String methods to validate it
If you have a complex data structure, like nested objects, then using Object.keys and then looping on them makes more sense as you do not know what keys you might need.

const query = "red hot";
const matches = [
    "Red Hot Chili Peppers",
    "Dua Lipa",
    "X&Y",
    "Viva la Vida or Death and All His Friends"
];

const filteredList = matches
  .filter((match) => match.toLowerCase().includes(query))

console.log(filteredList)

You can even use Regex for this. This will allow you to ignore toLowerCase() call for every iteration

var list = [{
  external_urls: {
    spotify: "https://open.spotify.com/artist/0L8ExT028jH3ddEcZwqJJ5"
  },
  followers: {
    href: null,
    total: 14620829
  },
  genres: ["alternative rock", "funk metal", "funk rock"],
  href: "https://api.spotify.com/v1/artists/0L8ExT028jH3ddEcZwqJJ5",
  id: "0L8ExT028jH3ddEcZwqJJ5",
  name: "Red Hot Chili Peppers",
  popularity: 86,
  type: "artist",
  uri: "spotify:artist:0L8ExT028jH3ddEcZwqJJ5"
}]
const query = 'red hot'
const regex = new RegExp(query, 'gi')
const filteredList = list
  .filter((item) => regex.test(item.name))
console.log(filteredList)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating map legend in ArcMap? Finished all my analysis and would like to make a legend to display the data in the map I have.

A: In ArcMap 9 and 10 you can go to Insert > Legend in layout view, and follow the GUI to create & format the legend.


text:
Q: Problem with reversing order of words in a sentence I want to read inputtext.txt line by line and reverse the order of words in each line and print them out (input: hello world,output: world hello). With this code my output is all messed up and I get a runtime error #2 saying the stack around my array "string" is corrupted. I tried resetting the strings to null after each while loop iteration but I still get the same error. Does anybody have any suggestions to get rid of the runtime error or help the code run more smoothly?
int main() {
    FILE *inp,*outp;        //file input and output
    int i,wordcount;                    //define counter variables
    int k = 0,j=0;
    char string[200];       //define string to scan sentence into
    char words[20][20];     //2D string for each word in the sentence
    inp = fopen("inputtext.txt", "r");
    outp = fopen("output.txt", "w");
    if (inp == NULL) {
        printf("File not found.\n");
    }
    else {
        while (!feof(inp)) {

            fgets(string, 1000, inp);
            printf("GOT SENTENCE\n");
            for (i = 0; string[i] != '\0'; i++) {

                if (string[i] == ' ') {
                    words[k][j] = '\0';
                    k++;
                    j = 0;
                }
                else
                {
                    words[k][j] = string[i];
                    j++;
                }

            }

            words[k][j] = '\0';
            wordcount = k;
            for (i = wordcount; i >= 0; i--) {
                printf("%s ", words[i]);
            }
            printf("\n\n");

        }
    }
    return 0;
}

A: the following proposed code:

*

*cleanly compiles

*properly checks for errors

*properly outputs error messages to stderr

*performs the desired functionality

*properly limits the max length of an input

*assumes no line in the input file is over 199 characters

*minimizes the number of times the function: strlen() is called

*actually writes the reversed sentences to the output file

And now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *inp,*outp;        //file input and output
    int wordcount;                    //define counter variables
    int k = 0;
    int j = 0;
    char string[200];       //define string to scan sentence into
    char words[20][20];     //2D string for each word in the sentence

    inp = fopen("inputtext.txt", "r");
    if( !inp )
    {
        perror( "fopen to read: inputtext.txt failed" );
        exit( EXIT_FAILURE );
    }

    outp = fopen("output.txt", "w");
    if( !outp )
    {
        perror( "fopen to write: output.txt failed" );
        // cleanup
        fclose( inp );
        exit( EXIT_FAILURE );
    }

    size_t strLength = strlen( string );

    for (size_t i = 0; i < strLength; i++)
    {
        // remove any trailing newline
        string[ strspn( string, "\n" ) ] = '\0';

        printf("GOT SENTENCE\n");

        for (size_t i = 0; i < strlen(string); i++)
        {
            if (string[i] == ' ')
            {
                words[k][j] = '\0';
                k++;
                j = 0;
            }

            else
            {
                words[k][j] = string[i];
                j++;
            }
        }

        words[k][j] = '\0';
        wordcount = k;

        for ( int i = wordcount; i >= 0; i--)
        {
            printf("%s ", words[i]);
            fprintf( outp, "%s ", words[i] );
        }
        printf("\n\n");
        fprintf( outp, "\n" );
    }

    return 0;
}


text:
Q: recursion, global variables, and OpenMP I'm having troubles with a function that calls itself
the proper way of threading with openmp is unclear to me on that case.
long *arrayofindex;
int length, N;

void gen(long index)
{
    if(index == 0)
    {
        #pragma omp parallel for
        for(int a=0; a<N; ++a)
        {
            #pragma omp critical
            {
            gen(index+1);
            ++arrayofindex[index];
            }
        }
    }
    else
    {
        for(arrayofindex[index]=0; arrayofindex[index]<N; ++arrayofindex[index])
        {
            if(index < length-1)
                gen(index+1);
            else printf("%ld\n", arrayofindex[index]);
        }
    }
}

int main(){
    length = 5, N = 4;
    arrayofindex = (long*) malloc(length * sizeof(long));
    for(int i=0; i<length; ++i)
        arrayofindex[index] = 0;
    gen(0);
}

the way I did it, it runs several threads and is correct but doesn't seem to get any faster than without openmp support.
Is there an way through this ? or is it going to be helpless because of the way of the code.
The complete code https://github.com/e2002e/zhou

A: As I understand the code presented, the general objective is essentially to generate all the N-letter words that can be formed with a length-letter alphabet.  Each recursive call to gen() corresponds to one letter position, and so each time control reaches the bottom of the recursion, the first N elements of arrayofindex represent the letters of one word.
But it should be obvious that multiple threads running in parallel cannot use the same arrayofindex.  Each thread expects when it reaches the bottom of the recursion to find  in arrayofindex the values that it set along its recursive path.  That's fundamental to the approach.  If other threads are modifying arrayofindex at the same time then they all likely get mishmashes of values set by different threads.  Moreover, you probably don't get anything like the speedup you hope for, because the threads need to synchronize their accesses to arrayofindex.

Note: This problem has nothing in particular to do with recursion.  You would have exactly the same issue if you modified the code to be iterative instead of recursive -- which I, myself, would in fact do if I were looking to improve performance, though I do not demonstrate that here.

There are various ways to give each OMP thread its own working array.  If the space must continue to be dynamically allocated, then you should arrange for it to be allocated inside the parallel region, so that each thread allocates its own.  If you're willing and able to rely on variable-length arrays for this, however, then probably the only other thing you need is an OMP private clause attached to your parallel for construct.
For example, this variation on your code works for me:
void gen_tail(int length, int num_letters, int arrayofindex[], int position) {
    for (int letter = 0; letter < num_letters; letter++) {
        arrayofindex[position] = letter;
        if (position + 1 < length) {
            gen_tail(length, num_letters, arrayofindex, position + 1);
        } else {
            // this is the bottom ... do something with arrayofindex, such as:
            #pragma omp critical
            {
                for (int i = 0; i < length; i++) {
                    putchar('A' + arrayofindex[i]);
                }
                putchar('\n');
            }
        }
    }
}

void gen(int length, int num_letters) {
    assert(length > 1);
    int arrayofindex[length];  // Note: VLA, _not_ dynamically allocated

    // Marking the array 'private' means each thread gets its own copy.
    // This would not have the needed effect if 'arrayofindex' were a pointer.
    #pragma omp parallel for private(arrayofindex)
    for (int letter = 0; letter < num_letters; letter++) {
        arrayofindex[0] = letter;
        gen_tail(length, num_letters, arrayofindex, 1);
    }
}

int main(void) {
    gen(5, 4);
}

That emits the expected 1024 (== 45) results for me, all distinct, as I have every reason to expect it should do.


text:
Q: Modify javascript files with an event i work with the freeware tool gpxviewer (https://www.j-berkemeier.de/GPXViewer/) to visualize gps tracks.
my question:
I would like to implement a dropdown to the html to change the appearence and scaling.
There are javascript files where i would like to change some parameters while the site is open.
Is it possible to make a  menu, which opens the js files, modifies some line of codes and reload the page with the new parameters?
<select id="dropdown" onchange="changeFunc();">
    <option value="variante1" selected>Variante1</option>
    <option value="variante2">Variante2</option>
    <option value="variante3">Variante3</option>
</select>

lines in javascript file i would like to modify with the select-menu (example):
JB.Scaling = {
   bandwidthDownmin: 0,bandwidthDownmax: 150,
   hardscaling:true
};

thank you for your help

A: Scripts running in web browsers cannot edit files on the server like this directly. If they could, literally anybody could make literally any change they wanted to your site. No offense, but this should be 100% obvious to you before you work on a project like this. If it isn't, you really need to do some reading first.
As for how to actually do something like this... You can simply assign over values in JB.scaling as I'm doing here:
JB.scaling.bandwidthDownmin = 10;
JB.scaling.bandwidthDownmax = 200;

However, as comments have mentioned, this probably won't do anything because your "tool" almost certainly won't check these values and make updates unless you explicitly tell it to. For that, it will need to have a function you can call. See if you can find it in the documentation. I'd help, but I can't read German. :\
Note that telling the "tool" to redraw is distinct from actually reloading the page. Reloading the page is what happens when you click the "refresh"  button on your browser. This effectively throws out the page you're looking at-- along with any local changes you've made to its contents-- and requests a fresh copy from the server.
You can trigger this with Javascript, but if you do it, you'll be throwing away any changes you've made to these values, as well as which option the user has selected from the drop-down. In order for their choice to persist between page loads, you'll have to use cookies or local storage. You could also set up a database to store things on the server, but that's probably overkill.


text:
Q: FBSDKMessageDialog for iOS doesn't work FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
content.contentURL = [NSURL URLWithString:APPSTORE_URL_MAIN];
content.contentTitle = INVITE_TITLE;
content.imageURL = [NSURL URLWithString:INVITE_IMG_URL];
content.contentDescription = INVITE_TEXT;

[FBSDKMessageDialog showWithContent:content delegate:self];

If the Facebook Messenger app is closed, this just opens the app and does nothing else.
Works fine is the FB Messenger app is working in background

A: Issue resolved by Facebook Developers.


text:
Q: Using layer loadstart & loadend events in OpenLayers 3? OpenLayers 2 has these layer events "loadstart & loadend."
What is equivalent to them in OpenLayers 3?
While a vector layer loads and is rendered, I need to show a loading icon.

A: Assuming you use an ol.layer.Vector with an ol.source.GeoJSON you can use something like this:
var vectorSource = new ol.source.GeoJSON({
  projection : 'EPSG:3857',
  url: 'http://examples.org/fearures.json'
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

map.addLayer(vectorLayer);

// show loading icon
// ...

var listenerKey = vectorSource.on('change', function(e) {
  if (vectorSource.getState() == 'ready') {
    // hide loading icon
    // ...
    // and unregister the "change" listener
    ol.Observable.unByKey(listenerKey);
    // or vectorSource.unByKey(listenerKey) if
    // you don't use the current master branch
    // of ol3
  }
});

This shows how to get a notification when the vector source is loaded. It only works with sources inheriting from ol.source.StaticVector. Examples include ol.source.GeoJSON and ol.source.KML .
Also, note that this code may no longer work in the future when ol3 will provide a consistent way to know if/when a source is loaded.

A: I have not found the class ol.source.GeoJSON, and could not find a case where vectorSource.getState() != 'ready'. So I ended up doing something like this:
    function spin(active) {
        if (active) {
            // start spinning the spinner
        } else {
            // stop spinning the spinner
        }
    }

    // Toggle spinner on layer loading
    layer.on('change', function() {
        spin();
    });
    layer.getSource().on('change', function() {
        spin(false);
    });

A: In ol3 version 3.10.0 things have changed. So is more clear than older versions but still more complicated than ol2.
So for TILE (ol.layer.Tile) layers your code snip should look like:
//declare the layer
var osmLayer =  new ol.layer.Tile({
  source: new ol.source.OSM()
});
//asign the listeners on the source of tile layer
osmLayer.getSource().on('tileloadstart', function(event) {
//replace with your custom action
document.getElementById('tilesloaderindicatorimg').src = 'css/images/tree_loading.gif';
 });

osmLayer.getSource().on('tileloadend', function(event) {
//replace with your custom action
document.getElementById('tilesloaderindicatorimg').src = 'css/images/ok.png';
 });
osmLayer.getSource().on('tileloaderror', function(event) {
//replace with your custom action
document.getElementById('tilesloaderindicatorimg').src = 'css/images/no.png';
 });

while for WMS layers the approach is a bit different:
//declare the layer
var wmsLayer =   new ol.layer.Image({
source: new ol.source.ImageWMS({
  attributions: [new ol.Attribution({
    html: '© ' +
        '' +
        'National parks / geo.admin.ch'
  })],
  crossOrigin: 'anonymous',
  params: {'LAYERS': 'ch.bafu.schutzgebiete-paerke_nationaler_bedeutung'},
  serverType: 'mapserver',
  url: 'http://wms.geo.admin.ch/'
})
});

//and now asign the listeners on the source of it
var lyrSource = wmsLayer.getSource();
  lyrSource.on('imageloadstart', function(event) {
  console.log('imageloadstart event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/tree_loading.gif';
  });

  lyrSource.on('imageloadend', function(event) {
   console.log('imageloadend event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/ok.png';
  });

  lyrSource.on('imageloaderror', function(event) {
   console.log('imageloaderror event',event);
  //replace with your custom action
  var elemId = event.target.params_.ELEMENTID;
  document.getElementById(elemId).src = 'css/images/no.png';
  });

For WFS Vector layers things are even more complicated:
//declare the vector source
sourceVector = new ol.source.Vector({
    loader: function (extent) {
        //START LOADING
        //place here any actions on start loading layer
        document.getElementById('laodingcont').innerHTML = "start loading.....";
        $.ajax('http://demo.opengeo.org/geoserver/wfs', {
            type: 'GET',
            data: {
                service: 'WFS',
                version: '1.1.0',
                request: 'GetFeature',
                typename: 'water_areas',
                srsname: 'EPSG:3857',
                bbox: extent.join(',') + ',EPSG:3857'
            }
        }).done(loadFeatures)
            .fail(function () {
            //FAIL LOADING
            //place here any actions on fail loading layer
            document.getElementById('laodingcont').innerHTML = "error loading vector layer.";
        });
    },
    strategy: ol.loadingstrategy.bbox
});

//once we have a success responce, we need to parse it and add fetaures on map
function loadFeatures(response) {
formatWFS = new ol.format.WFS(),
sourceVector.addFeatures(formatWFS.readFeatures(response));
 //FINISH LOADING
document.getElementById('laodingcont').innerHTML = "finish loading vector layer.";
}

check this post. it has all the above +  a fiddle for the WFS vector layers

A: you can also use the getState() function
if (source instanceof ol.source.Vector) {
        source.on("change", function () {
            //console.log("Vector change, state: " + source.getState());
            switch (source.getState()) {
                case "loading":
                    $("#ajaxSpinnerImage").show();
                    break;
                default:
                    $("#ajaxSpinnerImage").hide();
            }
        });
    }

A: On OL 4.5.0, for vector layers I haven't found a way to deal with the source, instead I use the following on the layer events:
if (layer instanceof ol.layer.Vector) {
    layer.on("precompose", function () {
              $("#ajaxSpinnerImage").show();
            });
    layer.on("render", function () {
              $("#ajaxSpinnerImage").hide();
            });
}

Hope it can help.


text:
Q: How to remove the empty node in the treeview WPF Desired Output
---1
--------11
---2
--------22
---3
--------33
Actual Output:
---(Empty Node)
--------1
-----------11
--------2
-----------22
--------3
-----------33
If I add header to treeviewitem i get the following result:
---Header
--------1
-----------11
--------2
-----------22
--------3
-----------33
Here is the below XAML code
<TreeView>
    <TreeViewItem ItemsSource="{Binding Groups,Mode=OneWay}" Header="Root">
        <TreeViewItem.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Vertical" Height="Auto" Width="Auto" Background="Transparent" VirtualizingStackPanel.VirtualizationMode="Recycling" VirtualizingStackPanel.IsVirtualizing="True"/>
            </ItemsPanelTemplate>
        </TreeViewItem.ItemsPanel>
        <TreeViewItem.Resources>
            <Style TargetType="{x:Type TreeViewItem}" >
                <Setter Property="ItemsSource" Value="{Binding Members,Mode=OneWay}"/>
                <Setter Property="DisplayMemberPath" Value="Number"/>
            </Style>
        </TreeViewItem.Resources>
    </TreeViewItem>
</TreeView>

A: Just go one step deeper when you assign the ItemsSource of the TreeView itself so that the children of your root become the items for the tree view. Here's how its done
  <TreeViewItem ItemsSource="{Binding Groups,Mode=OneWay, XPath=./*}" Header="Root" />

Notice XPath in there!


text:
Q: jQuery plugin overwrite option Unfortunately I am stumbling upon an issue with jQuery plugins.
I made a small plugin to facilitate building bootstrap modals.
The options for the plugin look like this:
defaults = {
    modalName: "",
    size: "md",
    title: "",
    body: "",
    buttons: {
        confirm: {
            class: 'btn btn-primary',
            value: 'Save'
        },
        cancel: {
            class: 'btn btn-default',
            value: 'Cancel'
        }
    }
};

But I want the value of the confirm button to differ for some pages. I thought I could just do this:
$( 'body' ).CreateModel ( {
    // Different settings
    buttons: {
        confirm: {
            value: 'Save & exit'
        }
    }
});

But unfortunately, this completely purges the default object and it only leaves buttons.confirm.value. Is there any way I can fix this?
Thanks in advance!

A: You haven't shown us your implementation of how you're working with defaults and the object passed in arguments, respectively, but you would be able to solve this problem using $.extend.
Something like this:
$.fn.CreateModel = function(options) {
  options = $.extend({}, defaults, options);
  ....
};

A: Using the jQuery function .extend, You can pass true as first parameter that allow a deep merging.
You have to change the line this.options = $.extend( {}, defaults, options) ; to :
this.options = $.extend(true, {}, defaults, options) ;

See an example here : http://jsfiddle.net/n5BKk/


text:
Q: How to print logs in jsonformat with metadata field in jbpm/wildfly? I am using jbpm 7.37 standard edition, with  WildFly Full 14.0.1.Final (WildFly Core 6.0.2.Final).
I am using logger class(org.slf4j.LoggerFactory,org.slf4j.Logger) to print the logs.
I have enabled custom REST endpoints.I am using Jersey REST api.
I am making custom jar fil where I have written custom code (custom REST APIs) and deploying this jar file inside kie-server.war file.
I want to print logs in json format for my custom class.
Like below :
{"timestamp":"2021-03-04T05:27:07.063Z",
"service":"demo",
"level":"error/info",
"message":"Errormessage/Info message",
"metadata":{"requestId":"somerequestid","sessionId":"somesif"}
}

However i am able to print logs in json format with the below command :
sudo bash jboss-cli.sh -c "/subsystem=logging/json-formatter=json:com.demo.add(exception-output-type=formatted, pretty-print=true, meta-data={service=demo})"

But this gives me output like below :
{"timestamp":"2021-03-04T05:27:07.063Z",
"service":"demo",
"level":"error/info",
"message":"Errormessage/Info message",
}

Not able to print the "metadata":{"requestId":"somerequestid","sessionId":"somesrequestid"}
The fields requestId and sessionId are having runtime values which i have to get from the http request.
From @HeaderParam("requestId"),@HeaderParam("sessionId") and needs to append with each and every response.
When i append this values in my response it shows inside the "message" field as follow.
{"timestamp":"2021-03-04T05:27:07.063Z",
"service":"demo",
"level":"error/info",
"message":"data{"requestId":"somerequestId","sessionId":"somesessionId"}",
}

How do i print the values for requestId and sessionId for each and every request
as "metadata":{"requestId":"somerequestid","sessionId":"somesid"} ?


text:
Q: using this to hold variable in a function? Why not just use let total in below case? I know the purpose is to demo how arrow function solve the this dilemma but in the real world do we have real use case for this?
function sum() {
  this.total = 0;

  arr.forEach((item) => {
    this.total+= item;  // all is well `this` points to outer function
  })
  return this.total;
}

A: Local variable make sense in above case. But this (lexical scope) using arrow function has wider use.
Now a days you uses framework for your project which has components and all. We have variable at component level and then that are bound to html.
class component {
  constructor() {
   this.data  = {};
  }
  // lets say you bring data and have to assign to above this.data
  getData() {

      somePromise.then((res) => {
        this.data = res // you can access parent. No this dra,a
      })
  }

 }

But in case of normal function
  getData() {
      const self = this; // save parent this to local variable
      somePromise.then(function(res) {
           self.data = res // now you can set data as function'this is different here
      })
   }

There are other approach as well. You can bind your anonymous function with this using native bind function and then you can access valid this inside anonymous function.
So in real world, arrow function has solved this dilemma brilliantly.


text:
Q: How are multiple variables and lists given in a for loop interpreted? Since my text book tutorial on lists and for loops, I have come to see for loops written with more complexity than the type that were explained:
for i in list:

Often times I will see something like
for j, k in l, ll:

and that's just one example of varied syntax for loop I have seen.
Let's use this example to demonstrate how I've tried to explain to myself in the shell how to read these multiple variable/multiple list for loops.
>>> l
['one', 'two']
>>> ll
['b', 'a']

With these values, I can do:
>>> for j, k in l, ll:
...     print(j, k)
...     print("increment")
...
one two
increment
b a
increment

Okay, so I tried l.append("three") and running the same lines back in the shell. This results in this:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

I want to understand in English how to read the syntax when multiple values are given for vars/lists in a for loop, and I just don't get it.

I have gathered from reading other questions that the iterable j, k is a tuple, which makes sense now that I think about it. But I still don't understand what is going on when there are multiple lists, probably to be understood as a tuple of two lists as well.
I believe that what I am struggling to understand about for-loops is described in the documentation as "list comprehension," which is amusing since I am not comprehending it.
If anyone can make this more clear at the highest level, that would be great.

A: The way to read this statement:
for j, k in l, ll:
    print(j, k)

is that l,ll is treated as a tuple containing two lists with each list expected to have exactly two elements (which will be unpacked to loop variables j and k).
It would be the same as writing:
for j, k in (l, ll):
    print(j, k)

The j, k part of the for loop "unpacks" the content of each list so these list MUST have exactly two elements.
The number of iterations corresponds to the number of lists provided.  You could add a third list but it will need to also have two elements.  You cannot add elements to these lists because they would not fit into the j,k assignment of the for loop
lll = ['x','y']
for j,k in l, ll, lll:
    print(j,k)

# one two
# b a
# x y

A: When you write for i in a, b:, it is the same as for i in (a, b):
Let's take a closer look. Imagine you have this code:
array = [(1, 2), (3, 4), (5, 6)]
for i in array:
    print(i)

It's easy to understand that output of this code is this:
(1, 2)
(3, 4)
(5, 6)

You iterate throw a list of tuples. Now, in Python, there is a syntax to get the values of a tuple in different variables like this:
i, j = (1, 2)

which is the same as
i, j = 1, 2

So you could also have written your loop like this:
for i, j in a, b:
    print(i, j)

And get the same output:
1 2
3 4
5 6

But now imagine that you change your array like this
array = [(1, 2), (3, 4), (5, 6, 7)]

Python won't be able to figure out what you mean when you ask him to get i and j from (5, 6, 7) and that's the cause of the ValueError.


text:
Q: cannot catch SQLAlchemy IntegrityError Try as I might, I can't seem to catch the sqlalchemy IntegrityError correctly:
from sqlalchemy import exc

try:
    insert_record()
except exc.IntegrityError, exc:
    print exc # this is never called
    handle_elegantly() # this is never called

As what one might expect:
IntegrityError: (IntegrityError) insert or update on table "my_table"
                violates foreign key constraint "my_table_some_column_fkey"

I've tried to explicitly:
from sqlalchemy.exc import IntegrityError

UPDATE:
I found something that seems to fit what's happening here, where Integrity Error isn't thrown until the session is flushed to the db, and after the try/exceptblocks have been executed: Trying to catch integrity error with SQLAlchemy
However, adding session.flush() in the try block yields an InvalidRequestError:
ERROR:root:This Session's transaction has been rolled back due to a previous
           exception during flush. To begin a new transaction with this Session,
           first issue Session.rollback().
           Original exception was: (IntegrityError)

A: I have the same need in my Flask application, I handle it like below and it works:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc

db = SQLAlchemy(Flask(__name__))

try:
     db.session.add(resource)
     return db.session.commit()
except exc.IntegrityError:
     db.session.rollback()

A: As soon as the IntegrityError is raised, regardless of whether or not you've caught the error, the session you were working in is invalidated.  As the second error message is instructing you, To begin a new transaction with this Session, first issue Session.rollback()., to continue using the session you'll need to issue a session.rollback()
I cannot say for sure, but I am guessing you or your web framework is attempting to continue using the session which raised the IntegrityError in some way.  I recommend you issue a session.rollback() either after you catch the exception or in your handle_elegantly function.
If you run the below you'll see what I mean:
from sqlalchemy import types
from sqlalchemy import exc
from sqlalchemy import create_engine
from sqlalchemy.schema import Column
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    name = Column(types.String, primary_key=True)

def handle_elegantly(name):
    session = DBSession()
    session.add(User(name=name))
    session.flush()
    print 'Exception elegantly handled!!\n'

def pretend_view(request):
    """Pretend view in a Pyramid application using pyramid_tm"""
    session = DBSession()
    user = User()
    print '\n-------Here we rollback before continuing -------'
    try:
        session.add(user)
        session.flush()
    except exc.IntegrityError:
        session.rollback()
        handle_elegantly('This will run fine')

    print '\n------- Here we do not, and this will error -------'
    try:
        session.add(user)
        session.flush()
    except exc.IntegrityError:
        handle_elegantly('Exception will be raised')

if __name__ == '__main__':
    engine = create_engine('sqlite://')
    global DBSession
    DBSession = scoped_session(
        sessionmaker(extension=ZopeTransactionExtension()))
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all()
    pretend_view("dummy request")

A: You have to add session.rollback() after you catch an error:
try:
    session.flush()
except IntegrityError:
    session.rollback()

A: The answer is the same as the answers above, I want just to add an extra piece of code if you want to display some dynamic error on except to return it as a JsonResponse or whatever.
Note: outputting this type of error is not good in terms of security.
from sqlalchemy import exc

try:
     db.session.add(resource)
     return db.session.commit()
except exc.IntegrityError as e:
     err_msg = str(e.orig).split(':')[-1].replace('\n', '').strip()
     print(err_mg)
     return err_mg

exc.IntegrityError has a key called orig containing this message:
duplicate key value violates unique constraint "ix_table_column"
DETAIL:  Key (column)=(some_data) already exists.

This message has the type of <class 'driver.errors.UniqueViolation'> and not str, so we should convert it to str then with some simple string manipulation we got only the exact error, which is in this case:
Key (column)=(some_data) already exists.

A: SQLALCHEMY_COMMIT_ON_TEARDOWN = False


text:
Q: Why scroll doesn't work correct? Link to jsfiddle -   https://jsfiddle.net/dn5t2mwm/3/
$('a.item_link').click(function(){
    var hash = this.hash, top = $(hash).offset().top;
    console.log(hash, top);
    $('html, body').animate({
        scrollTop: top
    }, 500);
    return false;
});

I want to make smooth scroll. But when i account coordinates of link with anchor it returns different results. It looks like it accounts coordinates from the start of viewport - not a start of document. It works on codepen, but doesn't work on local and jsfiddle. css is disabled. Maybe you know what is wrong with it?

A: Use this piece of code:
$('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});


text:
Q: Use a field other than the category field to set marker-width in CartoDB's Torque Category I have rabies data that contains a date, animal type and county.  The centroid of the county polygon was used to generate a geometric point, the date used for Torque's Time Column, and the animal type for Torque's Category column.  I would like to use the count of each type of animal for a given date county combination to set the marker-width using CartoCSS.
It seems that for Torque the value of a field is not accessible to CartoCSS as [field] although you can access the numeric value of your category using [value].  Is there a way to pass the value of another field to Torque either using sql to generate count(animal type) grouped by animal type, time and county or by having Torque directly calculate the number of category records?


text:
Q: If statement wont execute last line I'm a beginner in coding and theres something wrong with my elif statement and i cant figure out what
For some reason this code gets stuck in the or, it will never execute the '4' option. We're trying to use less repetitive code, but nothing too advanced because we just starting learning python.
# defines menu
menu = '1- Sum of integers\n2- Sum of squares\n3- sum of cubes\n4- Geometric series'

# asks user for menu choice
print(menu)

menuChoice = 0
while menuChoice >= 0:
menuChoice = int(input(
    'Please enter a choice from our menu. (enter a negative number to quit)\n'))
sum = 0
calcSum = 0
if menuChoice == 0:
    print(menu)
elif menuChoice == 1 or 2 or 3:
    n = int(input('Enter n: '))
    for i in range(n + 1):
        if menuChoice == 1:
            sum += i
            calcSum = n * (n + 1)/2
        elif menuChoice == 2:
            sum += i ** 2
            calcSum = n * (n + 1) * (2 * n + 1)/6
        elif menuChoice == 3:
            sum += i ** 3
            calcSum = (n + (n + 1) / 2) ** 2

elif menuChoice == 4:
    x = int(input("Please Enter the Common Ratio: "))
    n = int(input("Please Enter the Total Numbers in this Geometric Series:  "))
    for i in range(n + 1):
        sum += x ** i

A: menuChoice == 1 or 2 or 3 is parsed as (menuChoice == 1) or 2 or 3, and always evaulates to a truthy value because 2 (and 3) is truthy. Use menuChoice == 1 or menuChoice == 2 or menuChoice == 3 or menuChoice in (1, 2, 3) instead.

A: Change your if statment with this:
elif menuChoice == 1 or menuChoice == 2 or menuChoice == 3:

Yuor code didn't work because  in python or 2 or 3 condition translates as or True or True since the values (non-zero) are always considered 'truthful' in the conditions.
This code run:
# defines menu
menu = '1- Sum of integers\n2- Sum of squares\n3- sum of cubes\n4- Geometric series'

# asks user for menu choice
print(menu)

menuChoice = 0
while menuChoice >= 0:
    menuChoice = int(input('Please enter a choice from our menu. (enter a negative number to quit)\n'))
    sum = 0
    calcSum = 0
    if menuChoice == 0:
        print(menu)
    elif menuChoice == 1 or menuChoice == 2 or menuChoice == 3:
        n = int(input('Enter n: '))
        for i in range(n + 1):
            if menuChoice == 1:
                sum += i
                calcSum = n * (n + 1)/2
            elif menuChoice == 2:
                sum += i ** 2
                calcSum = n * (n + 1) * (2 * n + 1)/6
            elif menuChoice == 3:
                sum += i ** 3
                calcSum = (n + (n + 1) / 2) ** 2

    elif menuChoice == 4:
        x = int(input("Please Enter the Common Ratio: "))
        n = int(input("Please Enter the Total Numbers in this Geometric Series:  "))
        for i in range(n + 1):
            sum += x ** i


text:
Q: Struts 2 is soo irritating with the namespaces. Can someone help understand the issue with it?

I have been able to create an application with Struts 2 and tiles 2.1 and complete the login action so far. Now I need to be able to click on a button and perform an action. I have configured the action-method-namespace mapping as per the guides out there but every guide has the same example and same configuration. I am having a difficult time trying to understand and troubleshoot this one.
Please check my configuration below
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true"/>
    <constant name="struts.custom.i18n.resources" value="ApplicationResources"/>

    <constant name="struts.mapper.alwaysSelectFullNamespace" value="true" />

    <package name="logindefault" extends="struts-default">
        <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
        </result-types>
        <action name="login" method="execute" class="com.schenker.ocean.actions.LoginAction">
            <result name="success" type="tiles">baseLayout</result>
            <result name="input">/login.jsp</result>
            <result name="fail">/login.jsp</result>
        </action>

    </package>

    <package name="default" extends="logindefault" namespace="/">
        <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
        </result-types>
        <action name="login" method="execute" class="com.schenker.ocean.actions.LoginAction">
            <result name="success" type="tiles">baseLayout</result>
            <result name="input">/login.jsp</result>
            <result name="fail">/login.jsp</result>
        </action>
    </package>

    <package name="dashboard" extends="logindefault" namespace="dashboard">
        <result-types>
         <result-type name="tiles1" class="org.apache.struts2.views.tiles.TilesResult"/>
        </result-types>
        <action name="getDashboard" method="getDashboard" class="com.schenker.ocean.actions.Dashboard">
            <result name="success" type="tiles1">dash</result>
            <result name="input">/login.jsp</result>
            <result name="fail">/login.jsp</result>
        </action>
    </package>
</struts>

tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE tiles-definitions PUBLIC
   "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
   "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

   <definition name="baseLayout" template="/baseLayout.jsp">
      <put-attribute name="title"  value="Template"/>
      <put-attribute name="header" value="/header.jsp"/>
      <put-attribute name="leftmenu"   value="/leftmenu.jsp"/>
      <put-attribute name="body"   value=""/>
      <put-attribute name="footer"   value="/footer.jsp"/>
   </definition>

   <definition name="dash" extends="baseLayout">
      <put-attribute name="title"  value="dash"/>
      <put-attribute name="body"   value="/viewBody.jsp"/>
   </definition>

   <definition name="assign" extends="baseLayout">
      <put-attribute name="title"  value="Assign"/>
      <put-attribute name="body"   value="/assignBody.jsp"/>
   </definition>

</tiles-definitions>

left menu.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" HREF="css/styles.css">

    <s:form name="searchForm" action="dashboard/getDashboard" method="post">

            Search

             <s:textfield size="20" maxlength="20" name="stt" key="label.stt"></s:textfield>

            <s:textfield size="20" maxlength="20" name="hawb" key="label.hawb"></s:textfield>

            <s:textfield size="20" maxlength="20" name="chi" key="label.chi"></s:textfield>

            <s:textfield size="20" maxlength="20" name="invoice" key="label.invoice"></s:textfield>

            <s:textfield size="20" maxlength="20" name="shipment" key="label.shipment"></s:textfield>

            <s:submit key="label.search" method="getDashboard" ></s:submit>

    </s:form>

folder structure

I have been trying for the past few days so please help me out without telling me to go check google.. I keep getting this

no dashboard/getDashboard action configured in namespace /

Why?
I tried moving the getDashboard action declaration to 'logindefault' and 'default' packages.
It gives me different ways of saying the same thing.

A: You are doing several strange things, but your main problem is that you need to specify the namespace separately, then instead of
<s:form action="dashboard/getDashboard" method="post">

use
<s:form action="getDashboard" namespace="dashboard" method="post">

After that, you are using a login action in "" namespace and another one in "/" namespace, redefining exactly the same tiles result that you are inheriting because of extends="logindefault", starting action names with get, using alwaysSelectFullNamespace in a strange way, enabling DMI, that is discouraged, without actually needing to use it, etc.
Change also
<s:submit key="label.search" method="getDashboard" ></s:submit>

to
<s:submit key="label.search" />

Because you've already defined the getDashboard method as the one to call when calling the getDashboard action.
My 2 cents: If I were you I'd restart from scratch, without tiles, making a clean, full working small project with 3-4 pages to use as future reference. And please, remove those tutorial sites from the bookmarks...


text:
Q: CFDocument PDFs are huge (ColdFusion 8) I wanted to add a PDF generation button for articles. Everything is working well until I noticed that the file sizes are upwards of 4MB for a document with 200KB of JPG images and about 120KB of HTML. So, I tossed the CFDocument into the CFPDF tag which reduced it to 1.5MB. Better. Then I put it through Acrobat's web optimizer which took it down to 335KB. I cannot find an "optimizing" solution with either CFDocument or CFPDF. I was hoping for a quality setting or something. I should also note that CFDocument takes a while to process (relatively speaking). Since ColdFusion 9 added an optimize function, I'm guessing that I'm out of luck until this server is upgraded. True?
<cfdocument format="pdf"
            localurl=true
            name="loc.tempPDF">

    <cfoutput>#loc.articleContent#</cfoutput>

</cfdocument>

<cfpdf action = "write"
       destination = "#expandPath('\pdf\temp.pdf')#"
       source = "loc.tempPDF"
       overwrite = "yes"
       saveOption = "linear" />

A: That's correct, there is currently no way to optimize PDFs in ColdFusion 8 with the native cfdocument or cfpdf tags. If you absolutely have to make this happen without upgrading to CF9 (which has much improved PDF compression), then you could look at the iText library for generating PDFs via Java.

A: I built a Document Management System using CF 6.1 a few years ago. I used GhostScript to create, concatenate and optimize PDFs.
Here's a blog post showing how you can use GS to optimize a PDF's size.


text:
Q: Is there a way provided by nextjs 13 to protect routes? I have following pages /about, /user, /user/[id]. Since I cannot access req.page which gives us slug i.e. (/user/[id]), I couldn't apply logic to redirect requests made by unauthenticated users. So, my question is there any specific way that nextjs 13 provides to protect routes.
I tried the next-shield which is package to handle this problem. But that gives us flashy content.


text:
Q: How do I see that $\lim_{x \rightarrow -\infty} 5/4-x-\sqrt {(x-5/4)^2 -1} = 0$? How do I see that $$\lim_{x \rightarrow -\infty} 5/4-x-\sqrt {(x-5/4)^2 -1} = 0$$ ?
I see that the function is continuous, so I can take the limit under the square root, but this doesn't help me much here, because the limit is evaluated at infinity ?
Also, I've tried looking for an upper bound that goes towards $-1$ as $t$ goes towards $-\infty$.
Can someone help ?

A: You can't "take the limit under the square root", because this is in the form $\infty-\infty$, so some more work is needed.
I usually advice doing the substitution $t=-x$ so you have a limit at $\infty$ that's arithmetically easier, but in this case it's much better to use
$$
t=\frac{5}{4}-x
$$
so we get
$$
\lim_{t\to\infty}t-\sqrt{t^2-1}
$$
The standard path is to remove the square roots:
$$
\lim_{t\to\infty}t-\sqrt{t^2-1}=
\lim_{t\to\infty}\frac{(t-\sqrt{t^2-1})(t+\sqrt{t^2-1})}{t+\sqrt{t^2-1}}
$$
Develop the numerator and finish.

Why is it "arithmetically easier" to cope with limits at $\infty$ than at $-\infty$? If you have something like
$$
\lim_{x\to-\infty}\left(\dots+\sqrt{x^2(\cdots)}\;\right)
$$
the correct way to take out $x^2$ from the square root is
$$
\sqrt{x^2(\cdots)}=-x\sqrt{\cdots\mathstrut}
$$
because we can suppose to be working in an interval where $x<0$. This is often cause for mistakes. If we have made the transformation $t=-x$, we'd have no problem in taking out $t$ from the square root.

A: $$\lim_{x\to -\infty}5/4-x-\sqrt{(x-5/4)^2-1}$$$$=\lim_{x\to -\infty}\frac{(5/4-x-\sqrt{(x-5/4)^2-1})(5/4-x+\sqrt{(x-5/4)^2-1})}{5/4-x+\sqrt{(x-5/4)^2-1}}$$
$$=\lim_{x\to -\infty}\frac{(5/4-x)^2-(x-5/4)^2+1}{5/4-x+\sqrt{(x-5/4)^2-1}}$$
$$=\lim_{x\to -\infty}\frac{1}{5/4-x+\sqrt{(x-5/4)^2-1}}$$
$$=\lim_{\color{red}{t\to +\infty}}\frac{1}{5/4+t+\sqrt{(-t-5/4)^2-1}}\ \ \ (\text{set $t=-x$})$$
$$=\lim_{t\to +\infty}\frac{1/t}{5/(4t)+1+\sqrt{(1+5/(4t))^2-1/(t^2)}}=0.$$

A: If we have a limit where $x$ is going to negative infinity, we can make the substitution to let $x = -x$. Then it follows that as $\lim_{x\to -\infty} x = \lim_{x\to \infty} -x$
Therefore, our limit now becomes:
$$\lim_{x\to \infty} \frac{5}{4} + x - \sqrt{\left(-x - \frac{5}{4}\right)^2 - 1} = \lim_{x\to \infty} \frac{5}{4} + x - \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}$$
First, let's note that, for the constant in this limit, it's simiply going to equal $\frac{5}{4}$.
Now, we can focus on the variable terms:
$$\frac{5}{4} + \left[\lim_{x\to \infty} x - \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}\right]$$
For the limit, if we multiply the top and bottom by its conjugate:
$$\lim_{x\to \infty} \frac{\left(x - \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}\right)*\left(x + \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}\right)}{x + \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}} = \frac{x^2 - \left(\left(x + \frac{5}{4}\right)^2 - 1\right)}{x + \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}} = \frac{-\frac{5}{2}x - \frac{25}{16} + 1}{x + \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}}$$
Now, we can divide each of your terms by $x$, or the $\sqrt{x^2}$:
$$\lim_{x\to\infty}\frac{-\frac{5}{2}x - \frac{25}{16} + 1}{x + \sqrt{\left(x + \frac{5}{4}\right)^2 - 1}} =\frac{-\frac{5}{2} - \frac{25}{16x} + \frac{1}{x}}{1 + \sqrt{1 + \frac{5}{2x} + \frac{25}{16x^2} - \frac{1}{x^2}}} = -\frac{5}{4}$$
Therefore, our final answer is:
$$\frac{5}{4} - \frac{5}{4} = 0$$
In fact, we find that the limit is $0$, not $-1$.

A: You can collect the term $x-5/4$. So you get $$\lim_{x\to-\infty} -(x-5/4) \left( 1+\frac{\sqrt{(x-5/4)^2-1}}{x-5/4} \right)$$.
Putting the term $(x-5/4)$ under the square root we obtain $$\lim_{x\to-\infty} -(x-5/4) \left( 1-\sqrt{ \frac{ (x-5/4)^2-1}{(x-5/4)^2} }  \right)$$ where the minus before the square root appear because x goes to minus infinity. Then $$\lim_{x\to-\infty} -(x-5/4) \left( 1-\sqrt{ 1-\frac{ 1}{(x-5/4)^2} }  \right)$$.
Using the well known limit of $\lim_{x \to 0} \frac{(1+x)^a-1}{x}=a$ we get $$\lim_{x\to-\infty} (x-5/4) \left( \sqrt{ 1-\frac{ 1}{(x-5/4)^2} }-1  \right)=(x-5/4)\left( \frac{1}{2}\frac{1}{(x-5/4)^2}\right)$$ that goes to zero as $x \to -\infty$


text:
Q: Parent div not expanding with children, why not? My parent div is not expanding to hold the height of its children. I read that:
position: absolute;
float: any;
Both ruin this. The thing is that the div that does hold absolute elements does expand, but the div holding this, position: relative;, div is not expanding. I'd add a link for viewing but my page is not on a server yet (I am viewing it directly from HTML in Firefox.)
Clarification: It is the .banner_section div that is refusing to expand.
My HTML

    <?php include 'header.php'; ?>

            Show Menu
            <input type="checkbox" id="show-menu" role="button"></input>

HEM

HUDVÅRD

FOTVÅRD

MASSAGE

TEJPNING

VÅRA VARUMÄRKEN

OM OSS

KONTAKT

ONLINEBOKNING

TELEFONBOKNING

My CSS
.banner_section{
    background-color: #83AFB4;
    margin-bottom: 20px;
}
.banner{
    width: 100%;
    height: 269px;
    margin-bottom: 0;
    padding-bottom: 0;
}
.rslides_container {
    margin-bottom: 50px;
    position: relative;
    float: left;
    width: 100%;
    max-width: 960px;
}
.rslides {
    position: relative;
    list-style: none;
    overflow: hidden;
    width: 100%;
    padding: 0;
    margin: 0 auto;
}

.rslides li {
    -webkit-backface-visibility: hidden;
    position: absolute;
    display: none;
    width: 100%;
    left: 0;
    top: 0;
}

.rslides li:first-child {
    position: relative;
    display: block;
    float: left;
}

.rslides img {
    display: block;
    height: auto;
    float: left;
    width: 100%;
    border: 0;
}

.rslides1_nav {
    z-index: 3;
    position: absolute;
    top: 50%;
    left: 0px;
    opacity: 0.7;
    text-indent: -9999px;
    overflow: hidden;
    text-decoration: none;
    height: 61px;
    width: 38px;
    background: url("themes.gif") no-repeat scroll left top transparent;
    margin-top: -45px;
}
.prev{
    background: red;
}

.next{
    background: red;
}

A: OK check this out.
I added clearfix to the parent banner and I have a fiddle working here:
http://jsfiddle.net/lharby/x6qmtyqo/3/embedded/result/
This is the clearfix css:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */
.clear { overflow:hidden; clear:both; height:1px; margin:-1px 0px 0px 0px; font-size:1px; }
.clear-simple {clear:both; }

Then I added clearfix class to your banner_section, so:

Let me know if that works for you (it adds a margin below the images too, but you have that specified in your css).

A: To make the parent depending to the child div, you have to make the parent
postion:relative

and set the width and the height of the child at whatever you want, the parent will adjust to it.
Lets see the demo:
DEMO


text:
Q: What is the difference between these two types of training? Suppose that I want to detect if a picture contains a particular logo, for instance the following one.

Since template matching would be slow and fail those scaled or resized ones, I decided to train a classifier and I have two ideas:

*

*Gather many pictures that contain the logo and many others that don't, and directly train a binary classification model.

*After gathering the training data in the first step, I combine the logo and every image in the two types of images. For example, I combine(using this online tool) the logo with an image not containing the logo as follows:

and keep the labels.
I think they are two types of learning: In the first approach, the model pushes the embeddings/representations of the two kinds of pictures away in the space and hence if I try a different logo, the model would become dull; while in the second approach the model would learn to find the trick: If there exists a pattern somewhere in the picture which has the same shape/pattern as the left part of the picture(where the logo lies), the label should be one.
I wonder if the difference is transductive learning vs inductive learning? If not, what is it?
Any suggestions would be highly appreciated. Thanks in advance.


text:
Q: T-SQL (Access) remove all duplicates but one with highest ID I have problem with duplicates in my base but I can't use distinct select to other table becouse I have unique data in some colums. I want to keep last rating.
Example:
ID| ProductName | Code | Rating
------|------ | ------ | ------
1| Bag | 1122 | 5
2| Car| 1133 | 2
3| Bag | 1122 | 3
4| Car | 1133 | 1
5| Train| 1144 | 1

As result of query I want to get:
ID| ProductName | Code | Rating
------|------ | ------ | ------
3| Bag | 1122 | 3
4| Car | 1133 | 1
5| Train| 1144 | 1

A: One option uses a GROUP BY to identify the id values of the most recent duplicates for each Code/ProductName group:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT Code, MAX(ID) AS ID
    FROM yourTable
    GROUP BY Code
) t2
    ON t1.Code = t2.Code AND
       t1.ID   = t2.ID


text:
Q: how can i retrieve email from google api? I am using grails 3.2 and using following plugin:
compile 'org.grails.plugins:spring-security-rest:2.0.0.RC1'
 for spring security. I have successfully installed google login. But, I am not able to retrieve gmail id from the plugin.


text:
Q: URL used to deploy ipa with Enterprise Certificate I have an Apple Enterprise Certificate and want to deploy my app wirelessly to testers. Of course, I need to specify a URL of my ipa file. My question is, is any url OK?
Currently I put my ipa in the Amazon S3 server, and made a simple website with a link
<a href="itms-services://?action=download-manifest&url=itms-services://?action=download-manifest&url=https://s3.amazonaws.com/test/test.plist" id="text">

When you open my website on your iPhone, you can easily install my app by a tap.
However, my concern is, since the URL is public (you can download the plist file, open it with a text editor, and see the URL of the ipa file), and anyone who have the URL can download it, is there any potential danger?

A: From Apple's support center:

The iOS Developer Enterprise Program only allows you to distribute
  your apps to employees or members of your organization through Ad Hoc
  distribution

As far as I understand from enterprise license legal agreements, you must care about security by yourself. The link on ipa file is intended only for your employees and you mustn't make it public.

A: I think you should use a sort of redirection management of your url in relation to a session login parameters...
Anyhow I agree with @Alex Peda


text:
Q: OpenCV for OSX: OpenCL Concerns I am currently working on an OSX application that requires my team to use OpenCV, and we are thinking of utilizing the GPU in order to speed up some of our calculations. I am not familiar using the GPU when it comes to OpenCV, more so that we're working on an Apple/UNIX environment (I mostly used OpenCV in Windows/python back in my college freshman years). Will building OpenCV 3 with OpenCL be a safe bet? Does OpenCV even play nice with the GPU using OpenCL?
I've read from this blog that OpenCV doesn't fully support OpenCL in OSX, but that was written nearly three years ago, so I'm not sure if that is still applicable today. Also, I don't think CUDA is not an option since we're working on Apple machines. I apologize for the noobish question in advance.
Thank you.


text:
Q: @Query shortestPath return type in Spring Data Neo4j What's the return Type of the following query and how do I use it? I tried several things like Path, Iterable<Path>,  and others but I always hit some sort of exceptions. It seems to be a LinkedHashMap but are there any other handier object types that I can use?
@Query( "START u1=node:User(key= {0}), u2=node:User(key = {1}) " +
        "MATCH p = shortestPath(u1-[*]-u2) " +
        "RETURN p")
public ??? findShortestPath(String u1, String u2);

Am I missing any dependencies? This is the only one that I'm using:
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j-rest</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>

A: The return type is EndResult<EntityPath<S, E>, where S is the start node of the path, and E the end type.


text:
Q: Weird behavior of Bootstrap navbar-collapse with Animated.css Yesterday I implemented navbar-toggle collapsed like this one in the example. Everything works great except one thing. When I dynamically add the fadeInRight or slideInRight class from Animate.css to some alement in the page, the whole top menu width is resizing according to page size (when an element is sliding from right the page width is changing).
To be clear, here is an example of my code:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#topmenu">
                Toggle navigation

            </button>

ceník

podmínky

kontakt

All these classes are bootstrap classes.
Below is jQuery code which adds classes to visible element which should be animated.
// Plugin @RokoCB :: Return the visible amount of px
// of any element currently in viewport.
// stackoverflow.com/questions/24768795/
;(function($, win) {
    $.fn.inViewport = function(cb) {
       return this.each(function(i,el){
          function visPx(){
             var H = $(this).height(),
             r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
             return cb.call(el, Math.max(0, t>0? H-t : (b<H?b:H)));
          } visPx();
          $(win).on("resize scroll", visPx);
       });
   };
}(jQuery, window));

$("#references > div").inViewport(function(px){
    if(px) {
       var time = 0;
       $("#references > div").each(function() {
          var div = $(this);
          setTimeout(function(){ $(div).addClass("animated fadeInRight")}, time);
          time += 300;
       });
    }
});

And this is html which is animated.

Reference

Lorem ipsum

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sapien nunc, commodo et.

When I give width to header problem is solved. But I dont want fixed header width... Does somebody know how to fix it?


text:
Q: BigQuery: Symmetric difference (xor) between two sets BigQuery has UNION, INTERSECT, and EXCEPT [1], but not XOR.
SELECT * FROM [0, 1,2,3] XOR SELECT * FROM [2,3,4]
would return
0
1
4
As 0 and 1 are present in the first select but not second, and 4 is present in the second select, but not first.
I'd like to use it to find discrepancies between two tables, eg find customers that are present in one table, but not other and vice versa.
Any hints how to best do it?
[1] https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#set_operators

A: BigQuery does not need a XOR operator as it can be obtained from existing operators:
a first way to do so as @Genato points it out is to use JOIN like in this issue
Another way is to use set operators: A XOR B can be translated as (A AND NOT B) OR (B AND NOT A), so with your example you could write
(
SELECT * FROM UNNEST(ARRAY<int64>[0, 1, 2, 3]) AS number
EXCEPT DISTINCT SELECT * FROM UNNEST(ARRAY<int64>[2, 3, 4]) AS number)

UNION ALL

(
    SELECT * FROM UNNEST(ARRAY<int64>[2,3,4]) AS number
EXCEPT DISTINCT SELECT * FROM UNNEST(ARRAY<int64>[0, 1, 2, 3]) AS number);

which results in:

A: Few 'workarounds'
Option 1
with table1 as (
  select * from unnest([0, 1,2,3]) num
), table2 as (
  select * from unnest([2,3,4]) num
  )
select * from table1 where not num in (select num from table2)
union all
select * from table2 where not num in (select num from table1)

Option 2
with table1 as (
  select * from unnest([0,1,2,3]) num
), table2 as (
  select * from unnest([2,3,4]) num
)
select num from (
  select distinct num from table1 union all
  select distinct num from table2
)
group by num
having count(*) = 1

in both cases  - output is


text:
Q: Is there a way to skip a specific test case via the command line? I am using apache ant, and do not want to change my source tests, but I'd like the option to turn one off. I know that it is possible to only RUN tests you choose (-Dtestcase=whatever), but I'm not sure if you can exclude one.

A: You might use ant -DexcludedTest=SomeExcludedTest and have your batch test configured like this:
<batchtest ...>
    <!-- define the excludedTest property to an unexisting test name in case
         nothing is passed as a system property -->
    <property name="excludedTest" value="THIS_TEST_NAME_DOES_NOT_EXIST"/>
    <fileset dir="${src.tests}">
        <include name="**/*Test.java"/>
        <exclude name="**/${excludedTest}.java"/>
    </fileset>
</batchtest>


text:
Q: How to calculate $\int_0^\pi \frac{\cos^4(x)}{1+\sin^2(x)}dx$ using contour integrals How do I go about calculating $\int_0^\pi \frac{\cos^4(x)}{1+\sin^2(x)}dx$ using contour integrals?

A: Suppose we seek to evaluate
$$J = \int_0^{\pi} \frac{\cos^4 x}{1+\sin^2 x} dx
= \frac{1}{2} \int_0^{2\pi} \frac{\cos^4 x}{1+\sin^2 x} dx.$$
Put  $z   =  \exp(ix)$  so  that   $dz  =  i\exp(ix)   dx$  and  hence
$\frac{dz}{iz} = dx$ to obtain
$$\frac{1}{2} \int_{|z|=1}
\frac{(z+1/z)^4/2^4}{1+(z-1/z)^2/(2i)^2} \frac{dz}{iz}
\\ = -\frac{1}{8} \int_{|z|=1}
\frac{(z^2+1)^4}{-4z^2+(z^2-1)^2} \frac{dz}{iz^3}
\\ = \frac{i}{8} \int_{|z|=1}
\frac{(z^2+1)^4}{(z^2-1)^2-4z^2} \frac{z\; dz}{z^4}.$$
Now put  $w=z^2$ so that  $z\; dz =  \frac{1}{2} \; dw$ and  note that
this loops around  the origin twice so that we  must multiply a single
loop by two to get
$$2\times \frac{i}{8} \int_{|w|=1}
\frac{(w+1)^4}{(w-1)^2-4w} \frac{1}{2} \frac{dw}{w^2}
\\ = \frac{i}{8} \int_{|w|=1}
\frac{(w+1)^4}{w^2-6w+1} \frac{dw}{w^2}.$$
In  addition to the  double pole  at $w=0=\rho$  there are  two simple
poles here at
$$\rho_{0,1} = 3 \pm 2\sqrt{2}$$
and clearly  $\rho_1$ is the only  one inside the contour.
Converting to partial fractions we get
$$\frac{64}{w^2-6w+1} + 1 + \frac{10}{w} + \frac{1}{w^2}.$$
Hence the non-zero contribution comes from
$$\frac{64}{w^2-6w+1} + \frac{10}{w}.$$
The first term yields
$$\mathrm{Res}_{w=\rho_1}
\frac{64}{w^2-6w+1} =
\left. \frac{64}{2w-6} \right|_{w=\rho_1}
\\ = \frac{64}{-4\times\sqrt{2}}
= -\frac{16}{\sqrt{2}} = -8\sqrt{2}.$$
The second  term produces $10$  by inspection. Collecting
everything we have
$$2\pi i \times \frac{i}{8}
\times(10 - 8\sqrt{2})
= \frac{\pi}{4} (8\sqrt{2}-10)$$
or
$$\bbox[5px,border:2px solid #00A000]{
\frac{\pi}{2}(4\sqrt{2}-5).}$$

A: By symmetry,
$$ I = \int_{0}^{\pi}\frac{\cos(x)^4}{1+\sin(x)^2}\,dx = 2 \int_{0}^{\pi/2}\frac{\cos(x)^4}{1+\sin(x)^2}\,dx $$
and by substituting $x=\arctan(t)$ we get
$$ I = 2 \int_{0}^{+\infty}\frac{dt}{(1+t^2)^2 (1+2t^2)}=\int_{-\infty}^{+\infty}\frac{dt}{(1+t^2)^2(1+2t^2)}. $$
The integrand function is now a meromorphic function with double poles at $t=\pm i$, simple poles at $t=\pm\frac{i}{\sqrt{2}}$, bounded by $\frac{C}{|t|^2}$ as $|t|\to +\infty$. By the ML lemma and the residue theorem it follows that:
$$ I = 2\pi i\sum_{\xi\in\{i,i/\sqrt{2}\}}\!\!\!\text{Res}\left(\frac{1}{(1+t^2)^2(1+2t^2)},t=\xi\right)=2\pi i\left(\frac{5i}{4}-i\sqrt{2}\right)=\color{red}{\frac{\pi}{2}(4\sqrt{2}-5)}. $$


text:
Q: How to sync a dynamic ImportRange data with static data in one google spreadsheet? I have 3 spreadsheets where 1 is a master sheet (to which everything is imported and everything is exported from).
In the 1st spreadsheet a person fills in A:M which is imported to the Master spreadsheet, then the 2nd spreadsheet imports A:M range from the Master spreadsheet and the person in the 2nd spreadsheet adds additional data to N:P and Master spreadsheet also imports this to the correct row.
BUT the 2nd spreadsheet keeps desynchronizing because if the person in the 1st spreadsheet adds data then A:M data shifts down but the N:P data doesn't
Any way of keep the two synched?


text:
Q: python netCDF4 suddenly stopped working on Mac OS I have used python's netCDF4 package maybe 100 times on my Mac.  Today, I tried
>>> from netCDF4 import Dataset

as I have done countless times, and was told
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/netCDF4/__init__.py", line 3, in <module>
    from ._netCDF4 import *
ImportError: dlopen(/Library/Python/2.7/site-packages/netCDF4/_netCDF4.so, 2): Library not loaded: /opt/local/lib/libhdf5.100.dylib
  Referenced from: /Library/Python/2.7/site-packages/netCDF4/_netCDF4.so
  Reason: image not found

I suspect that this is related to an update I did through Mac Ports yesterday, but don't know for sure.  Anyone know the solution?
UPDATE: I don't have libhdf5.100.dylib in the directory where netCDF4 wants to find it, but I do have libhdf5.101.dylib.  Any way to convince netCDF4 to look for that instead?  Would setting up a link be a safe thing to do?
UPDATE AGAIN: Found an answer about an hour later if anyone is interested.  It is given below.

A: OK, after goofing around for about an hour, I hit on this:
Use pip to uninstall netCDF4, then turn right around and use pip to install it again.  Everything now works fine.
BTW, the initial uninstall is critical.  And, on my machine at any rate, I had to run everything under sudo.


text:
Q: Read Access Violation Code: 0xCDCDCDE1 and Code :0xCDCDCDE1 I'm doing a Shopping Mall project in Link List C++. In which I have to insert new Shop,Search Shop, Delete Shop, Count Shops and Display all. I written some of code.
I wrote the code but:
(1) it give error in input after when I input 2nd time and press input at last input i gives following Exception.
"Exception thrown: read access violation.
std::_String_alloc > >::_Mysize(...) returned 0xCDCDCDE1."
(2) When I display it give following Exception:
Exception thrown: read access violation.
temp was 0xCDCDCDCD.
Here is main.
int main()
{
ShoppingMallList* shopList=new ShoppingMallList();
string name="";
int shopNumber;
string brandShop;
int floor;
string shoptype;

do
{

    system("cls");
    cout << "**************WELCOME TO MALL**************\n1: Add Shop\n2: Search Shop\n3: Count Shops\n4:Display Shops\n5: Quit" << endl;
    int option;
    cin >> option;
    switch (option)
    {
        case 1:
        {
            input(name, shopNumber, brandShop, floor, shoptype);
            shopList->Insert(name, shopNumber, brandShop, floor, shoptype);
        }
        break;
        case 2:
        {
            string name1;
            cin.clear();
            cin.ignore();
            cout << "Enter Name of Shop to Search: ";
            getline(cin, name1);
            shopList->search(name1);
        }
        break;
        case 4:
        {
            shopList->Print();
        }
        break;
        case 5:
        {
            shopList->~ShoppingMallList();
            exit(0);
        }
        break;
        default:
            continue;
    }
    system("pause");

    shopList;
} while (true);

return 0;
}
void input(string& name, int& shopNumber, string& brandShop, int& floor,      string& shoptype)
{
char temp;
cin.clear();
cin.ignore();
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Shop Number: ";
cin >> shopNumber;
cin.clear();
cin.ignore();
cout << "Enter Brand(yes/no): ";
getline(cin, brandShop);
cout << "Enter Floor: ";
cin >> floor;
cin.clear();
cin.ignore();
cout << "Enter Shop Type: ";
getline(cin, shoptype);
}

Here is shoppingMall.h
class ShoppingMall
{
friend std::ostream& operator<<(std::ostream& cout, const ShoppingMall&   shop);
friend class ShoppingMallList;
public:
ShoppingMall(std::string& , int&, std::string&, int&, std::string&);

private:
std::string name;
int shopNumber;
std::string brandshop;
int floor;
std::string shopType;
ShoppingMall* link;

};

ShoppingMall::ShoppingMall(std::string& name , int& shopNumber, std::string&         brandShop, int& floor, std::string& shoptype) : name(name),    shopNumber(shopNumber), brandshop(brandShop), floor(floor), shopType(shoptype)
{

}

std::ostream& operator<<(std::ostream& cout, const ShoppingMall& shop)
{
cout << "Name: " << shop.name << std::endl << "Shop Number: " <<           shop.shopNumber << std::endl << "Brand Shop: " << shop.brandshop << std::endl <<    "Floor: " << shop.floor << std::endl << "Shop Type: " << shop.shopType <<    std::endl;
return cout;
}

And here is ShoppingMallList.h header file.
class ShoppingMallList
{
public:
ShoppingMallList();
void addToHead(std::string&, int&, std::string&, int&, std::string&);
void Insert(std::string&, int&, std::string&, int&, std::string&);
void Print();
int getsize();
void deleteShop(std::string&);
void search(std::string&);

private:
ShoppingMall* head;
int size;
};

ShoppingMallList::ShoppingMallList() : head(0), size(0)
{
}

void ShoppingMallList::addToHead(std::string& name, int& shopNumber,       std::string& brandShop, int& floor, std::string& shoptype)
{
ShoppingMall* temp = new         ShoppingMall(name,shopNumber,brandShop,floor,shoptype);
if (head==0)
{
    head = temp;
}
else
{
    temp->link = head;
    head = temp;
}
size++;
}

int ShoppingMallList::getsize()
{
return size;
}
void ShoppingMallList::Print()
{
 ShoppingMall* temp = head;

while ( temp != 0 )
{
    std::cout << "Name: " << temp->name << std::endl << "Shop Number: " <<     temp->shopNumber << std::endl << "Brand Shop: " << temp->brandshop << std::endl    << "Floor: " << temp->floor << std::endl << "Shop Type: " << temp->shopType <<    std::endl;
    temp = temp->link;
}
}
void ShoppingMallList::Insert(std::string& name, int& shopNumber,       std::string& brandShop, int& floor, std::string& shoptype)
{
ShoppingMall* newShop = new ShoppingMall(name, shopNumber, brandShop, floor,   shoptype);

//case-1 EmptyList

if ( head == 0 )
{
    head = newShop;
}
else
{
    ShoppingMall* temp = head;
    ShoppingMall* previous = 0;

    // Traversing link to find insert location
    while (temp!=0)
    {

        if ( temp->name >= newShop->name )
        {
            break;
        }
        else
        {
            previous = temp;
            temp = temp->link;
        }
    }
    //case-2 Adding To Head
    if ( temp == head )
    {
        newShop->link = head;
        head = newShop;
    }
    //case-3 Adding After Head
    else
    {
        newShop->link = temp;
        previous->link = newShop;
    }

 }
 size++;
 }
 void ShoppingMallList::deleteShop(std::string& name)
 {
  ShoppingMall* temp=head;
  ShoppingMall* previous = 0;

if (head == 0)
 {
    //Case-1 If There is no node
    std::cout << "Shop cannot be deleted becasue the there no Node " <<    std::endl;
 }
 //Traversing Node to find node to delete
 while (temp!=0)
 {
    if ( temp->name == name )
    {
        break;
    }
    else
    {
        previous = temp;
        temp = temp->link;
    }
 }

 //case-2 If Shop with name passed not found
 if ( temp == 0 )
 {
    std::cout << "Shop of name " << name << " not found!" << std::endl;
 }
 else
 {
    //case-3 Delete node from head Node
    if ( temp == head )
    {
        head = head->link;
    }
    //delete other than head shop
    else
    {
        previous->link = temp->link;
    }
    delete temp;
    size--;
 }
 }
 void ShoppingMallList::search(std::string& name)
 {
 ShoppingMall* tempShop = head;
 while ( tempShop != 0 )
 {
    if (tempShop->name == name)
    {
        std::cout << "Name: " << tempShop->name << std::endl << "Shop     Number: " << tempShop->shopNumber << std::endl << "Brand Shop: " << tempShop-  >brandshop << std::endl << "Floor: " << tempShop->floor << std::endl << "Shop    Type: " << tempShop->shopType << std::endl;
    }
    else
    {
        tempShop = tempShop->link;
    }
}

if ( tempShop == 0 )
{
    std::cout << "Shop of name " << name << " not found!" << std::endl;
}

}

A: link field of ShoppingMall class is not initialized in constructor and contains some random rubbish. All list iterations like:
while ( temp != 0 )
{
  // Code skipped for simplicity
  temp = temp->link;
}

could cause Access Violation because condition temp != 0 never met and skipped code access memory at random address.
To fix it:
ShoppingMall::ShoppingMall(const std::string& name, int shopNumber, std::string& brandShop, int floor, const std::string& shoptype)
  : link(nullptr), name(name), shopNumber(shopNumber), brandshop(brandShop), floor(floor), shopType(shoptype)
{
}


text:
Q: After rebooting server, service start without special chars I wrote a simple Java server. This service (java server) connects with a mySQL database. I am connecting to this service with a socket connection.
Everything works well when I start my service by command line.
service quiz start

I also added this service to autorun. I use this simple wrapper.
The problem occurs when service starts with autorun -- I don't have special characters. Every select from the database returns something like this "??" instead of "ąę".
When I restart the service everything is working well again.
service quiz stop

service quiz start


text:
Q: SQLite password is available in memory using ADO.Net I have a .net 4.0 app that connects to an encrypted SQLite database via the ADO driver.
Something I have noticed is that when connecting the connection string and thus database password is available to view in memory, meaning that users can in fact find out of the database password.
Has anybody out there had any experience with this? found a workaround or fix?
Thanks for your time.


text:
Q: How to define what will be inserted in share message? I have an app with blog records per each user. I have add share button to my app, to give ability to post interesting blog records to users time line or to send to other user. But in default it takes image and text for share as it wants and not always correctly. So I find out that it can be dirven by meta tags (using for example "image" property to set image for share dialog). That's work ok on main page (where I'd like to make ability share with whole application), but on pages of blog records I cann`t customize it. meta tag should be in , but all info (short text and image of blog post) I get later in body, so I can insert it. How can I manage with this? Or may be there is another way to share content with?

A: What blog engine are you using? If it is a wordpress - try this plugin http://wordpress.org/extend/plugins/facebook-share-new/ from offician facebook docs http://developers.facebook.com/docs/. Otherwise I'd suggest to find a facebook plugin for your blog engine using google and install it.


text:
Q: Unable to understand a line
I am unable to understand the conclusion lines in the attached solution image. Here u=sup S>r, it may occur, but book mentioned it as contradiction. Please elaborate the conclusion part only.

A: No, it may not occur. By definition, the supremum is the least upper bound. In (ii) it is shown that $r$ is an upper bound*, and in (i) it is shown that $r$ is less than $u,$ so $u$ is not the least upper bound.
*To check this, we need to show that $r$ is greater than any element of $S.$ For any $x \in S,$ we have $x^2 < 2$ by definition. So $r^2 > 2 > x^2,$ and thus by taking square roots, $|r| > \sqrt{2} > |x|.$ But $x$ is positive by definition of $S,$ and $r$ is positive as argued, so the absolute value bars are unnecessary, and we have $r > x.$


text:
Q: How can I check if a doubly-linked list is a palindrome without using extra space? Recently, I went for an interview and they asked me "to check if below doubly-linked list is a palindrome without using any extra storage, such as STL's linked list, stack, queue, tree, string, character arrays, etc.." I was unable to give a perfect solution though.
Below is an image of the doubly-linked list:

This is not a homework question, but merely a question to find any solutions to be shared.

A: The problem here is that you have natural iterators whose elements can be more than one character, but you want to do an operation over just the sequence of characters.  So I would define another iterator type that behaves the way we need, using boost::iterator_facade.  (Often for this sort of thing boost::iterator_adaptor is even more convenient, but in this case it wouldn't help.)
The diagram suggests a raw C-like struct and pointer setup, so I'll assume the custom doubly linked list is defined like this:
struct list_node {
    list_node* prev;
    list_node* next;
    const char* data;
};

class LinkedList {
public:
    list_node* head() const;
    list_node* tail() const;
    // ...
};

The custom iterator class needs to contain a list_node* pointer and a pointer to an element of the char array.
#include <boost/iterator_facade.hpp>
class ListCharIter :
    public boost::iterator_facade<
        ListCharIter,                      // Derived class for CRTP
        const char,                        // Element type
        std::bidirectional_iterator_tag >  // Iterator category
{
public:
    ListCharIter() : m_node(nullptr), m_ch(nullptr) {}

    // "Named constructors":
    static ListCharIter begin(const LinkedList& listobj);
    static ListCharIter end(const LinkedList& listobj);

private:
    list_node* m_node;
    const char* m_ch;
    ListCharIter(list_node* node, const char* where)
        : m_node(node), m_ch(where) {}

    // Methods iterator_facade will use:
    char dereference() const;
    bool equal(const ListCharIter& other) const;
    void increment();
    void decrement();
    // And allow boost to use them:
    friend class boost::iterator_core_access;
};

For a past-the-end iterator only, we'll allow m_ch to point at the last node's terminating '\0'.  In the special case of a list with no elements, we'll set both members null for the single iterator which is both beginning and end and cannot be dereferenced.
inline ListCharIter ListCharIter::begin(const LinkedList& listobj)
{
    list_node* node = listobj.head();
    const char* str = nullptr;
    if (node) {
        str = node->data;
    }
    return ListCharIter(node, str);
}

inline ListCharIter ListCharIter::end(const LinkedList& listobj)
{
    list_node* node = listobj.tail();
    const char* nul = nullptr;
    if (node) {
        nul = node->data;
        while (*nul != '\0') ++nul; // Find the '\0'.
    }
    return ListCharIter(node, nul);
}

dereference() and equal() are trivial:
inline char ListCharIter::dereference() const
{ return *m_ch; }

inline bool ListCharIter::equal(const ListCharIter& other) const
{ return this->m_node == other.m_node && this->m_ch == other.m_ch; }

And finally, to step forward or backward, the basic idea is to change only m_ch if that makes sense, or change m_node otherwise.
inline void ListCharIter::increment()
{
    ++m_ch;
    // If m_node->next is null, we're advancing
    // past the end of the entire list.
    while (*m_ch == '\0' && m_node->next) {
        m_node = m_node->next;
        m_ch = m_node->data; // Start of new node.
        // while loop repeats if m_node contains "".
    }
}

inline void ListCharIter::decrement()
{
    if (m_ch == m_node->data) {
        // Already at the start of this node.
        do {
            m_node = m_node->prev;
            m_ch = m_node->data; // Start of new node.
            // while loop repeats if m_node contains "".
        } while (*m_ch == '\0');

        // Find the char before the terminating nul.
        while (m_ch[1] != '\0') ++m_ch;
    } else {
        --m_ch;
    }
}

Now you can use that custom iterator in an ordinary palindrome algorithm (and many other algorithms).
template<typename BidirIter>
bool is_palindrome(BidirIter start, BidirIter stop)
{
    for (;;) {
        if (start == stop) return true;
        if (*start != *stop) return false;
        ++start;
        if (start == stop) return true;
        --stop;
    }
}

bool is_palindrome(const LinkedList& the_list)
{
    return is_palindrome(ListCharIter::begin(the_list),
                         ListCharIter::end(the_list));
}

A: Declare two iterators, start and end. Then loop through the list and decrement/increment them simultaneously, comparing at each step. NOTE: This algorithm assumes that you have properly overridden the operators, but it also works for any sort of list, not just numerical lists.
for(int i=0;i<list.size()/2;i++){
    if(*start!=*end) return false;
    start++;
    end--;
}
return true;

The key here is that you are using iterators instead of actually working with the list directly.

A: template<typename List>
bool isPalindrome(List const &list) {
   auto b = list.begin();
   auto e = list.end();
   while (b != e) {
     --e;
     if (b == e) // for lists with exactly 1 or an even number of elements
        break;
     if (*b != *e)
       return false;
     ++b;
   }
   return true;
}

We can't use > or >= because list iterators are not random access (in most imlementations) and so can only be compared equal/not-equal.  std::distance is an option, but for non-randomaccess iterators it just does a whole lot of incrementing, which is slow.  Instead, the check in the middle of the loop handles the greater-than case, so that the entire function can be written using only equality comparisons.

A: This is the code I use for palindrome testing. It takes two iterators and correctly handles empty ranges and odd/even length ranges.
template <typename BidIt>
bool is_palindrome(BidIt first, BidIt last)
{
    if (first == last) return false; // empty range
    for (;;) {
        if (first == --last) break;
        if (*first != *last) return false; // mismatch
        if (++first == last) break;
    }
    return true; // success
}

A: I'd like to add a C++11 solution (due to a range-based for loop and an auto specifier) which makes use of std::list, std::advance(), and std::equal(), resulting in quite short code:
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    // Fill a doubly-linked list with characters.
    string str = "racecar";
    list<char> l;
    for (char c : str)
        l.emplace_back(c);

    // Find the center of the list.
    auto it = l.begin();
    advance(it, l.size() / 2);

    // Compare the first half of the list to the second half.
    if (equal(l.begin(), it, l.rbegin()))
        cout << str.c_str() << " is a palindrome." << endl;
    else
        cout << str.c_str() << " is not a palindrome." << endl;

    return 0;
}

Output:

racecar is a palindrome.

Note 1: This solution might be less efficient than that of the other answers, because it has to step through half of the list to find its center first. However, IMHO, it looks less complicated.
Note 2: The function equal() compares the first half of the list to its second half in reverse order because of list::rbegin(). Increasing this iterator moves it towards the beginning of the list.
Note 3: If you want to apply the code for different kinds of containers, you can put it into a function template as shown in most of the other answers.
Code on Ideone


text:
Q: IF SYNTAX AND EXAMPLE in CRM ON DEMAND There are 3 picklists. If particular values are selected in 1st and 2nd picklist the 3rd picklist must be updated.
I have Written the following rule condition:
IIf(='BUILDING' AND ='RETAILS', 'BUIDLING', IIf(='BUILDING' AND ='RAILS','INFRA','INDUSTRY') )
This Condition gives me Invalid Expession Syntax.

A: A few things about CRMOD workflows:

*

*A workflow condition are the specified conditions that must be met in order for the workflow to activate, if this is left blank it will activate everytime the trigger event(see below) happens e.g. If a record is created or modified.

a) Workflows are object specific e.g. Contact
b) The Trigger event inconjunction with the workflow condition above specifies when the workflow activates.
Once you have decided on your trigger then you have the option to select actions, this is where you would add the fields you want to update and specify the values.
You may find that you need more than one workflow depending on your business requirements.
I suggest you read the online user guide and oracle support resources to better understand the process before creating any automation in a product.
As for your If statement here is the syntax you need to follow:
IIf
The IIf function in Expression Builder returns one of two parameters based on the evaluation of a conditional expression. IIf is an abbreviation for Immediate If.
Syntax
IIf(expr, result_if_true, result_if_false)
Alternate Syntax
IIf(expr, expr_if_true, expr_if_false)
Mixed Syntax
IIf(expr, result_if_true, expr_if_false)
IIf(expr, expr_if_true, result_if_false)
E.g.
IIf([<PrimaryBillToState>]='OK' OR [<PrimaryBillToState>]='TX', 'Central', IIf([<PrimaryBillToState>]='CA', 'West', 'East'))

Kind Regards
Simon


text:
Q: Why boost python built library without any export function? I built boost python (1.55) without any errors or warnings.
Here is list:
C:\Programming\boost>b2 toolset=msvc-11.0 link=static variant=release threading=multi runtime-link=static --with-python
link.jam: No such file or directory
Building the Boost C++ Libraries.

Component configuration:
    - atomic                   : not building
    - chrono                   : not building
    - context                  : not building
    - coroutine                : not building
    - date_time                : not building
    - exception                : not building
    - filesystem               : not building
    - graph                    : not building
    - graph_parallel           : not building
    - iostreams                : not building
    - locale                   : not building
    - log                      : not building
    - math                     : not building
    - mpi                      : not building
    - program_options          : not building
    - python                   : building
    - random                   : not building
    - regex                    : not building
    - serialization            : not building
    - signals                  : not building
    - system                   : not building
    - test                     : not building
    - thread                   : not building
    - timer                    : not building
    - wave                     : not building

...patience...
...patience...
...found 1654 targets...
...updating 30 targets...
compile-c-c++ bin.v2\libs\python\build\msvc-11.0\release\link-static\runtime-link-static\threading-multi\numeric.obj
numeric.cpp
..........................
compile-c-c++ bin.v2\libs\python\build\msvc-11.0\release\link-static\runtime-link-static\threading-multi\object\function_doc_signature.obj
function_doc_signature.cpp
msvc.archive bin.v2\libs\python\build\msvc-11.0\release\link-static\runtime-link-static\threading-multi\libboost_python-vc110-mt-s-1_55.lib
common.copy stage\lib\libboost_python-vc110-mt-s-1_55.lib
bin.v2\libs\python\build\msvc-11.0\release\link-static\runtime-link-static\threading-multi\libboost_python-vc110-mt-s-1_55.lib
Скопировано файлов:         1.
...updated 30 targets...

The Boost C++ Libraries were successfully built!
The following directory should be added to compiler include paths:
    C:/Programming/boost
The following directory should be added to linker library paths:
    C:\Programming\boost\stage\lib
C:\Programming\boost>

EDITED:
But if I add it to my project (References -> Linker -> Input -> Additional dependencies), I get linker errors, such as:
PyRunnable.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) class boost::python::api::object __cdecl boost::python::api::getitem(class boost::python::api::object const &,class boost::python::api::object const &)" (__imp_?getitem@api@python@boost@@YA?AVobject@123@ABV4123@0@Z)
PyRunnable.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) class boost::python::api::object __cdecl boost::python::api::getattr(class boost::python::api::object const &,char const *)" (__imp_?getattr@api@python@boost@@YA?AVobject@123@ABV4123@PBD@Z)
PyRunnable.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) protected: __thiscall boost::python::detail::str_base::str_base(void)" (__imp_??0str_base@detail@python@boost@@IAE@XZ)

If I use dumpbin /symbols , I even can find methods that are unresolved. So, they are inside, but VS2012 ignores them somehow.
Why?
In Additional dependencies field there is:
libboost_system-vc110-mt-1_55.lib
libboost_program_options-vc110-mt-1_55.lib
libboost_filesystem-vc110-mt-1_55.lib

And no problems with them. But if I add there libboost_python-vc120-mt-1_55.lib or not, I still get 15 linker errors.
What do I do wrong way?
Thank you in advance.

A: That's normal. The dumpbin /exports option is for showing functions exported from a PE file (e.g. a DLL), not for listing the functions in a COFF library.
To list the functions in a COFF library, use the /symbols option:
dumpbin /symbols libboost_python-vc110-mt-s-1_55.lib


text:
Q: When Press Tabbar But it's not going to it"s Rootviewcontroller When i press certain Tab it's not going to its rootviewcontroller,
When user changes a tab, for the selected tab I want to push it to its top level controller.
I have implement this method but not works,
-(void)tabBarController:(UITabBarController *) tabBarController didSelectViewController : (UIViewController *)viewController
{
   [viewController.navigationController popToRootViewControllerAnimated:NO];
}

What's wrong with this?
How can i do that?

A: Assuming the method gets called (if not you should set the UITabBarController delegate), you are probably receiving the UINavigationController (which is a subclass of UIViewController) as viewController, you can check by logging it:
-(void)tabBarController:(UITabBarController *) tabBarController didSelectViewController : (UIViewController *)viewController
{
   NSLog(@"didSelect %@", viewController);
   [viewController.navigationController popToRootViewControllerAnimated:NO];
}

if that is the case, viewController.navigationController will probably be nil, you should be doing:
-(void)tabBarController:(UITabBarController *) tabBarController didSelectViewController : (UIViewController *)viewController
{
    if ([viewController isKindOfClass:[UINavigationController class]])
        [(UINavigationController*)viewController popToRootViewControllerAnimated:NO];
}