text:
Q: Wierd behaviour while transfer of a file in pendrive HI I have Ubuntu 20.04. When I transfer any file from laptop to Sandisk 16 GB pendrive greater than 800 mb or around it the 600-700 MB is transfered in 5 seconds and after that file transfer speed is around 1MB/sec and takes 30-40 seconds even if the transfer is completed. Is this normal ?
Partitioning type :- Master Boot Record [ I know that GPT is better but I have to use this pendrive for a old T.V and it doesn't detect devices with GPT partotioning scheme. ]
Partition type :- W95 FAT32 (LBA) <-- I don't know whats the meaning of it.
Contents :- FAT (32-bit version)

A: This isn't "weird" at all, but normal under most conditions. The slow-down will be seen for all large copies, though the point of slow-down will be different on every machine as this is largely based on available memory resources. System buffers are used during the copy process and will eventually flush to the target. This makes it rather difficult to consistently predict at what point a file copy will decelerate.
There are generally two ways to get around this slow-down:

*

*Use a copy command that allows you to set your own buffers, such as cpio or tar.

*Install the nocache package and use nocache cp {source} {destination}
If you are regularly working with very large file copies, the second option would be the simplest.


text:
Q: Menubar App - Is this right? I'm trying to make an app, which, when the main window isn't visible, shows an icon in the menubar. However, I'm not sure about this code and whether it's ok. I get no errors and no warnings but after a few app switches back and forth between my app and another eg. Twitter or Safari I get

Program received signal:
  "EXC_BAD_ACCESS".

Here is my code:
- (void)applicationDidResignActive:(NSNotification*)aNotification
{
        statusItem = [[[NSStatusBar systemStatusBar]
                       statusItemWithLength:NSVariableStatusItemLength]
                      retain];
        [statusItem setHighlightMode:YES];
        [statusItem setEnabled:YES];

            //Set menubar item's tooltip
        [statusItem setToolTip:@"Nucleus"];
        [statusItem setMenu:theMenu];
            //Set the menubar item's title
        [statusItem setTitle:[NSString stringWithString:@"N"]];

}

- (void)applicationDidBecomeActive:(NSNotification*)aNotification
{
    [statusItem release];
}

A: If the app crashes when you're releasing the statusItem variable there's probability that assigned menu attribute gets over-released. I'm not sure about this since I don't know here theMenu variable is coming from.

A: I simply replaced [statusItem release]; with [[NSStatusBar systemStatusBar] removeStatusItem:statusItem]; and that worked a treat. I don't want to completely release it as I still need it incase the user switches apps later. Thanks to @Kevin Ballard for that! :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to call model while creating controller in laravel? I want to make 'use App\Models\Model-name' in any controller i create..is there a way to do this ?!
I searched for this and found something like use auto-load file but didn't get the idea.

A: Yes this is possible! As per the Laravel documentation, you can use the following command:
php artisan make:controller PhotoController --resource --model=Photo

A: To declare a controller with the model try:
php artisan make:controller YourModelController --model=Models/YourModel


text:
Q: Why isnt my rock papar scissors game working? I'm working on a rock paper scissor game to practice some fundamentals as I try to teach myself c++.
I had it working briefly, but I adjusted some of the cout content and now it is short circuiting some of the if statements. Any insights as to why this isn't working would be appreciated.
#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>

game function. Requests input for player. Assigns variables random and guess to ints and then to strings result and result_2. Lastly the while loop tracks the score.
void Play_rps() {
    int guess;
    int i = 0;
    int o = 0;
    std::string result;
    std::string result_2;
    std::cout << " Rock, Paper, Scissors. GO!! \n";
    while (i != 2 || o != 2) {

        int random = rand() % 4;
        std::cout << " 1.) Rock \n 2.) Paper \n 3.) Scissors \n";
        std::cin >> guess;

        switch (guess) {
        case 1:
            result = "rock";
            break;
        case 2:
            result = "paper";
            break;
        case 3:
            result = "scissors";
            break;

        }
        switch (random) {
        case 1:
            result_2 = "rock";
            break;
        case 2:
            result_2 = "paper";
            break;
        case 3:
            result_2 = "scissors";
            break;
        }

Nested if statements determine the out come of each round and increment the win counter.

        if (result == result_2) {

            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " TIE! \n" << std::endl;
        }
        else if (result == " rock" && result_2 == " paper") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " Paper Beats Rock!\n You Lose! \n" << std::endl;
            o++;
        }
        else if (result == " paper" && result_2 == " rock") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " Paper Beats Rock!\n You win! \n" << std::endl;
            i++;
        }
        else if (result == " scissors" && result_2 == " paper") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " scissors Beat Paper!\n You Win! \n" << std::endl;
            i++;

        }
        else if (result == " rock" && result_2 == " scissors") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " Rock Beats Scissors!\n You Win! \n" << std::endl;
            i++;
        }
        else if (result == " scissors" && result_2 == " rock") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " Rock Beat Scissors! \n You lose! \n" << std::endl;
            o++;
        }
        else if (result == " paper" && result_2 == " scissors") {
            std::cout << " you threw " << result << std::endl;
            std::cout << " your opponant threw " << result_2 << std::endl;
            std::cout << " scissors Beat Paper!\n You Lose! \n" << std::endl;
            o++;
        }

        if (i == 2) {
            std::cout << " YOU ARE VICTORIOUS \n";
        }
        else if (o == 2) {
            std::cout << " DEFEAT \n";
        }

    }
}

The main function is working properly as far as I can tell, but when I compile there is a warning about "t-time being an unsigned int, which may cause data to be lost" which is the only notification I get.
        int main()
         {
            srand(time(NULL));
            int choice;

            do {
                std::cout << "0.) Quit \n1.) Play Game \n";
                std::cin >> choice;

                switch (choice) {
                case 0:
                    std::cout << "Thanks for nothing! \n";
                    return 0;

                case 1:
                    Play_rps();
                    break;

                default:
                    std::cout << " That's not a valid choice. \n";
                }
            } while (choice != 0);
        }

A: Remove the white spaces in the == statements and you can factorize some of your cout calls
    //" paper" --> "paper",  " rock" --> "rock"

    std::cout << " you threw " << result << std::endl;
    std::cout << " your opponant threw " << result_2 << std::endl;

    if (result == result_2) {
        std::cout << " TIE! \n" << std::endl;
    }
    else if (result == "rock" && result_2 == "paper") {
        std::cout << " Paper Beats Rock!\n You Lose! \n" << std::endl;
        o++;
    }
    else if (result == "paper" && result_2 == "rock") {
        std::cout << " Paper Beats Rock!\n You win! \n" << std::endl;
        i++;
    }
    else if (result == "scissors" && result_2 == "paper") {
        std::cout << " scissors Beat Paper!\n You Win! \n" << std::endl;
        i++;

    }
    else if (result == "rock" && result_2 == "scissors") {
        std::cout << " Rock Beats Scissors!\n You Win! \n" << std::endl;
        i++;
    }
    else if (result == "scissors" && result_2 == "rock") {
        std::cout << " Rock Beat Scissors! \n You lose! \n" << std::endl;
        o++;
    }
    else if (result == "paper" && result_2 == "scissors") {
        std::cout << " scissors Beat Paper!\n You Lose! \n" << std::endl;
        o++;
    }


text:
Q: Browser cache while adding comments I have problem with cache. When I'm adding a comments they are still visible even when option that admin must to approve comments is checked. When I clear a cache, the comments disappear. And it's ok.
Any suggestion?
ps. or maby this is not problem with cache but with wordpress settings


text:
Q: ajax,I am getting same value when its has different value I am clicking on different value but console.log give me same value.
enter image description here
i also going html code which has different value attribute has different value but, its give me first value of attribute.
enter image description here
actually, there 2 options for ajax. here is what i have tired.

                        @foreach($categories as $category)
                        <option  class="categoryList" value="{{$category->id}}">{{$category->category}}</option>
                        @endforeach

                          <option value=""></option>

enter code here

A: The html code specified is all wrong. You either go with  anchor tag or <select><option></option> </select> select tag.
If you prefer anchor tag then you can get the click functionality, but in the html you will end up with a long list of anchors
If you choose the select tag, then you can invoke the on change event and get the selected value. You can use either of the following
on change function
change event handler using jquery


text:
Q: Mask fire scars across a collection of images and combine them into one singular image I am a GEE and JavaScript novice.
I am trying to calculate a specific fire index for a collection of sentinel 2 images so as to map burn scars throughout a one year period. I then want to apply a mask on all the images when this particular index exceeds a certain value. Finally I want to combine this collection of masked images into a single image with a mask on any pixel that satisfied the threshold range for the burn index within the specified date range. This is where I am at in terms of initialising the process.
var sentinel2series = ee.ImageCollection(sentinel2.filterDate('2019-01-01', '2020-01-01').filterBounds(geometry).select('B12', 'B11', 'B8'));
print(sentinel2series)

  // Function to calculate and add a MIRBI band
var addMIRBI = function(image) {
  var MIRBI = image.expression(
  '10*(SWIR2)-9.8*(SWIR1)+2', {
        'SWIR2' : image.select('B12'),
        'SWIR1' : image.select('B11')
         })
          .rename('MIRBI')
   return image.addBands(MIRBI);
  };

var serieswithBIndex = sentinel2series.map(addMIRBI)
print(serieswithBIndex)

I have tried various iterating functions on my images but haven't had much luck. The addition of the burn index band seems to work fine as when I view the collection each image has a new band titled 'MIRBI'. I just cannot get across the line with masking the images once they exceed a threshold for that value and then combining those masks into a singular image that is an aggregate of all the masks.
I have applied the process detailed below by Rodrigo Lustosa, and I have since tried to run the script there and it was displaying something like what I am looking for. However I know it's not quite right because there is a fire in particular that I am trying to capture and I know it's outline shape (ie. it's been groundtruthed and it is my way of QA) but it seemed to get obscured in the mask - probably by erroneous clouds I guessed.
I since applied a cloud mask to the ImageCollection after it had the MIRBI band appended to each image, and then did the same process as outlined below with using the Reducer to get the maximum MIRBI value for each pixel. However now the area where there should be a mask indicating fire (ie. where the groundtruthed fire is and I know there is a fire scar) there isn't a mask.
Is it possible that something with my cloud masking has interfered with my subsequent masking of the MIRBI threshold?
Here's my working script
Map.centerObject(geometry);

var sentinel2series = ee.ImageCollection(sentinel2.filterDate('2019-01-01', '2020-01-01').filterBounds(geometry).select('B12', 'B11', 'B8', 'B4', 'B3', 'B2', 'QA60'));
print(sentinel2series)

  // Function to calculate and add a MIRBI band
var addMIRBI = function(image) {
  var MIRBI = image.expression(
  '(10*SWIR2)-(9.8*SWIR1)+2', {
        'SWIR2' : image.select('B12'),
        'SWIR1' : image.select('B11')
         })
          .rename('MIRBI')
   return image.addBands(MIRBI);
  };

var serieswithMIRBI = sentinel2series.map(addMIRBI)
print(serieswithMIRBI)

function maskS2sr(image) {
 var cloudShadowBitMask = (2<<10);
 var cloudsBitMask = (2<<11);
 // Get the pixel QA band.
 var qa = image.select('QA60');
 // Both flags should be set to zero, indicating clear conditions.
 var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
 .and(qa.bitwiseAnd(cloudsBitMask).eq(0));
 return image.updateMask(mask);
}

// mask clouds and cirrus
var seriesNoClouds = serieswithMIRBI.map(maskS2sr);

var certainValue = -5000;
var othervalue = 0;
// get max value for each pixel
var final_image = seriesNoClouds.select('MIRBI')
  .reduce(ee.Reducer.max());
// mask every pixel which was greater than certainValue in any image
var final_image_masked = final_image
  .updateMask(final_image.gt(certainValue).and(final_image.lt(othervalue)));
// view example on the map
Map.addLayer(final_image_masked,{},'max MIRBI masked');
print(final_image_masked)

I am reasonably confident in my threshold values, at least for the ROI that I am looking where I have validated them with a fire scar that I know is there in that image series.

A: I'm answering based on what I understood of your question, but maybe you also want to make a cloud mask and/or to reescale the values (cose the data don't come in the right scale). I didn't make these changes, so the index might appear weird, with strange values.
Here is the code you provided (I just made some changes so it's reproducible, I picked a case over Brazil and I assumed you used the Image Collection below).
var sentinel2 = ee.ImageCollection("COPERNICUS/S2_SR");
var geometry = ee.Geometry.Point([-57.23006235092618, -13.960284001225315]);
Map.centerObject(geometry,9); //change map position to be over geometry

var sentinel2series = sentinel2
  .filterDate('2019-01-01', '2020-01-01')
  .filterBounds(geometry)
  .select('B12', 'B11', 'B8');
print(sentinel2series);

  // Function to calculate and add a MIRBI band
var addMIRBI = function(image) {
  var MIRBI = image.expression(
  '10*(SWIR2)-9.8*(SWIR1)+2', {
        'SWIR2' : image.select('B12'),
        'SWIR1' : image.select('B11')
         })
          .rename('MIRBI');
   return image.addBands(MIRBI);
  };

var serieswithBIndex = sentinel2series.map(addMIRBI);
print(serieswithBIndex);

I understood that the first thing you wanted was to mask (in other words, to remove) pixels that are greater than a certain value. I chose a certain value so the mask could be seen in the map. I made a function that pick up the index of an image and make another image with true or false values, as described in the code. Then it is used as a mask. Here it is.
// mask, i.e. remove, pixels with index greater than certainValue
var certainValue = -7853;
var makeMask = function(image){
  // make an image with true or false values
  // true for MIRBI less than or equal (lte) a certainValue
  // false otherwise
  var mask = image.select('MIRBI').lte(certainValue);
  // remove false values, i.e, remove MIRBI greater than certainValue
  return image.updateMask(mask);
};
var serieswithBIndex_masked = serieswithBIndex.map(makeMask);

// view example on the map
Map.addLayer(serieswithBIndex.first().select('MIRBI'),{min:-12000,max:1000},'MIRBI unmasked');
Map.addLayer(serieswithBIndex_masked.first().select('MIRBI'),{min:-12000,max:1000},'MIRBI masked');

The second thing I understood that you want is to make an image with all the masked pixels from the images above also masked in this new image. For this, you don't need to use the serieswithBIndex_masked variable made above. You can first pick up the max value over each pixel then see if any pixels got greater than your certain value. Again I chose another certain value so the mask could be seen on the map.
certainValue = 5000;
// get max value for each pixel
var final_image = serieswithBIndex.select('MIRBI')
  .reduce(ee.Reducer.max());
// mask every pixel wich was greater than certainValue in any image
var final_image_masked = final_image
  .updateMask(final_image.lte(certainValue));
// view example on the map
Map.addLayer(final_image,{min:0,max:10000},'max MIRBI unmasked');
Map.addLayer(final_image_masked,{min:0,max:10000},'max MIRBI masked');

Hope this can answer you or at least some of your questions.


text:
Q: Capturar Coordenadas Neste script Api Maps Neste scrupt a baixo eu insiro a origem e o destino ele me retorna o km o tempo e dados do endereço entre eles.
mais minha pergunta é como fazer que ele me retorne a latitude e longitude
<script type="text/javascript">
  function CalculaDistancia() {
    $('#litResultado').html('Aguarde...');
    // Instancia o DistanceMatrixService.
    var service = new google.maps.DistanceMatrixService();

    // Executa o DistanceMatrixService.
    service.getDistanceMatrix({
        origins: [$("#txtOrigem").val()], // Origem
        destinations: [$("#txtDestino").val()], // Destino
        travelMode: google.maps.TravelMode.DRIVING, // Modo (DRIVING | WALKING | BICYCLING)
        unitSystem: google.maps.UnitSystem.METRIC // Sistema de medida (METRIC | IMPERIAL)
    }, callback); // Vai chamar o callback
  }

  // Tratar o retorno do DistanceMatrixService
  function callback(response, status) {
    // Verificar o status.
    if (status != google.maps.DistanceMatrixStatus.OK) { // Se o status não for "OK".
        $("#litResultado").html(status);
    } else { // Se o status for "OK".
        $("#litResultado").html(" "); // Remove o "aguarde".

        // Popula os campos.
        $("#txtOrigemResultado").val(response.originAddresses);
        $("#txtDestinoResultado").val(response.destinationAddresses);
        $("#txtDistancia").val(response.rows[0].elements[0].distance.text); // se text Km se value em Metros

        /////////////////////////////////////////////////////////////////////////////////////////////////
        var tempo = response.rows[0].elements[0].duration.text;
        tempo = tempo.replace("day", "dia").replace("hour", "hora").replace("min", "min");
        $("#txtTempo").val(tempo);
        /////////////////////////////////////////////////////////////////////////////////////////////////

        var dist = (response.rows[0].elements[0].distance.value); //pego a distancia em metros
        var km = Math.round(dist / 1000); //converto para Km e arredondo

        }}


text:
Q: what is the concept behind java iterator? I am doing a research on java iterator interface and cannot understand why it is designed like that.
Why java iterator use hasNext and next instead merge them into one method?
this a typical usage of java iterator
Iterator iter = //iterator from a list
while(iter.hasNext()){
    Object obj = iter.next();
    // do something to obj
}

why not
Iterator iter = //iterator from a list
Object obj = null;
try {
    while(true){
        obj = iter.next();
        // do something to obj
    }
} catch (NoSuchElementException e) {}

It is clear this approach looks ugly but what happen if next return null for when reach to end instead throw an exception? than code can be simplify to
Iterator iter = //iterator from a list
Object obj = null;
while((obj = iter.next()) != null){
    // do something to obj
}

this is how NSEnumerator in Objective-C works
NSEnumerator *enumerator = // from an array
while (id obj = [enumerator nextObject]) {
    // do something to obj
}

This increase the overhead of implement custom iterator.
This also make java iterator not thread-safe. For example an ArrayList have one element in it. Two threads both ask for a same iterator for that list hasNext at same time. Than both threads will see true and they will invoke next on that iterator. Because there is only one element and iterator has been asked twice which definitely will lead to an exception or error state.
I know there are thread-safe iterator but I am not sure hot it implement but I think lots blocking are happening which make it inefficient.
I think problem is that check and update are not happen atomically and I cannot understand why java designed iterator interface like that.

Update
I see that null can be a value so my approach is invalid. But is any possible workaround to the problems I mentioned above?

A: Your proposition would make it impossible to have null values in collections, since it uses null as a "poison pill" to detect the end of the iteration.
In the very very rare cases two threads share an iterator, you just need to wrap it inside some custom class and synchronize the access to the iterator, to make the check-then-act operation atomic. This is needed anyway since, even if the iterator just had one method, the backing collection (ArrayList in your example) is not thread-safe.

A: Your first suggestion is poor design because it relies on throwing and catching an exception for a condition that is known to eventually happen. Exceptions are rather expensive, and are meant only for "exceptional" situations which should not normally occur.
Your second suggestion doesn't take into account that Iterables can have null elements.
As for the thread safety bit, yes standard Iterators tend not to be thread safe and a custom implementation with added overhead would be necessary. This is true for most Java structures. As JB Nizet notes, it's more a matter of the Iterable structure being thread-safe before its Iterator can be.

A: For improved source code clarity, use (example with a collection of Strings)
Iterable<String> values = ... // typically a Collection (List, Set...)

for (String value : values) {
    // do something with the value
}

I concur with previous replies about null-bounded collections, loop control with exceptions (which is atrocious form) and thread safety.
Of your suggestions, null-bounding the collection is the least unwise, especially if you have a "no nulls" policy in your code. However it's very unidiomatic Java (edit: and breaks the contract of the Iterator interface), so liable to confuse future maintainers of the code (edit: and possibly cause subtle and/or unexpected bugs).


text:
Q: Jquery Parsing Raw dump XMl node containing html - YQL I am using YQL and the results are being returned in XML, I have not opted for Json, this Time since I need to emit the exact html under the Results tag of YQL.
So i give a call to $.Ajax and get the xml and find the "results" node in the xml.
when i do an alert or appending to a div or a body of html, somehow it seems the whole of Div's and Table's and Td's and Tr's are getting ripped before rendering.
I did an alert still didn't see the full raw html.
 $("#result").html("Loading...");
            $.ajax({
                type: "GET",
                url: yql,
                dataType: "xml",
                success: function (xml) {
                    info = $(xml).find('results');
                    alert(info.text());
                    $("body").html(info.text());
                }

What am i missing over here.
CDATA for covering html inside xml is not an option over here, just trying to render what is being served from YQL.
Thanks

A: I just ran into this problem, and dug up a couple of solutions.  The first and easiest would be to do this:
$("#result").html("Loading...");
        $.ajax({
            type: "GET",
            url: yql,
            dataType: "html",
            success: function (xml) {
                info = $(xml).find('results').html();
                alert(info);
                $("body").html(info);
            }

You can find that here (check in the response to the answer): How to use jquery get content with tags in xml
The second solution that worked for me was best explained here: Getting HTML from XML with JavaScript/jQuery


text:
Q: JavaScript error using bootstrap-table I'm trying to use bootstrap-table with MVC. I have the following files in scripts and content:
bootstrap-table.js
bootstrap-table.min.js
bootstrap-table-locale-all.js
bootstrap-table-locale-all.min.js

bootstrap-table.css
bootstrap-table.min.css

I'm then using the following in the bundleconfig.cs file:
        bundles.Add(new ScriptBundle("~/bundles/bootstraptable").Include(
                  "~/Scripts/bootstrap-table*"));

        bundles.Add(new StyleBundle("~/Content/bootstraptable").Include(
                  "~/Content/bootstrap-table*"));

and these in the "_Layout.cshtml" file:
    @Styles.Render("~/Content/bootstraptable")
    @Scripts.Render("~/bundles/bootstraptable")

I also have jQuery and Bootstrap included (and working), so I don't think it's a dependency issue.
When I run the project (before I even try doing anything with a table), I get:
Unable to get property 'locales' of undefined or null reference

There's no NuGet package for this, so I had to add the files manually, so perhaps I missed something. But according to the website (http://bootstrap-table.wenzhixin.net.cn/getting-started/), it would seem I have what I need.
Anyone had this issue or have any idea what I'm doing wrong?
Thanks.

A: So apparently the list of the files in the bundle is important for this. When I bundled it with the wildcard, it didn't work. When I switched it to
        bundles.Add(new ScriptBundle("~/bundles/bootstraptable").Include(
                  "~/Scripts/libs/bootstrap-table.js",
                  "~/Scripts/libs/bootstrap-table-en-US.js"));

explicitly putting the 2 necessary files in the bundle (I replaced the "all" locale with just the one I need), then it worked.


text:
Q: AngularJS: Login/Sign Up & Multiple Updates @ the same time I've quick questions below related to angularjs.
1- How to achieve login/ sign up features in AngularJs like we have in facebook or different applications??
2-  I created a single page app using Angular where user can enter data using form and as soon as user enters submit button; the new data becomes visible on the same page in descending order, now my question is how can i handle synchronous updates  meaning if multiple users are using the same app at the same time  and if anybody inserts something using the form than does angular provides a way that other users will get updated data at the same time, I am confused with this functionality. Please help

A: 1) You will need to use a form of some type to capture the information and either store it locally on the front-end, or if you want to persist the information, then create a back-end server to store this information.
2)  If you are talking about two users using the login form at the same time, there is no synchronous issue, because each form is rendered in the user's browser, and is therefore independent and one user's login form will not interact at all with another user's login form. If you want a page that shows who is logged in and who is not, then you will want to use websockets to allow 2 way communication between the front-end and the back-end in real time.


text:
Q: Hibernate: on delete cascade action for join table I have a many-to-many relation between two entities 'menu_groups' and 'pages' as follows
    public class MenuGroup {
        @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
        @JoinTable(name = "menu_group_pages",schema="live",
                  joinColumns=@JoinColumn(name="menu_groups_id"),
                  inverseJoinColumns=@JoinColumn(name="pages_id"))
        private Set<Page> pages = new HashSet<Page>();
    }

    public class Page {
       @ManyToMany(fetch = FetchType.EAGER, mappedBy="pages",
                   cascade={CascadeType.MERGE})

       private Set<MenuGroup> menuGroups = new HashSet<MenuGroup>();
    }

As you could see there is a join table which has two fk: menu_groups_id and pages_id. Now I want to add on delete cascade action for fk 'pages_id' in this join table. For a normal table, the statement is something like
    @OnDelete(action=OnDeleteAction.CASCADE)

How could I do this for a join table? Thanks

A: You will have to manually set the cascade options in the database and then just call remove on a managed Page object to remove it from the link table.
The OnDelete annotation should have generated the cascade options in the DB but it does not seem to work for ManyToMany (HHH-4404)
On the other hand, if you would like to avoid making any schema changes, then you would just have to remove the association between the MenuGroup and Page. In your PageDAO (or whatever abstraction you use) you could have a remove method that removes the associations:
public void remove(Page page) {
    for(MenuGroup menuGroup : page.getMenuGroups()){
        menuGroup.getPages().remove(page);
    }
    session.remove(page);
}

A: I believe you need to just set the CascadeType in your ManyToMany annotations to include CascadeType.Remove as well. You might be able to do CascadeType.All if it fits in with your data model. Either of these should cascade the deletes to both the Page\ManuGroup table as well as the join tables.


text:
Q: Adapting Bayesian logistic regression script to my data I'm looking to run a hierarchical logistic regression in a Bayesian framework, but am having trouble adapting codes for my data. I have the great book "Doing Bayesian Data Analysis", but I'm not sure how to modify the script the author provided (will paste below) to rerun the analysis on my thesis data. Specifically, I have the following questions:

*

*How do I add more terms to this model? I had 5 predictors in my thesis, and this model only has 2

*How do I make it hierarchical/include multiple steps or blocks?

*How do I add interaction terms among my predictors?

*I believe this script is set up for metric predictors (the book's example used height and weight data); If I am running a mixture of metric and nominal independent variables, how do I need to adapt it?

any help on any of these questions would be wonderful.
# Jags-Ydich-XmetMulti-Mlogistic.R
# Accompanies the book:
#   Kruschke, J. K. (2015). Doing Bayesian Data Analysis, Second Edition:
#   A Tutorial with R, JAGS, and Stan. Academic Press / Elsevier.

source("DBDA2E-utilities.R")

#===============================================================================

genMCMC = function( data , xName="x" , yName="y" ,
                    numSavedSteps=10000 , thinSteps=1 , saveName=NULL ,
                    runjagsMethod=runjagsMethodDefault ,
                    nChains=nChainsDefault ) {
  require(runjags)
  #-----------------------------------------------------------------------------
  # THE DATA.
  y = data[,yName]
  x = as.matrix(data[,xName],ncol=length(xName))
  # Do some checking that data make sense:
  if ( any( !is.finite(y) ) ) { stop("All y values must be finite.") }
  if ( any( !is.finite(x) ) ) { stop("All x values must be finite.") }
  cat("\nCORRELATION MATRIX OF PREDICTORS:\n ")
  show( round(cor(x),3) )
  cat("\n")
  flush.console()
  # Specify the data in a list, for later shipment to JAGS:
  dataList = list(
    x = x ,
    y = y ,
    Nx = dim(x)[2] ,
    Ntotal = dim(x)[1]
  )
  #-----------------------------------------------------------------------------
  # THE MODEL.
  modelString = "
  # Standardize the data:
  data {
    for ( j in 1:Nx ) {
      xm[j]  <- mean(x[,j])
      xsd[j] <-   sd(x[,j])
      for ( i in 1:Ntotal ) {
        zx[i,j] <- ( x[i,j] - xm[j] ) / xsd[j]
      }
    }
  }
  # Specify the model for standardized data:
  model {
    for ( i in 1:Ntotal ) {
      # In JAGS, ilogit is logistic:
      y[i] ~ dbern( ilogit( zbeta0 + sum( zbeta[1:Nx] * zx[i,1:Nx] ) ) )
    }
    # Priors vague on standardized scale:
    zbeta0 ~ dnorm( 0 , 1/2^2 )
    for ( j in 1:Nx ) {
      zbeta[j] ~ dnorm( 0 , 1/2^2 )
    }
    # Transform to original scale:
    beta[1:Nx] <- zbeta[1:Nx] / xsd[1:Nx]
    beta0 <- zbeta0 - sum( zbeta[1:Nx] * xm[1:Nx] / xsd[1:Nx] )
  }
  " # close quote for modelString
  # Write out modelString to a text file
  writeLines( modelString , con="TEMPmodel.txt" )

  #-----------------------------------------------------------------------------
  # INTIALIZE THE CHAINS.
  # Let JAGS do it...

  #-----------------------------------------------------------------------------
  # RUN THE CHAINS
  parameters = c( "beta0" ,  "beta" ,
                  "zbeta0" , "zbeta" )
  adaptSteps = 500  # Number of steps to "tune" the samplers
  burnInSteps = 1000
  runJagsOut <- run.jags( method=runjagsMethod ,
                          model="TEMPmodel.txt" ,
                          monitor=parameters ,
                          data=dataList ,
                          #inits=initsList ,
                          n.chains=nChains ,
                          adapt=adaptSteps ,
                          burnin=burnInSteps ,
                          sample=ceiling(numSavedSteps/nChains) ,
                          thin=thinSteps ,
                          summarise=FALSE ,
                          plots=FALSE )
  codaSamples = as.mcmc.list( runJagsOut )
  # resulting codaSamples object has these indices:
  #   codaSamples[[ chainIdx ]][ stepIdx , paramIdx ]
  if ( !is.null(saveName) ) {
    save( codaSamples , file=paste(saveName,"Mcmc.Rdata",sep="") )
  }
  return( codaSamples )
} # end function

#===============================================================================

smryMCMC = function(  codaSamples ,
                      saveName=NULL ) {
  summaryInfo = NULL
  mcmcMat = as.matrix(codaSamples)
  paramName = colnames(mcmcMat)
  for ( pName in paramName ) {
    summaryInfo = rbind( summaryInfo , summarizePost( mcmcMat[,pName] ) )
  }
  rownames(summaryInfo) = paramName
  if ( !is.null(saveName) ) {
    write.csv( summaryInfo , file=paste(saveName,"SummaryInfo.csv",sep="") )
  }
  return( summaryInfo )
}

#===============================================================================

plotMCMC = function( codaSamples , data , xName="x" , yName="y" ,
                     showCurve=FALSE ,  pairsPlot=FALSE ,
                     saveName=NULL , saveType="jpg" ) {
  # showCurve is TRUE or FALSE and indicates whether the posterior should
  #   be displayed as a histogram (by default) or by an approximate curve.
  # pairsPlot is TRUE or FALSE and indicates whether scatterplots of pairs
  #   of parameters should be displayed.
  #-----------------------------------------------------------------------------
  y = data[,yName]
  x = as.matrix(data[,xName])
  mcmcMat = as.matrix(codaSamples,chains=TRUE)
  chainLength = NROW( mcmcMat )
  zbeta0 = mcmcMat[,"zbeta0"]
  zbeta  = mcmcMat[,grep("^zbeta$|^zbeta\\[",colnames(mcmcMat))]
  if ( ncol(x)==1 ) { zbeta = matrix( zbeta , ncol=1 ) }
  beta0 = mcmcMat[,"beta0"]
  beta  = mcmcMat[,grep("^beta$|^beta\\[",colnames(mcmcMat))]
  if ( ncol(x)==1 ) { beta = matrix( beta , ncol=1 ) }
  #-----------------------------------------------------------------------------
  if ( pairsPlot ) {
    # Plot the parameters pairwise, to see correlations:
    openGraph()
    nPtToPlot = 1000
    plotIdx = floor(seq(1,chainLength,by=chainLength/nPtToPlot))
    panel.cor = function(x, y, digits=2, prefix="", cex.cor, ...) {
      usr = par("usr"); on.exit(par(usr))
      par(usr = c(0, 1, 0, 1))
      r = (cor(x, y))
      txt = format(c(r, 0.123456789), digits=digits)[1]
      txt = paste(prefix, txt, sep="")
      if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
      text(0.5, 0.5, txt, cex=1.5 ) # was cex=cex.cor*r
    }
    pairs( cbind( beta0 , beta )[plotIdx,] ,
           labels=c( "beta[0]" ,
                     paste0("beta[",1:ncol(beta),"]\n",xName) ) ,
           lower.panel=panel.cor , col="skyblue" )
    if ( !is.null(saveName) ) {
      saveGraph( file=paste(saveName,"PostPairs",sep=""), type=saveType)
    }
  }
  #-----------------------------------------------------------------------------
  # Data with posterior predictive:
  # If only 1 predictor:
  if ( ncol(x)==1 ) {
    openGraph(width=7,height=6)
    par( mar=c(3.5,3.5,2,1) , mgp=c(2.0,0.7,0) )
    plot( x[,1] , y , xlab=xName[1] , ylab=yName ,
          cex=2.0 , cex.lab=1.5 , col="black" , main="Data with Post. Pred." )
    abline(h=0.5,lty="dotted")
    cVec = floor(seq(1,chainLength,length=30))
    xWid=max(x)-min(x)
    xComb = seq(min(x)-0.1*xWid,max(x)+0.1*xWid,length=201)
    for ( cIdx in cVec ) {
      lines( xComb , 1/(1+exp(-(beta0[cIdx]+beta[cIdx,1]*xComb ))) , lwd=1.5 ,
             col="skyblue" )
      xInt = -beta0[cIdx]/beta[cIdx,1]
      arrows( xInt,0.5, xInt,-0.04, length=0.1 , col="skyblue" , lty="dashed" )
    }
    if ( !is.null(saveName) ) {
      saveGraph( file=paste(saveName,"DataThresh",sep=""), type=saveType)
    }
  }
  # If only 2 predictors:
  if ( ncol(x)==2 ) {
    openGraph(width=7,height=7)
    par( mar=c(3.5,3.5,2,1) , mgp=c(2.0,0.7,0) )
    plot( x[,1] , x[,2] , pch=as.character(y) , xlab=xName[1] , ylab=xName[2] ,
          col="black" , main="Data with Post. Pred.")
    cVec = floor(seq(1,chainLength,length=30))
    for ( cIdx in cVec ) {
      abline( -beta0[cIdx]/beta[cIdx,2] , -beta[cIdx,1]/beta[cIdx,2] , col="skyblue" )
    }
    if ( !is.null(saveName) ) {
      saveGraph( file=paste(saveName,"DataThresh",sep=""), type=saveType)
    }
  }
  #-----------------------------------------------------------------------------
  # Marginal histograms:

  decideOpenGraph = function( panelCount , saveName , finished=FALSE ,
                              nRow=1 , nCol=3 ) {
    # If finishing a set:
    if ( finished==TRUE ) {
      if ( !is.null(saveName) ) {
        saveGraph( file=paste0(saveName,ceiling((panelCount-1)/(nRow*nCol))),
                   type=saveType)
      }
      panelCount = 1 # re-set panelCount
      return(panelCount)
    } else {
    # If this is first panel of a graph:
    if ( ( panelCount %% (nRow*nCol) ) == 1 ) {
      # If previous graph was open, save previous one:
      if ( panelCount>1 & !is.null(saveName) ) {
        saveGraph( file=paste0(saveName,(panelCount%/%(nRow*nCol))),
                   type=saveType)
      }
      # Open new graph
      openGraph(width=nCol*7.0/3,height=nRow*2.0)
      layout( matrix( 1:(nRow*nCol) , nrow=nRow, byrow=TRUE ) )
      par( mar=c(4,4,2.5,0.5) , mgp=c(2.5,0.7,0) )
    }
    # Increment and return panel count:
    panelCount = panelCount+1
    return(panelCount)
    }
  }

  # Original scale:
  panelCount = 1
  panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMarg") )
  histInfo = plotPost( beta0 , cex.lab = 1.75 , showCurve=showCurve ,
                       xlab=bquote(beta[0]) , main="Intercept" )
  for ( bIdx in 1:ncol(beta) ) {
    panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMarg") )
    histInfo = plotPost( beta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,
                         xlab=bquote(beta[.(bIdx)]) , main=xName[bIdx] )
  }
  panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,"PostMarg") )

  # Standardized scale:
  panelCount = 1
  panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMargZ") )
  histInfo = plotPost( zbeta0 , cex.lab = 1.75 , showCurve=showCurve ,
                       xlab=bquote(z*beta[0]) , main="Intercept" )
  for ( bIdx in 1:ncol(beta) ) {
    panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMargZ") )
    histInfo = plotPost( zbeta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,
                         xlab=bquote(z*beta[.(bIdx)]) , main=xName[bIdx] )
  }
  panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,"PostMargZ") )

  #-----------------------------------------------------------------------------
}
#===============================================================================


text:
Q: Small values in alluvial plot where decreasing fontsize does not seem to be the solution I have a question where I am having some trouble with small counts in the category "Worse". Decreasing fontsize even more will decrease the readability (changing the vertical height is also not the solution for me). Does somebody have an ingenious idea of presenting the category (arrow with textbox e.g., but how?)
library(alluvial)
library(ggalluvial)
library(ggplot2)

Shortterm<-c("Healed","Impoved","Same","Worse","Healed","Improved","Same","Worse","Healed","Improved","Same","Worse")
Longterm<-c("Healed","Healed","Healed","Healed","Improved","Improved","Improved","Improved","Worse","Worse","Worse","Worse")
Frequence<-c(28,2,0,1,14,6,3,0,1,1,0,0)
Order<-c(0,0,0,0,1,1,1,1,2,2,2,2)
Improved<-c("Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","No","No","No")

output<-data.frame(Shortterm,Longterm,Frequence,Order,Improved)
output$Improved <- factor(output$Improved, levels = c("Yes", "No"))

ggplot(data = output,
       aes(axis1 = Shortterm, axis2 = Longterm,
           y = Frequence)) +
  scale_x_discrete(limits = c("Short-term \n ~ 6 months", "Long-term \n ~ 15 years"),expand = c(.2, .05),position="bottom") +
  scale_y_continuous(label = scales::percent_format(scale = 100 /n_id),breaks=c(0,1/4*n_id,1/2*n_id,3/4*n_id,n_id)) +
  geom_alluvium(aes(fill = Improved)) +
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  scale_fill_manual(values = c("green", "red"))+
  theme_minimal()

A: I found the answer:
Shortterm<-c("Healed","Improved","Same"," ","Healed","Improved","Same"," ","Healed","Improved","Same"," ")
Longterm<-c("Healed","Healed","Healed","Healed","Improved","Improved","Improved","Improved","Worse","Worse","Worse","Worse")
Frequence<-c(28,2,0,1,14,6,3,0,1,1,0,0)
Order<-c(0,0,0,0,1,1,1,1,2,2,2,2)
Improved<-c("Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","No","No","No","No")

output<-data.frame(Shortterm,Longterm,Frequence,Order,Improved)
output$Improved <- factor(output$Improved, levels = c("Yes", "No"))
output$Shortterm <- factor(output$Shortterm, levels = c("Healed","Same","Improved"," "))
output$Longterm  <- factor(output$Longterm,  levels = c("Healed","Same","Improved","Worse"))

n_id <- sum(output$Frequence)
ggplot(data = output,
       aes(axis1 = Shortterm, axis2 = Longterm,
           y = Frequence)) +
  scale_x_discrete(limits = c("Short-term \n ~ 6 months", "Long-term \n ~ 15 years"),expand = c(.2, .05),position="bottom") +
  scale_y_continuous(label = scales::percent_format(scale = 100 /n_id),breaks=c(0,1/4*n_id,1/2*n_id,3/4*n_id,n_id)) +
  geom_alluvium(aes(fill = Improved)) +
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum)),size=3) +
  scale_fill_manual(values = c("green", "red"))+
  theme_minimal() +
  ylab("Operated patients") + xlab("")+ theme(axis.text.x = element_text(face="bold",size=14))+
  annotate(
    geom = "curve", x = 1, y = 0.4, xend = 1.05, yend = -2,
    curvature = .3, arrow = arrow(length = unit(2, "mm"))
  )+
  annotate(geom = "text", x = 1.07, y = -2, label = "Worse", hjust = "left",size=3)


text:
Q: Sign Android project in Android Studio with shared keystore Hi I have a problem with signing android project in Android Studio, we are 3 people working on a project and we want to include the google+ sign in.
Since the google+ sign in requires to sign with a selfsigned cerficate (we cannot use the debug.keystore because it's different on each machine), so set the build.gradle like this:
android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
    }

    signingConfigs {

        release {
            storeFile file("path/to/key.keystore")
            storePassword "password"
            keyAlias "alias"
            keyPassword "password"
        }
    }

    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

}

dependencies {
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
    compile 'com.android.support:support-v4:+'
    compile 'com.google.android.gms:play-services:4.3.23'
}

Obviously the login with google+ doesn't work because I checked that the SHA1 of the apk (in workspace/project/app/build/apk/project.apk) is different, what am I doing wrong?
Thank you in advance for the help!

A: You need to select the release build variant for Gradle to use the keystore specified.
To do so, open the "Build Variants" tool window near the lower left corner of Android Studio, then use the dropdown to select "release."

If you don't see the "Build Variants" button, you should be able to find it under View > Tool Windows.


text:
Q: Why doesn't Stack Overflow have a tag for the "Scout" programming language? I don't know what Scout is, but here's the story, I dual booted my Windows XP last week, installing Linux Mint 12 and I wanted today to download Eclipse IDE.
On the download page, I see this
Developing Scout applications is supported by this Scout Developers Package.
I googled "scout" and found this and this and more of course...
Anyway, the question is, if Scout is not a popular language then why would Eclipse make an IDE for it?
If it is popular, then why doesn't Stack Overflow have a tag for it?
If you search for scout in the tag list, you'll see bugzscout which is an entirely different thing.

A: Tags are created by the community as needed.  When someone asks a question about scout and tags it with scout, the tag will be created.

A: Because we don't keep tags for things that aren't being used.  Think about it this way: how useful would tags be as a way to organize questions if we created one for every tech-related term you could think of?  There are already somewhere around 31,000 tags in existence on SO.  Do you really want more?
Of course, if you ask some questions about Scout, then by all means create it.

A: At the time this answer was written there were zero questions that mention Eclipse Scout.
In order for a tag to exist, it has to be attached to one or more questions.

A: At Eclipse, Scout isn't a programming language as mentioned in your references, but an Eclipse based framework to build business apps. So, the language behind Eclipse Scout is Java.
As questions will arise on Stack Overflow, I would like to suggest using eclipse-scout as a tag to avoid confusion with the many other uses for the word 'scout' (i.e. google for 'eclipse scout' will return meaningful hits)


text:
Q: SQL - If statement seemingly ignoring 'AND' I made the following stored procedure which will be called when creating a new employee.
The insert should be successful so long as the employee doesnt already exist in the Employee table.
To check for this I decided to check FirstName, LastName and DateOfBirth. If a row contains a 3 way match of all those columns, the insert should fail.
What i'm seeing is that the If statement is treating my AND as an OR.
If one match occurs the insert fails.
After some searching around I cant see to see what is wrong with my If structure.
Any help would be appreciated.
            Create Procedure CreateEmployee
            (
            @Role_ID Int,
            @FirstName Varchar(50),
            @LastName Varchar(50),
            @DateOfBirth Varchar(50),
            @Active Bit
            )
            As
            Begin

            If Not Exists (Select FirstName From Employee Where FirstName = @FirstName)
                AND Not Exists (Select LastName From Employee Where LastName = @LastName)
                AND Not Exists (Select DateOfBirth From Employee Where DateOfBirth = @DateOfBirth)

                Begin
                Insert Into Employee (Role_ID, FirstName, LastName, DateOfBirth, Active)
                Values (@Role_ID, @FirstName, @LastName, @DateOfBirth, @Active)
                End

            Else
                Begin
                Select 'User already exists!'
                End

            End

A: Why are you not just running 1 query for your check?
If Not Exists (Select 1 From Employee
               Where FirstName = @FirstName
                     and LastName = @LastName
                     and DateOfBirth = @DateOfBirth)
    begin
        ...

A: This is another way (@@rowcount for sql server): using Where not exists. Similar Sql Fiddle Demo
Insert Into Employee (Role_ID, FirstName, LastName, DateOfBirth, Active)
Select @Role_ID, @FirstName, @LastName, @DateOfBirth, @Active
Where not exists (
  select 1 from Employee where FirstName = @FirstName
                         and LastName = @LastName
                         and DateOfBirth = @DateOfBirth
)

If @@rowcount=0 select 'User already exists!'


text: Q: I can restrict listview with single item but i am unable to place get more button in list view to load remaining items in android How can I show my ListView to load remaining items on button click?  http://pastie.org/10565423


text:
Q: Elementary transformations of circles
Discuss the image of the circle $|z-2|=1$ and its interior under the
  following transformations.
a.) $w=\frac{z-2}{z-1}$
b.) $w=\frac{z-4}{z-3}$
c.) $w=\frac1z.$

The answer that is provided are, respectively: $$\{w:Rew\le\frac12\},\{w:Rew\ge \frac32\},\{w:|w-\frac23|\le\frac13\}.$$
Not sure how they got that. I know each of the circles has a pole and those poles lies on the circle, so the image has to be a straight line, but how do I go about finding those lines? Is there an algebraic or a more easy recognizable method to follow?

A: The usual mantra is 'three points defined a circle (or line)'. This is usually the quickest way to find the answer.
We'll use the fact that $1,3,2+i$ are in the original circle.
(a) $1\mapsto \infty$ so it is a line. $3 \mapsto \frac{1}{2}$, and $2+i \mapsto \frac{i}{1+i} = \frac{1}{2}(1+i)$. Hence we have a line through $\frac{1}{2},\frac{1}{2} + \frac{i}{2}$. This is clearly the line $\mathrm{Re} w = \frac{1}{2}$. To check which side of the line is which, note that $z=2$ is in the interior, and $2 \mapsto 0$ so the region is $\mathrm{Re} w \le \frac{1}{2}$
(b) I'll leave to you.
(c) You could do this as the above too. Alternatively, note $$|z-2| = 1 \iff (z-2)(z^\star-2) = 1 \iff 1 - 2/z - 2/z^\star+3/zz^\star = 0$$ and then using $w=1/z$ we find
$$3ww^\star - 2w -2w^\star + 1 = 0 \iff \left(w-\frac 2 3 \right)\left(w^\star-\frac 2 3 \right) = \frac 1 9$$
which gives the result. Again, one point is enough to tell you where the interior is.


text:
Q: Animated item alone in flatlist using useRef - react native? I'm trying to Animated "Scale" item when pressed In/Out,
but have an issue when pressing any item from the list there's a random item scaled!
I'm set the active index to Ref for every item when pressed and make a condition to scale the item based on it but not works well :\
here's My Code Snippet
(Live) One Here.
import React from 'react';
import {
  FlatList,
  SafeAreaView,
  Text,
  Pressable,
  Animated,
} from 'react-native';

const examples = [
  {
    key: 1,
    name: 'Animated Progress Bar Indicator',
  },
  {
    key: 2,
    name: 'FlatList Carousel Animation 1',
  },
  {
    key: 3,
    name: 'FlatList Carousel Animation 2',
  },
  {
    key: 4,
    name: 'FlatList Carousel Animation 3',
  },
];

const HomeScreen = ({navigation}) => {
  const scaleItem = React.useRef(new Animated.Value(1)).current;
  const activeIndexRef = React.useRef(null);

  const onPressInItem = (inds) => {
    activeIndexRef.current = inds;
    console.log('activeIndexRef', activeIndexRef.current);
    Animated.spring(scaleItem, {
      toValue: 0.95,
      useNativeDriver: true,
    }).start();
    console.log(inds === activeIndexRef.current ? 'hey' : 'no');
  };

  const onPressOutItem = (inds) => {
    activeIndexRef.current = inds;
    console.log('activeIndexRef-onPressOutItem', activeIndexRef.current);
    Animated.spring(scaleItem, {
      toValue: 1.0,
      useNativeDriver: true,
    }).start();
    console.log(inds === activeIndexRef.current ? 'hey' : 'no');
  };

  return (
    <SafeAreaView style={styles.container}>

      <FlatList
        data={examples}
        keyExtractor={(item) => item.key.toString()}
        renderItem={({item, index}) => {
          return (
            <Pressable
              onPressIn={() => onPressInItem(index)}
              onPressOut={() => onPressOutItem(index)}>
              <Animated.View
                style={{
                  flexDirection: 'row',
                  backgroundColor: '#56f',
                  alignItems: 'center',
                  paddingVertical: 10,
                  marginVertical: 10,
                  transform: [
                    {
                      scale: activeIndexRef.current === index ? scaleItem : 1,
                    },
                  ],
                }}>
                <Text style={styles.itemTitle}> </Text>
                <Text style={styles.itemTitle}>{item.name}</Text>
              </Animated.View>
            </Pressable>
          );
        }}
      />
    </SafeAreaView>
  );
};

export default HomeScreen;


text:
Q: Simple C++ script - Factorial - Errors I am learning C++. Here is a code counting factorial(silnia). Liczba means number.
#include <iostream>

using namespace std;

int _main()
{
    int silnia;
    int n;
    if (n == 0) return 1;
    else;
    return n * silnia(n-1);

    int liczba;
    cout << "Podaj liczbe: ";
    cin >> liczba;
    cout << liczba << "! = " << silnia(liczba) << endl;
    return 0;
}

However I still become error message:
main.cpp: In function 'int _main()':
main.cpp:9:20: error: 'silnia' cannot be used as a function
 return n*silnia(n-1);
                    ^
main.cpp:14:42: error: 'silnia' cannot be used as a function
 cout << liczba << "! = " << silnia(liczba) << endl

What can be the problem?

A: delete this part from your main:
 int silnia;
 int n;
 if (n == 0) return 1;
 else;
 return n * silnia(n-1);

put this function outside main function
 int silnia(int a)
{
 if(a==0) return 1;
 else return silnia(a-1)*a;
}

A: silnia(liczba)

Looks like you're trying to "call" the integer silnia.  Exactly what your error message says. I'm not sure what you're trying to do in that line.


text:
Q: How to amend a commit without changing commit message (reusing the previous one)? Is there a way to amend a commit without vi (or your $EDITOR) popping up with the option to modify your commit message, but simply reusing the previous message?

A: Another (silly) possibility is to git commit --amend <<< :wq if you've got vi(m) as $EDITOR.

A: To extend on the accepted answer, you can also do:
git commit --amend --no-edit -a

to add the currently changed files.

A: You can save an alias that uses the accepted answer so it can be used like this:
git oops

adds everything, and amends using the same commit message
git oops -m "new message"

uses a new commit message.

This is the alias:
 oops = "!f(){ \
    git add -A; \
    if [ \"$1\" == '' ]; then \
        git commit --amend --no-edit; \
    else \
        git commit --amend \"$@\"; \
    fi;\
}; f"

A: Full Tutorial for Dummies
Once you finish your changes in the code.
1.- git status to check in terminal the changes;
2.- Save your changes by using git add . or git add /your.file/ to do it file by file, using the previous command will help you in this last option;
3.- Once your changes have been staged you can now use git commit --amend --no-edit. This will add your recent changes to your last commit without editing the message.
4.- Finally, if you didn't push your previous commit just make a git push or git push origin/yourBranch.
In case you already pushed your last commit use git push -f or git push -f origin/yourBranch.

A: git commit -C HEAD --amend will do what you want.  The -C option takes the metadata from another commit.

A: Since Git 1.7.9 you can also use git commit --amend --no-edit to get your result.
Note that this will not include metadata from the other commit such as the timestamp or tag, which may or may not be important to you.

A: just to add some clarity, you need to stage changes with git add, then amend last commit:
git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.


text:
Q: Performing isnull in string How do I check if a string is null and set it to some value if it is?
Like in SQL,
isnull(string, 0)

A: string myString = null;
string isNullString = myString == null ? "0" : myString;

A: If you are using .Net 4.0 you can use string.IsNullOrWhiteSpace method also.

A: You could test for null:
if (s == null)
   s = "Hello";

or use the null coalescing operator:
string null_s = null;
string non_null_s = null_s ?? "Hello";

If you want to catch empty strings too, then you could use the IsNullOrEmpty test:
if (String.IsNullOrEmpty(s))
   s = "Hello";


text:
Q: Follow the link from PHPDoc in PhpStorm Imagine there is code like that:
<?php

class T
{
    /**
     * {@link http://php.net/count}
     * @link http://php.net/count
     *
     * @param array $inputArray
     *
     * @return int
     */
    public static function count(array $inputArray)
    {
        return count($inputArray);
    }
}

If I open a quick documentation window for the method, then there is an HTTP link, which I can click and it'll be opened in browser.

But I wonder if there is a way to follow the link from @link tag by clicking on it immediately from PhpStorm, without opening the quick documentation window?
I think I remember using this functionality, but I'm not 100% sure, and I could not find any info in the PhpStorm's documentation.

A: Unfortunately there is a bug in PhpStorm v2016.1 final.
It's now fixed -- but you have to use 2016.1.1 EAP build or wait until 2016.1.1 final will actually be released.
2016.1.1 EAP (latest for this moment build) can be downloaded here.

A: Ctrl-click on Windows (and Linux, I suppose) and Cmd-click on OSX opens the URL in the browser.


text:
Q: Why do I get "FATAL: parse 'gl-conf' failed: Permission denied" when installing GitLab 4.0? I'm trying to install a brand new instance of GitLab 4.0 onto an Ubuntu 12.04 server.
I follow the guide at https://github.com/gitlabhq/gitlabhq/blob/4-0-stable/doc/install/installation.md all the way up to the end of step 4.
When I try to clone the gitolite-admin repository, it fails like this:
root@ws-prod-git-01:/home/git# sudo -u gitlab -H git clone git@localhost:gitolite-admin.git /tmp/gitolite-admin
Cloning into '/tmp/gitolite-admin'...
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
FATAL: parse 'gl-conf' failed: Permission denied
fatal: The remote end hung up unexpectedly

I tried just ssh'ing in with the git user, but this is what I got:
root@ws-prod-git-01:/home/git# ssh -i /home/gitlab/.ssh/id_rsa git@localhost
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
PTY allocation request failed on channel 0
hello gitlab, this is git@ws-prod-git-01 running gitolite3 v3.2-gitlab-patched-0-g2d29cf7 on git 1.7.9.5

FATAL: parse 'gl-conf' failed: Permission denied
Connection to localhost closed.

This is the second time running through the set up process. I got the same errors the first time, so reset and tried again.
The permission denied error makes me think my permissions are set wrong, but I copied and pasted exactly what the installation guide told me to:
# Make sure the repositories dir is owned by git and it stays that way
sudo chmod -R ug+rwXs,o-rwx /home/git/repositories/
sudo chown -R git:git /home/git/repositories/

So, what should I try now?
Edit:
For various reasons, I mount my /home from an NFS share. On the off chance something was going on with that, I made a VM that didn't mount from NFS at all. Using that, I did NOT get the gl-conf error.
I then recreated the VM with the NFS shares, and the error reappeared.
Note that I have an old Gitlab v2.something install running that works with the NFS shares just fine.
Any thoughts on how NFS would effect this?


text:
Q: Certificate Verify Failed Postgresql Heroku I am running a PostgreSQL database through Heroku and asyncpg. My url is: postgres://user:pass@ec2-23-21-76-49.compute-1.amazonaws.com:5432/db_name.
When I run this, I get the error:
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)

This database url definitely works, it is valid when I use psycopg2. Just when I use asyncpg, I get this error.
I have tried not using a connection pool, that does not work either. Manually passing the user, password, etc. does not work either.
class Database:
    """Accessing database functions"""
    def __init__(self, bot):
        self.bot = bot
        try:
            self.dsn = os.environ["DATABASE_URL"]
        except KeyError:
            database_file = open('database_secret.txt', mode='r')
            self.dsn = database_file.read()
            database_file.close()

        self.pool = None
        self.prefix_conn = None
        self.prefix_stmt = None
        print(self.dsn)

        lop = asyncio.get_event_loop()
        lop.run_until_complete(self.init())

    async def init(self):
        self.pool = await asyncpg.create_pool(self.dsn, ssl=True)
        # It fails here

A: I had this issue and it was probably because I had a new SSL certificate, and a really old version of the Heroku stack (cedar-14), really old python (2.7.9), and really old requests (2.5.1) module.
I upgrade everything (heroku-16 stack, python 2.7.14, requests 2.18.4), but probably the thing that resolved the issue was that requests now requires the certifi module. My understanding is that module handles the SSL validation now.


text:
Q: apple mach-o linker error - string ar Xcode builds… I'm following http://www.youtube.com/watch?v=mQCjup8Uv5Q to the T and I'm getting errors.
I have the error apple Mach-o Linker Error some how with
'Undefined symbols for architecture armv7 and it references some items from the location: StringLoadImageMarker in libstringUnityDemo-1.1.3.a (StringAppController.o)
StringSetProjectionAndViewport in libStringUnityDemo-1.1.3a (StringAppController.o)
The undefined symbols to the error above are _timer, _cur0rientation, 0orientationwillchangesuraceextents, _surface, unitykeyboardorientation, handle0rientationRequest, Shouldhandlerotation, present surface, unitysetalloworientationdetection
My software versions are
Unity 4.1.3, Xcode 4.6.2, String 1.1.3
I would appreciate your help!
Regards,

A: well without doing a logmein or seeing any code... hard to tell... often these linker errors happen when you forget to add the library to the project (not just import the files, but actually go in the project settings and make sure it gets imported, just google importing library to project), or sometimes the libraries you use are ok to use on a device but not on the simulator, or vice versa....


text:
Q: Difference between AMPS(Advanced Message Processing System) and JMS What is the difference between the 2 because both of them are based on the same methodology of publishers and subscribers who exchange messages between them via topics/subjects?

A: JMS is a Java-based API for asynchronous messaging supporting both point-to-point and pub-sub semantics. It can be implemented by anyone. Apache ActiveMQ is probably the most popular and well-known JMS implementation, although there are numerous implementations.
AMPS is a proprietary messaging system developed by 60East Technologies which appears to only support pub-sub semantics.

A: I recently came across this post and, as an employee of 60East Technologies, felt that it deserved a more complete response.
If you're asking in terms of "what role in an architecture do these serve", then you're right: both of these fall in the broad category of message-oriented middleware. They're both ways to coordinate and exchange data between processes based on the concept of messages as the units of data exchanged.
JMS is a standard API for Java, and one of the more popular ways of handling messaging. There are multiple implementations from multiple vendors. Since it's a standard, these are all similar in interface and have distinct implementations. Products that support JMS can also support wire standards such as AMQP to provide a level of interoperability for components that aren't written in Java.
AMPS (Advanced Message Processing System) is a bit less widely-known. It's a messaging product developed by 60East Technologies, Inc. Since it's a product rather than a standard, there's one implementation. It's a broker-based system, so in AMPS all message traffic passes through the broker. AMPS supports multiple programming languages (right now, there are clients available for Java, C#/.Net, Python, JavaScript, and C++). AMPS supports a variety of message payload formats (FIX, JSON, XML, Protocol Buffers, MessagePack, etc.). AMPS also supports a few different styles of message delivery: message queues (as JMS does), fan-out publish and subscribe, "query and subscribe" where an application gets current values for a set of records and then receives push updates when the records change, and historical replay ("bookmark subscribe") that exactly replays a stream of messages any number of times. AMPS also provides things like inline message transformation/enrichment, the ability to aggregate messages and project views (similar to the way an RDBMS can project a view of an underlying table).
AMPS was initially designed for very high-volume and low-latency applications (things like crossing engines/crossing networks in the financial sector). AMPS emphasizes performance, and takes a "whole-system" view of performance. That is, performance is considered from the point at which a producer starts to send a message to the point at which a consumer can act on the message, not just with regards to time in the broker.
To sum it up: AMPS is a product rather than a standard, supports multiple programming languages, provides a wide variety of capabilities and beyond message queues, and is designed for very high performance
Ryan
60East Technologies


text:
Q: List order by another contained list I have a list of Objects and one of the item is another list. How can I Group them based on the inner list.
Here is an example of what I wish to do.
class Student
{
    public string Name;
    public int Age;
    public List<GroupInfo> GroupList; // This is the inner list
}

class GroupInfo
{
    public string GroupName;
    public int GroupId;
}

static void Main()
{
   GroupInfo firstGroup = new GroupInfo
   {
      GroupId = 1,
      GroupName = "First group"
   };

   GroupInfo secondGroup = new GroupInfo
   {
       GroupId = 2,
       GroupName = "Second group"
    };

    GroupInfo thirdGroup = new GroupInfo
    {
       GroupId = 3,
       GroupName = "Third group"
    };

    GroupInfo fourthGroup = new GroupInfo
    {
       GroupId = 4,
       GroupName = "Fourth group"
    };

    List<Student> studentList = new List<Student>();

    Student firstStudent = new Student();
    firstStudent.Name = "Name1";
    firstStudent.Age = 15;
    firstStudent.GroupList = new List<GroupInfo>();
    firstStudent.GroupList.Add(firstGroup);
    firstStudent.GroupList.Add(secondGroup);
    studentList.Add(firstStudent);

    Student secondStudent = new Student();
    secondStudent.Name = "Name2";
    secondStudent.Age = 17;
    secondStudent.GroupList = new List<GroupInfo>();
    secondStudent.GroupList.Add(firstGroup);
    secondStudent.GroupList.Add(thirdGroup);
    studentList.Add(secondStudent);

    Student thirdStudent = new Student();
    thirdStudent.Name = "Name3";
    thirdStudent.Age = 18;
    thirdStudent.GroupList = new List<GroupInfo>();
    thirdStudent.GroupList.Add(secondGroup);
    thirdStudent.GroupList.Add(thirdGroup);
    thirdStudent.GroupList.Add(fourthGroup);
    studentList.Add(thirdStudent);

    List<GroupInfo> groupInfoList = new List<GroupInfo>();
   // Now What I want is to get a group List Where...
    foreach (var student in studentList)
    {
        // ...First Group Should contains firstStudent and secondStudent
        // Second group Should firstStudent & thirdStudent
        // Third group Should contains secondStudent & thirdStuden
        // Fourth Group Should contains only thirdStudent
      }
    }

One way is to iterate on the whole List and populate the GroupInfo List. Just wondering is there any other way to do this task.

A: You can do this with SelectMany like this:-
var result = studentList.SelectMany(x => x.GroupList,
                                      (studentObj, groups) => new { studentObj, groups })
                        .GroupBy(x => new { x.groups.GroupId, x.groups.GroupName })
                        .Select(x => new
                               {
                                  GroupId = x.Key.GroupId,
                                  GroupName = x.Key.GroupName,
                                  Students = x.Select(z => z.studentObj).ToList()
                               });

Since your GroupInfo class only has two properties i.e. GroupId & GroupName, you won't be able to fetch the Students associated with it. This is the reason I am fetching anonymous type out of it.
I am getting following output with this query:-


text:
Q: Tabs in every activity in android My first page contains 3 tabs. I want to retain all these 3 tabs through out my entire application. That means I want to see these 3 tabs in every view. For example : I have 3 views. First view is Main.class. It contains 3 tabs (Home tab, Favourite tab, settings tab). When I am clicking any one tab (Ex: Home Tab), it shows the contents of Home.class (a ListView) below these tabs. But when I am clicking the ListView view , it will go to another activity(SubListView.class), and I can't see the tabs in that activity. Only contents of that view will be displayed there. How can I show these header tabs in that view also?
Main View: (in Main.class)
   final TabHost tabHost = getTabHost();
   Intent intent;
   LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(),true);
   tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Home",getResources().getDrawable(R.drawable.img_home)).setContent(new Intent(this, Home.class)));
   tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Favourites",getResources().getDrawable(R.drawable.img_fav)).setContent(new Intent(this, Favourites.class)));
   tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Settings",getResources().getDrawable(R.drawable.img_set)).setContent(new Intent(this, Settings.class)));
   tabHost.setCurrentTab(0);

Home View: (in Home.class)
 public ArrayAdapter<String> adapter;
 final ArrayList<String> results = new ArrayList<String>();
 ListView listitems=(ListView)findViewById(R.id.list);
 adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,results);
 listitems.setAdapter(adapter);
 listitems.setOnItemClickListener(new AdapterView.OnItemClickListener()
 {
       //@Override
       public void onItemClick(AdapterView arg0, View view, int position, long id)
       {
               categoryNameFromList=results.get(position);
               Bundle category_bundle = new Bundle();
               category_bundle.putString("selected_item",categoryNameFromList);
               Intent category_intent = new Intent(view.getContext(), SubListView.class);
               category_intent.putExtras(category_bundle);
               startActivityForResult(category_intent, 1);

       }
 });

SubList View (in SubListView.class)
 TextView txtmessage=new TextView(this);
 txtmessage.setTex("WELOCME TO SUB LIST VIEW!!");
 setContentView(txtmessage);

Please help me.. Thanking you in advance..

A: Use TabActivity.
Example on using TabActivity and Tab widgets.


text:
Q: Position frame on top of button in Xamarin Forms I will be creating a custom control where a frame is positioned on top of a button, all within a grid. When I do this and the button is clicked, the button ends up on top and the frame disappears. How do I keep the frame on top when the button is clicked?
Here is the simple xaml:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="30"/>
    </Grid.ColumnDefinitions>
    <Button
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Text="Test"
        BackgroundColor="Green"
        TextColor="White"/>
    <Frame
        Grid.Row="0"
        Grid.Column="1"
        CornerRadius="12"
        HasShadow="false"
        OutlineColor="Transparent"
        BackgroundColor="Red"
        Padding="0">
        <Label Text="3" TextColor="White" FontAttributes="Bold" Margin="10"/>
    </Frame>
</Grid>

I am trying to create a button with a badge. The badge isn't positioned well here, but I'm just concerned about the behavior of the badge being hidden when the button is clicked.

A:
The frame does disappear when the button is clicked

Your code works well on iOS and there is a known issue in Android:Content rendered above a Material button is not visible when button is pressed
Just add the following to your MainActivity.OnCreate before the global::Xamarin.Forms.Forms.Init(this, savedInstanceState) call:
global::Xamarin.Forms.Forms.SetFlags("UseLegacyRenderers");

Refer: Button in a AbsoluteLayout issue

A: In button, while clicking by applying the tap animation to hide your frame. So, you use the Label instead of the button like below,
<Label
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Text="Test"
        BackgroundColor="Green"
        TextColor="White">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
                </Label.GestureRecognizers>
</Label>

For handling the click, you can use TapGestureRecognizer.


text:
Q: Unity Mobile Notification android, звук уведомлений         AndroidNotificationChannel channel = new AndroidNotificationChannel()
        {
            Name = "Имя уведомления в настройка",
            Description = "Описание уведомления в настройка",
            Id = "test",
            Importance = Importance.High,
        };
        AndroidNotificationCenter.RegisterNotificationChannel(channel);

        AndroidNotification notification = new AndroidNotification()
        {
            Title = "Заголовок уведомленя",
            Text = "Текст уведомления",
            FireTime = DateTime.Now.AddSeconds(5),
            Color = Color.white,
        };

        AndroidNotificationCenter.SendNotification(notification,"test");

Канал уведомления работает, в настройках приложения появляется соответствующая кнопка, уведомление также приходит, лампочка загорается белым и есть вибрация, но нет звука от уведомления, причём вибрации нет, если я переключаю телефон в звучный режим. Возможно что-то не так с моим телефоном, вопрос, есть ли какие-то способы работы со звуком уведомлений, а также каким образом я могу это протестировать без использования своего телефона (потому что как я и сказал, кажется что там какая-то проблема с уведомлениями)


text:
Q: Change DataTrigger binding reference at runtime I've a ListView with this DataTrigger attached:
<Style x:Key="HideShowStyle" TargetType="{x:Type ListViewItem}">
        <Style.Resources>
            <localConverters:ShowHideConverter x:Key="ShowHideConverter" />
        </Style.Resources>

        <Style.Triggers>
            <DataTrigger Value="true">
                <DataTrigger.Binding>
                    <MultiBinding Converter="{StaticResource showHideConverter}">
                        <Binding Path="EndingDate" />
                        <Binding Path="UserName" />
                        <Binding ElementName="SearchBox" Path="Text" />
                    </MultiBinding>
                </DataTrigger.Binding>
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>

            <DataTrigger Value="false">
               (...)
            </DataTrigger>
        </Style.Triggers>
</Style>

I use this in a hardcoded scenario to hide/show some ListItems in the ListView. The binding source is specified in the ElementName tag, and the TextBox referred is declared a few lines before.
Now, I've the necessity to change that Binding at runtime with another field incapsulated in a istantiated class. I've tried to use WPF class instead of XAML, but nothing, I don't have any clue how to obtain this.
I'm open to any advice! :)

A: var style = (Style)FindResource("HideShowStyle");
var trigger = (DataTrigger)style.Triggers[0];
var multibinding = (MultiBinding)trigger.Binding;

var binding1 = (Binding)multibinding.Bindings[0];
var binding2 = (Binding)multibinding.Bindings[1];
var binding3 = (Binding)multibinding.Bindings[2];

Change bindings at will.


text:
Q: jquery validation plugin not working jQuery validation plugin doesn't seem to work with my code. The text fields are present in a table wrapped inside a form. This is a dynamic form.
$('#buttonID').live('click', function(event) {

        $('#formID').validate({
          rules: {
                firstName: "required",
                lastName: "required",
                phoneNum: {
                    required: true,
                    minlength: 10
                },
                pword: {
                    required: true,
                    minlength: 7
                },
                cpword: {
                    required: true,
                    minlength: 7,
                    equalTo: "#pword"
                },
                emailId: {
                    required: true,
                    email: true
                }
            },
            messages: {
                firstName: "Please enter firstname",
                lastName: "Please enter lastname",
                phoneNum: "Please provide a phone number",
                pword: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 7 characters long"
                },
                cpword: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 7 characters long",
                    equalTo: "Please enter the same password as above"
                },
                emailId: "Please enter a valid email address"
            }

        });

    event.preventDefault();
});

Here is the code where I create a form on button click:
function createNewUser(event){
    //clear all the divs
                    if ($("#srchResults").length > 0){
                            $('#srchResults').empty();
                    }
        var htmlTable;

                    htmlTable = '<form id="userAttrC">';
                    htmlTable += '
';
                    htmlTable += '
';
                    htmlTable += '<input type="submit" id="saveUser" class = "buttons" value="Save" > <input type="submit" id="cancelUser" class = "buttons" value="Cancel" >';
                    htmlTable += '
';
                    htmlTable += '
';
                    htmlTable += '';
                    htmlTable += '	';
                    htmlTable += '';
                    htmlTable += '	';
                    htmlTable += '';

                    htmlTable += 'Personal Information
';
                    htmlTable += '
';
                    htmlTable += 'Salutation:';
                    htmlTable += '<select id="salutationDD" name="salutation" class="filterselect">';
                    htmlTable += '<option value=""></option>';
                    htmlTable += '<option value="Mr.">Mr.</option>';
                    htmlTable += '<option value="Ms.">Ms.</option>';
                    htmlTable += '<option value="Mrs.">Mrs.</option></select>
';

                    htmlTable += 'First Name:';
                    htmlTable += '<input type="text" name="fname" id="firstName" class="readOnlyIp" value="" />
';

                    htmlTable += 'Last Name:';
                    htmlTable += '<input type="text" name="lname" id="lastName" class="readOnlyIp" value="" />
';

                    htmlTable += 'Name Suffix:';
                    htmlTable += '<input type="text" name="suffix" class="readOnlyIp" value="" />
';

                    htmlTable += 'Email:';
                    htmlTable += '<input type="text" name="email" id="emailId" class="readOnlyIp" value="" />
';

                    htmlTable += 'Country:';

                    htmlTable += '<select id="countryDD" name="country" class="filterselect">';

                    //get country list via ajax call
                    $.ajaxSetup({
                        async: false,
                        "error":function() {
                            alert("error");
                    }});
                    $.getJSON("<url>",
                    {
                    countries: "1"
                    },
                    function(data) {

                            htmlTable += '<option value=""></option>';

                            for(var i=1; i<data[0].length; i++){
                                htmlTable += '<option value="'+data[0][i]+'">'+data[0][i]+'</option>';
                            }
                    });
                    htmlTable += '</select>
';

                    htmlTable += 'Phone Number:';
                    htmlTable += '<input type="text" name="phone" id="phoneNum" class="readOnlyIp" value="" />
';

                    htmlTable += 'Phone Extension:';
                    htmlTable += '<input type="text" name="ext" class="readOnlyIp" value="" />
';

                    htmlTable += 'Cell Phone:';
                    htmlTable += '<input type="text" name="cell" class="readOnlyIp" value="" />
';

                    htmlTable += 'Password:';
                    htmlTable += '<input type="text" name="pwd" id="pword" class="readOnlyIp" value="" />
';
                    htmlTable += 'Confirm Password:';
                    htmlTable += '<input type="text" name="cpwd" id="cpword" class="readOnlyIp" value="" />
';
                    htmlTable += '
';
                    htmlTable += '
';
                    htmlTable += '</form>';

     $('#srchResults').append(htmlTable);
    event.preventDefault();
}
$("#createUser").click(function(event){ createNewUser(event); });

A: adding the validation rules on the button is ok, especially if on document ready, your form doesn't exist yet,   without seeing your entire page code it's hard to say what the BEST place to do it is though.  Likely in the success handler of your ajax call that loads your form.
anyway, the point is, in your button handler, you need to actaully tell the form to validate! like so:
$('#formID').valid();

this is what i ussually do:
if($('#formId').valid()){
    //do your form posting logic here
}
else{
   //anything special you want to do with an invalid form

}

EDIT:
ok, put your $('#FormId').validate() stuff right after:
$('#srchResults').append(htmlTable);

and then have:
 if($('#formId').valid()){
        //do your form posting logic here
    }
    else{
       //anything special you want to do with an invalid form

    }

inside this:
$('#buttonID').live('click', function(event) {

A: Try to move validation to document ready handler:
$(document).ready(function() {
    $('#formID').validate({...})
});

A: That's not the way the validation plugin works.  You need to set your validation code inside the document.ready() function and then call the .form() method in your onClick  You can use the submit:false option if you don't want the form validated on any form submit event...
Something like this:
var _validator;

$(function() {
    _validator = $('#formID').validate({
          onsubmit: false,
          rules: { ... },
          messages: { ... }
    });

    $('#buttonID').click(function(e) {
        e.preventDefault();
        if ( _validator.form() ) {
            // valid form code
        }
    });
});

UPDATE :
Working jsFiddle example here :  http://jsfiddle.net/shaneblake/RQMaV/

A: validation plugin works out with 'name' of the input field  means
$('#formID').validate({
    rules: {
        firstName: "required"
    }
});

inside the rules  we uses the name of the input field not the id
<input type="text" name="firstName" id="firstName" class="readOnlyIp" value="" />
so amke

A: use validate() to create rules for validating fields
the call valid() to check if rules are met


text:
Q: Echo a SimpleXMLElement Object I've got an array that looks like this.
Array
(
    [@attributes] => Array
        (
            [version] => 2.0
        )

    [channel] => SimpleXMLElement Object
        (
            [title] => Active Fire Incident Page
            [link] => http://www.ci.austin.tx.us/fact/default.cfm
            [description] => This page provides information on active Austin/Travis County Fire incidents.  Data is updated every 3 minutes.

            [lastBuildDate] => Wed, 23 Nov 2016 10:59:38 PM GMT
            [copyright] => 2016 City of Austin. All rights reserved.
            [language] => en-us
            [item] => SimpleXMLElement Object
                (
                    [title] => E ST ELMO RD/SHERATON AVE
                    [link] => http://www.ci.austin.tx.us/fact/default.cfm
                    [description] => AFD - 4700 S Congress Ave - BOX -Structure Fire - Wed, 23 Nov 2016 10:51 PM
                    [pubdate] => Wed, 23 Nov 2016 10:51 PM
                )

        )

)

How would I go about echoing the last part of the array?  This section:
                    [title] => E ST ELMO RD/SHERATON AVE
                    [link] => http://www.ci.austin.tx.us/fact/default.cfm
                    [description] => AFD - 4700 S Congress Ave - BOX -Structure Fire - Wed, 23 Nov 2016 10:51 PM
                    [pubdate] => Wed, 23 Nov 2016 10:51 PM

With this code:
echo $xml->channel->item->link;

I'm getting
Notice:Trying to get property of non-object

A: You are using wrong code, try this
foreach($xml->channel->item as $key => $product){
   echo $product->link;

OR directly
 echo $xml->channel->item->link;

A: echo ($xml['channel'])->item->link;

Is the solution.


text:
Q: undefined local variable or method 'gallery' Okay, so I'm rebuilding an old photo gallery management app that I built a few years back in ROR 1 and running in to a few coding difficulties, since I'm rusty and apparently things have changed. My first question is I'm getting an undefined local variable or method 'gallery' error when trying to call a page. What I'm confused about is that I have the method defined in the 'gallery' controller but I'm wondering if I'm completely missing something. Here are some relevant code snippets, first is my index.html.erb page:
<% @photos.each do |photo| %>

<%= image_tag(photo.thumb_url) %>
<%= link_to 'Show', gallery %>

<% end %>

<%= will_paginate @photos %>

my gallery controller:
class GalleryController < ApplicationController
  skip_before_filter :authorize
  # GET /gallery
  # GET /gallery.xml
  def index
    @photos = Photo.all
    @photos = Photo.paginate :page=>params[:page], :order=>'date desc',
    :per_page => 2

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @gallery }
    end
  end

  # GET /gallery/1
  # GET /gallery/1.xml

  def show
    @photo = Photo.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @photo }
    end
  end
end

And my error:
undefined local variable or method `gallery' for #<#<Class:0x111127b38>:0x1112d5700>

I should clarify that "Photos" is the admin section which requires login and contains all of the fields/database/record data. I have no problem using the following line:
<%= link_to 'Show', photo %>

Which brings up the correct record and viewing page, but in the admin section of the site (which requires login). Hopefully that makes sense.

A: Nowhere do I see you defining the variable gallery, and this is what your error message is telling you: gallery is undefined in your view.

Update RE your comments:
Just because you want the photo to go to the gallery controller doesn't mean you can just type "gallery" and expect results. This is a programming langauge, where words have meanings, and all you're doing is referencing an undefined variable. This, and nothing like this, has ever worked in any version of Rails.
If you want to route your photo to the Gallery controller, you can use the automagically generated _path helpers; specifically, gallery_path, which accepts an argument for the id of the "gallery" (really a photo) to show:
<%= link_to 'Show', gallery_path(photo.id) %>

A: Try replacing your link_to method with something like: <%= link_to 'Show', :controller => "photos", :action => :your_method, :params1 => gallery %>.
Then in your PhotoController you can use: @my_gallery = params[:params1] to access your gallery item.
Some documentation on routes:
http://guides.rubyonrails.org/routing.html


text:
Q: String substitutions across multiple columns in tidyverse My data frame
>df <- data.frame(Names = c("A", "B", "C"), Total = c("125", "2 500", "1 350"),
>           Boys = c("50", "1 500", "350"),
>           Girls = c("75", "1 000", "1 000"))
  Names Total  Boys Girls
1     A   125    50    75
2     B 2 500 1 500 1 000
3     C 1 350   350 1 000

All values are strings. I want to substitute spaces " " to non spaces "" in Total, Boys and Girls. I know about
df %>%
  mutate(Total = gsub(" ", "", Total),
         Boys = gsub(" ", "", Boys),
         Girls = gsub(" ", "", Girls))

But is there a (tidyverse style) way to do this more generally? Something like
df %>% # (This don't work)
  mutate(across(c(Total, Boys, Girls), gsub(" ", "", .x)))

I.e. I'm looking for a solution that scales well.
Thanks in advance.

A: You can use :
library(dplyr)

df %>% mutate(across(c(Total, Boys, Girls), ~as.numeric(gsub(" ", "", .))))

#  Names Total Boys Girls
#1     A   125   50    75
#2     B  2500 1500  1000
#3     C  1350  350  1000

Or in base R with lapply :
df[-1] <- lapply(df[-1], function(x) as.numeric(gsub(" ", "", x)))

A: We can use str_remove from stringr
library(stringr)
library(dplyr)
df %>%
    mutate(across(-Names, ~ as.numeric(str_remove(., "\\s+"))))
#  Names Total Boys Girls
#1     A   125   50    75
#2     B  2500 1500  1000
#3     C  1350  350  1000

A: Maybe you can try gsub + as.matrix like below
type.convert(cbind(df[1], gsub("\\s+", "", as.matrix(df[-1]))), as.is = TRUE)

which gives
  Names Total Boys Girls
1     A   125   50    75
2     B  2500 1500  1000
3     C  1350  350  1000


text:
Q: Finding the highest occurrence of a Physician based on how many patients in each City I want to create an aggregation query that will display the physician that has the most patients in each City. That also works with the average age for each city.
For example:
{
     City: "Vancouver"
     Physician: "Physician Test1"
     Average_Age: 56
},
{
     City: "Burnaby"
     Physician: "Physician Test2"
     Average_Age: 40
}

Example of some of my data
{
        "gender" : "Female",
        "full_name" : "Test Patient",
        "age" : 20,
        "city" : "Burnaby",
        "severity_code" : 2,
        "PHN" : "11-1111111",
        "primary_physician" : "Physician Test1",
        "location" : "4A",
        "attendance_method" : "Self-Driven"
},
{
        "gender" : "Male",
        "full_name" : "Test2 Patient2",
        "age" : 68,
        "city" : "Vancouver",
        "severity_code" : 1,
        "PHN" : "00-0000000",
        "primary_physician" : "Physician Test2",
        "location" : "6D",
        "attendance_method" : "Walk-In"
 }

How do I create the aggregation query for the above?

A: You can run the following aggregation pipeline:
db.patients.aggregate([
    {
        "$group": {
            "_id": {
                "City": "$city",
                "Physician": "$primary_physician"
            },
            "count": { "$sum": 1 },
            "Average_Age": { "$avg": "$age" }
        }
    },
    { "$sort": { "count": -1 } },
    {
        "$group": {
            "_id": "$_id.City"
            "Physician": { "$first": "$_id.Physician" },
            "Number_of_Patients": { "$first": "$count" },
            "Average_Age": { "$first": "$Average_Age" }
        }
    }
])

In the above aggregation, the first pipeline step with the $group operator groups the documents by the city and physician fields and calculates the number of documents (thus the number of patients) in the group through the { "$sum": 1 } expression, as well as aggregating the avarage age of the patients with { "$avg": "$age" } expression.
The second pipeline stage { "$sort": { "count": -1 } } orders the previously grouped documents by the count. This is necessary for the further grouping since you want to get the physician that has the most patients in each city i.e. in the each group, take the top document that has the largest count. The preceding pipeline does excactly this.
It groups the sorted documents by the city key and then returns the  desired fields using the $first operator.


text:
Q: Serializing C# model with a custom list to JSON I have a model with a list that I need to serialize to JSON in order to send a request to a web service.
The problem is that in my model I have a list that need to be serialized in a specific format.
My class looks like the following:
[DataContract()]
public class StanjeZalihaLek : BaseParameters
{
    [DataMember(Name = "datumStanje")]
    public string _datumStanja;

    [DataMember(Name = "type")]
    public int Type { get; set; }
    [IgnoreDataMember]
    public DateTime? DatumStanja { get; set; }
    [IgnoreDataMember()]
    public List<Lek> ListaLek { get; set; }

    [OnSerializing()]
    protected void OnSerializingMethod(StreamingContext context)
    {
        _datumStanja = DatumStanja?.ToString(FormatDate);
    }
}

So all the elements are ok except the List ListaLek { get; set; } member that looks like the following:
   [DataContract()]
   public class Lek
{
    const string FormatDate = "dd.MM.yyyy";

    [DataMember(Name = "datumUlaz")]
    string _datumUlaza;
    [DataMember(Name = "datumRok")]
    string _rokUpotrebe;

    [DataMember(Name = "jkl")]
    public string JedinstvenaKlasifikacijaLeka { get; set; }
    [DataMember(Name = "kolicina)")]
    public double Kolicina { get; set; }
    [DataMember(Name = "kpp")]
    public string Kpp { get; set; }
    [IgnoreDataMember]
    public DateTime? DatumUlaza { get; set; }
    [IgnoreDataMember]
    public DateTime? RokUpotrebe { get; set; }

    [OnSerializing()]
    protected void OnSerializingMethod(StreamingContext context)
    {
        _datumUlaza = DatumUlaza?.ToString(FormatDate);
        _rokUpotrebe = RokUpotrebe?.ToString(FormatDate);
    }
}

This is the way my serialized code is supposed to look like:
{
    "idZu": "12345678",
    "user": "ustanova1",
    "pass": "pass1w0rd",
    "type": "1",
    "datumStanje": "26.02.2019",
    "0": {
        "jkl": "0010200",
        "kolicina": "4",
        "kpp": "071",
        "datumUlaz": "26.02.2019",
        "datumRok": " 31.12.2019"
    },
    "1": {
        "jkl": "0010220",
        "kolicina": "8",
        "kpp": "071",
        "datumUlaz": "26.02.2019",
        "datumRok": " 31.12.2019"
    },
    "2": {
        "jkl": "12205014",
        "kolicina": "12",
        "kpp": "071",
        "datumUlaz": "26.02.2019",
        "datumRok ": "31.12.2019"
    }
}

So each new element of the list has a number as its DataMember name, with idZu, user and pass being parameters from the BaseParameters class which StanjeZalihaLek derives.
Any ideas? Thanks

A: Problem solved:
        public static byte[] Serialize(this StanjeZalihaLek data)
        {
            var sb = new StringBuilder();

            using (var tw = new System.IO.StringWriter(sb))
            {
                Newtonsoft.Json.JsonTextWriter jsonWriter = new JsonTextWriter(tw);
                jsonWriter.WriteStartObject();

                jsonWriter.WriteRaw(JsonConvert
                                 .SerializeObject(data)
                                 .Substring(1)
                                 .TrimEnd('}'));

                jsonWriter.WriteRaw(",");

                int inx = 0;
                foreach (var item in data.ListaLek)
                {
                    var str = $"{inx++}";

                    jsonWriter.WritePropertyName(str);
                    jsonWriter.WriteRawValue(JsonConvert.SerializeObject(item));
                }
                jsonWriter.WriteEndObject();
                jsonWriter.Close();

            }

            return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
        }