text:
Q: Mongoose removes too many from ID I may be misunderstanding something, but on the client I have a request sent to the server.  Something like:
$.post("/resources/remove", {"id": 52024e25b26d39f931000003})

On the server I have
Resource.remove({_id: request.body.id})

The "ID" is correct and using Resource.find with the same arguments returns the record I want to remove.  However, when this is run it removes all Resource records.  The return value of exec(function (err, returnValue) is the number of Resource records that were there, so it is definitely removing all of them.  Using Remove.(request.body.id) does the same thing.
Do I need to do anything else to make sure that only the record with the corresponding _id is removed?  If the entry is invalid why is it removing all records?

A: Try using Resource.findOneAndRemove Reference
I've never used that but this is what I use and it works perfectly for me
PostModel.findOne({_id: id}, function (err, result) {
    if (err) {
        throw err;
    }
    if (result) {
        PostModel.remove({_id: id}, function (err, result) {
            if (err) {
                throw err;
            }
            res.json(200, result);
        });
    }
});


text:
Q: c# reflection with dynamic class I need to execute a method "FindAll" in my page. This method returns a list of the object.
This is my method that I execute "FindAll". FindAll requires an int and returns an List of these class.
public void ObjectSource(int inicio, object o)
{
  Type tipo = o.GetType();
  object MyObj = Activator.CreateInstance(tipo);
  object[] args = new object[1];
  args[0] = inicio;
  List<object> list = new List<object>();
  object method = tipo.InvokeMember("FindAll", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args);
}

When I execute ObjectSource, it returns ok, but I can't access the result. In VS2008, I can visualize the list by "ctrl + Alt + q" but by casting doesn't work.
I forgot to say: this method "FindAll" is static!

A: Few things going on here, first, your method doesn't return the result.
Second, when you do return the object, there's nothing stopping you casting to the appropriate type in the calling code.
Third, you could use Generics to make this method strongly typed like so:
public T ObjectSource<T>(int inicio, T o)
{
  Type tipo = typeof(T);
  object MyObj = Activator.CreateInstance(tipo);
  object[] args = new object[1];
  args[0] = inicio;
  return tipo.InvokeMember("FindAll", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args) as T;
}

A: Try this (updated):
public IEnumerable ObjectSource(int inicio, object o) {
    Type type = o.GetType();
    object[] args = new object[] { inicio };
    object result = type.InvokeMember("FindAll",
        BindingFlags.Default | BindingFlags.InvokeMethod, null, o, args);
    return (IEnumerable) result;
}

A better solution would be to put your FindAll method into an interface -- say, IFindable, and make all your classes implement that interface.  Then you can just cast the object to IFindable and call FindAll directly -- no reflection required.

A: Daniel, i got a few object that i need to bind a grid view and this list more than 1.000 records, then a want to pagging by 50, and this Object Source must be generic because will call FindAll of the classes!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change android component position with Virtual Keyboard status I have three buttons in linear layout of Activity. I want that these buttons change its position when keyboard is shown or Hidden.  Any Suggestion?

A: Use below code in manifest :-
<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

for more info see below link:-
http://developer.android.com/guide/topics/manifest/activity-element.html#wsoft


text:
Q: Joining all the keys of a list of rules that point to matching values Suppose I have a list of rules whose keys are not of identical structure (in my case, the keys are either lists of at least one symbol or symbols alone):
rules = {{a} -> 1, {b, c} -> 1, d -> 2, {e, f} -> 2, {g, g} -> 3, g -> 4};

The aim is to get all keys with matching values grouped together to end up with
newRules = {{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4};

I have what seems to me to be a hacky attempt to do this:
Reverse /@
    Normal[
        Merge[
            Association /@ Reverse /@ rules, Flatten]
        ] == newRules
(* True *)

Are there any better ways to do this?

A: Reverse /@ (Flatten /@ PositionIndex[Association@rules] // Normal)

{{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4}

In addition:
Flatten /@ PositionIndex[Association@rules]

<|1 -> {a, b, c}, 2 -> {d, e, f}, 3 -> {g, g}, 4 -> {g}|>

A: KeyValueMap[#2 -> #&] @ Merge[Flatten][Reverse /@ rules]

{{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4}

Als0
Flatten[#[[All, 1]]] -> #[[1, -1]]& /@ GatherBy[rules, Last]

{{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4}

and
Values @ GroupBy[rules, Last, Flatten @ #[[All, 1]] -> #[[1, -1]]&]

{{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4}

A: Reap[Sow @@@ (List @@@ rules), _, Flatten[{#2}] -> #1 &][[-1]]

yields:
{{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4}

A: There are many ways, here's one:
KeyValueMap[#2 -> # &] @ GroupBy[rules, Last -> First, Flatten]


text:
Q: Parse quites in text I have this Java code which I use to set in Google sheets text and link:
.setFormulaValue("=HYPERLINK(\"" + get.getUrl() + "\",\"" + get.getTitle() + "\")"))

In general it woking fine but if I have "" into the title I get parse error. Example values:
.setFormulaValue("=HYPERLINK(\"" + http://test.test + "\",\"" + some "title" + "\")"))

Is there some solution to this problem?


text:
Q: java - creating new thread to randomly send data to printwriter I'm messing arount with Bluetooth SPP. I'm using SimpleSPPClient from this thread and i'm using blk wd bc 04b demo board which is configured to just send back anything that is sent to it. I'd like to create new thread which would take PrintWriter as an argument and send data to it randomly. Will this work or does the PrintWriter work only in the thread that created it ? The end result should be that one thread is sending data over bluetooth to the board and the first should read that data.

A: Anything you create before you start a thread can be used in that thread.  If you only use that object in the new thread, you can use it safely.
In the case of PrintWriter you can use locking as well, but you don't need to in your case.


text:
Q: Permutations and Counting problem?
Postal codes in Canada have six characters with alternating letters
  and digits in the form L#L#L#. How many postal codes do not have one
  letter repeated three times?

What I did is $26*10*25*10*24*10=15600000$, which is apparently wrong. The solution in the marking scheme is like this:
Total number of codes: $ 26*10*26*10*26*10=17576000$
Number of codes with the same letter 3 times is: $26*10*10*10=26000$
Number of codes without the repeated letters is: $17576000-26000=1755000$
What is wrong with my logic? And I don't get the method the marking scheme used.

A: Your calculation also does not allow a letter to be repeated even twice.


text:
Q: Count on filefield with None value is not zero I have referred to the similar questions below:
Django - FileField check if None

How to save FileField with None in Django?

Yet I am unable to solve my case.
My model FileField looks like:
document = models.FileField(upload_to=habCompletionDocPath, null=True)

I uploaded a file and deleted.
q = ProgressQty.objects.get(id=id)
q.document = None
q.save()

Now the value of the field is showing None:
In [80]: q.document
Out[80]: <FieldFile: None>

I need to count the number of files uploaded in the table.
However, I am unable to do so because of this:
ProgressQty.objects.exclude(document=None)
<ProgressQty: 269891toubul>

as I was expecting <QuerySet []>
How do I get correct result from this code:
objects.annotate(doc=Count('document'))

A: Well,
I solved my case using:
doc=Count('document', filter=Q(document__gt=0))

Although this might not be the optimal solution.


text:
Q: Color cells in Excel based on certain values I have a list of 200 cells in Excel. I put in names and would like the text color in the cell or the background of the cell to change according to the name written. I use about 25 names.

A: I suggest that you use Excel's conditional formatting feature.   You can look at help to figure out how to do this.  You can also find various
documented examples
Example:

A: Conditional formatting would be best for this, but if you'd like a VBA alternative you can record a macro in the developer tab and edit it under "modules" in the "project" sidebar. Then under ThisWorkbook in the Project sidebar put the code into a SheetChange event.
You need to change the two dropdown menus above the text area, the left one needs to be set to Workbook (only option typically), the right one needs to be SheetChange Then you can use this simple code for as many names as you like. Keep in mind there are many ways to do this.
You can put as many ElseIf's in between the if and else as you like.
Sub Macro

Dim i As Integer
i = 1

    Range("A" & i).Select

    If ActiveCell = "Name1" Then

        ActiveCell.Interior.ColorIndex = 12

    ElseIf ActiveCell = "Name2" Then

        ActiveCell.Interior.ColorIndex = 4

    ElseIf ActiveCell = "Name2" Then

        ActiveCell.Interior.ColorIndex = 11

    Else

        ActiveCell.Interior.ColorIndex = 15

    End If

End Sub

using select in code is not the best programming practice, but this is a small amount of data so it is alright. Hope this helps!


text:
Q: Calling detach() at the end of the thread I have a working thread similar to the following code. In begin_work, it will check whether the working thread is executing before creating a new working thread. However, begin_work will never create the next working thread when the current thread is exited until I call end_work.
I have tried to call detach at the end of the thread and it works fine. Is it safe to call detach at the end of the thread? Or, how can I do to safely create the next working thread without calling end_work before calling begin_work?
class thread_worker {
private:
    std::thread worker;
    // ... other menbers

public:
    thread_worker() {};
    ~thread_worker() { end_work(); };

    void begin_work() {
        if (!worker.joinable()) {
            worker = std::thread { &thread_worker::do_work, this };
        }
    }

    void do_work() {
        // ... access other members ...

        if (exit not by notify) {
            worker.detach();    // can I call detach?
        }
    }

    void end_work() {
        if (worker.joinable()) {
            // notify worker to exit
            worker.join();
        }
    }
};

Edit:
My purpose is to call begin_work without block. If there is one working thread on execution, then the function will return directly or returns an is_working error. Otherwise, create a new working thread seamlessly.
Since std::thread::joinable() always returns true until join or detach is called. As a result, the future call of begin_work will never create the new working thread even though the current working thread has exited.
Therefore, I need a mechanism to automatically detach at the end of the thread.

A:
I have tried to call detach at the end of the thread and it works fine

There's data race in the access to worker - it's undefined behaviour. When begin_work tests worker.joinable(), do_work might be detaching it at the same time (the call to worker.detach()).
You can instead detach the immediately when creating it:
worker = std::thread { &thread_worker::do_work, this };
worker.detach();

However, this can leave multiple threads running at the same time, which contradicts your requirement of running one worker thread at a time (but why only one? that just makes threading pointless).
Instead you can do:
void begin_work() {
    end_work();
    worker = std::thread { &thread_worker::do_work, this };
}

which ensures the previous thread completed.

Based on yuor edit, you only need to check whether you can join without wait - that seems to be reason you want to detach. You can instead do that with an atomic flag. Basically, you just to take care of the data race noted above.
class thread_worker {
private:
    std::thread worker;
    std::atomic_bool w_done {true};

    // ... other menbers

public:
    thread_worker() {};
    ~thread_worker() { end_work(); };

    void begin_work() {
        if (w_done) {
            end_work();
            worker = std::thread { &thread_worker::do_work, this };
        }
    }

    void do_work() {
        // ... access other members ...

        w_done = true;
    }

    void end_work() {
        w_done = false;
        if (worker.joinable()) {
            // notify worker to exit
            worker.join();
        }
    }
};


text:
Q: web scraping multiple pages past a login using python Trying to scrape two tables on separate pages after accessing the site through a login. Tried a few different ways and can't figure it out.
The last attempt showed some promise but only the first data frame was appended to the list of data frames. Something like the following:
from selenium import webdriver
import pandas as pd
import requests
import time
from bs4 import BeautifulSoup as BS

    def text_to_chart (url, table) :

    df_list = []

    driver = webdriver.Chrome(path)
    driver.get(login)
    driver.find_element_by_xpath(password block).send_keys(password)
    driver.find_element_by_xpath(username block).send_keys(username)
    driver.find_element_by_xpath(submit).click()
    time.sleep(10)

    df = pd.DataFrame()

    for url, table in zip(urls, tables) :
        driver.get(url)
        time.sleep(10)
        soup = BS(driver.page_source, 'html')
        new_table = soup.find_all('table',
                  attrs = {'class': table})
        results_list = pd.read_html(str(new_table[0]))
        df = df.append(pd.DataFrame(results_list[0]))

    return df

    def scrape(url, table)
        df_list = []
        df_list = df_list.append(text_to_chart(url, table))

    scrape(url_list, table_list)

So, What Should I do to scrape multiple pages?

A: I suggest you must store the values in a list of dictionaries and then convert it to a dataframe.That will be good and easy.

A: Solved! I made a few changes which resulted in one function that created my list of df's. Then I began the session, logged in, and called the function, saving the output to my variable df_list.
from selenium import webdriver
import pandas as pd
import requests
import time
from bs4 import BeautifulSoup as BS

def text_to_chart (urls, tables) :

    df = []

    for url, table in zip(urls, tables) :
        driver.get(url)
        time.sleep(10)
        soup = BS(driver.page_source, 'html')
        new_table = soup.find_all('table',
              attrs = {'class': table})
        results_list = pd.read_html(str(new_table[0]))
        df.append(pd.DataFrame(results_list[0]))

    return df

driver = webdriver.Chrome(path)
driver.get(login)
driver.find_element_by_xpath(password block).send_keys(password)
driver.find_element_by_xpath(username block).send_keys(username)
driver.find_element_by_xpath(submit).click()
time.sleep(10)

df_list = text_to_chart(url_list, table_list)


text:
Q: get the rank of an element of a boost::multi_index container The code below shows a multi_index container which is indexed by sequence and order.
In my use case elements will be mainly searched by index, and if existing, the next element (by order) is obtained.
My question is, how to get the rank (by order) of obtained next element?
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/identity.hpp>

using namespace boost::multi_index;

typedef multi_index_container <
    int
  , indexed_by<
        sequenced<>
      , ordered_non_unique<identity<int>>
      , ranked_non_unique<identity<int>>
    >
> Ints;

int main() {
    Ints ints;

    auto & sequence=ints.get<0>();
    auto & order=ints.get<1>();

    sequence.push_back(2);
    sequence.push_back(-1);
    sequence.push_back(5);
    sequence.push_back(6);

    auto it = order.find(2);
    if (it!=order.end()) {
        std::cout
            << "next to "
            << *it
            << " by sequence is "
            << *(++(ints.project<0>(it)))
            << std::endl
        ;
        std::cout
            << "next to "
            << *it
            << " by order is "
            << *(++(ints.project<1>(it))) //++it is good too
            << std::endl
        ;
        std::cout
            << "rank of next by sequence is "
            // << ??? ints.rank<???>(???)
            << std::endl
        ;
        std::cout
            << "rank of next by order is "
            // << ??? ints.rank<???>(???)
            << std::endl
        ;
    }
}

A: @sehe's answer is perfectly valid but runs in linear time. If you want better performance, consider defining your index #0 as random_access and #1 as ranked_non_unique (index #2 is redundant):
typedef multi_index_container <
    int
  , indexed_by<
        random_access<>
      , ranked_non_unique<identity<int>>
    >
> Ints;

so that you can write:
std::cout
    << "rank of next by sequence is "
    << ints.project<0>(it)-sequence.begin()+1 // O(1)
    << std::endl
;
std::cout
    << "rank of next by order is "
    << order.rank(it)+1 // O(log n)
    << std::endl
;

A: Assuming you want some kind of "index into" or "offset from begin" in the sequenced index:
if (it!=order.end()) {
    auto rank_of = [&](auto it) {
        return std::distance(sequence.begin(), ints.project<0>(it));
    };

    auto seq_next = std::next(seq_it);
    auto ord_next = std::next(it);

    if (seq_next!=sequence.end())
    {
        std::cout << "next to                     " << *it << " by sequence is " << *seq_next << std::endl;
        std::cout << "rank of next by sequence is " << rank_of(seq_next) << std::endl;
    }

    if (ord_next!=order.end())
    {
        std::cout << "next to                     " << *it << " by order is " << *ord_next << std::endl ;
        std::cout << "rank of next by order is    " << rank_of(ord_next) << std::endl;
    }
}

Without polymorphic lambdas you should write it out


text:
Q: "Click" on website button I want to parse a list in a website with Java. I already know how to parse the list with Jsoup - so this part is done and working.
However, to show the list in the web page I need to press a button and I don't know how to do that with Java. I already found a similar question on SO: Programmatically click a webpage button. I think I could use HttpURLConnection and KVP for this but I don't know how to get it to work.
The list selector looks like this:

I would like to press the Show all button.
Code which I found in the html file:

        <button type="button" id="clearselection" class="btn btn-knx" style="float: right; margin: 0px">Clear selection</button>

        <button type="button" id="showall" class="btn btn-knx align-right" style="float: left">Show all</button>

Does anybody know how this is done?
..it is btw not only one button which I need to press in this website otherwise I would do it manually. Once I know how it is done with one button I will be able to figure it out for the other ones too.
UPDATE:
I want to point out that I don't have access to the HTML file. I basically want to simulate a button click of a website visitor. I'm sorry I was not clear.
UPDATE-2:
I have just now started working on this again. I found the Javascript code for the button in the web page:
$('#showall').on('click', function () {
            $('.mask').show();
            $('#name').attr('value', '');
            $("#letter option").removeAttr('selected');
            $("#letter option[value='']").attr('selected', true);
            $.ajax({
                url: '/src/international/Data/partListAjax',
                type: 'POST',
                dataType: "html",
                data: {
                    data: $('#filterForm').serialize(),
                    wTexts: {"Company":"Company","Country":"Country","Name":"Name","Total":"Total","search":"Search","matches_found":"matches found","search_no_results":"Your search did not match any results."},
                    national: 'null',
                    currentProject: 'nma-en'
                },
                success: function (data) {
                    if (data.indexOf("Allowed memor") >= 0) {
                        $('#accordion2').html("
Please use our search engine
");
                        $('.mask').hide();
                        $('#clearselection').attr('disabled', 'disabled');
                        $('#showall').attr('disabled', 'disabled');
                    } else {
                        $('#accordion2').html(data);
                        $('.mask').hide();
                        $('#clearselection').attr('disabled', 'disabled');
                        $('#showall').attr('disabled', 'disabled');
                    }
                }
            });
        });

If invoking the button function doesn't work, I will try to directly send/trigger the Ajax command which is included in the function.

A: LordBullington, i have done this on my website as well, below solution is working perfectly for me.
First you need send a variable to the UI.
if you are using servlet, you can do that by
request.setAttribute("clickbutton", "yes");

if you are using Spring, you can do that by
Map<String, Object> model = new HashMap<String, Object>();
model.put("clickbutton", "yes");
return new ModelAndView("yourView", model);

Then in your html, keep a hidden variable to receive the variable sent from JAVA.
<input type="hidden" id="clickbutton" value="${clickbutton}">

Then use Jquery to trigger the button on page load. Make sure this jquery code is after the hidden input tag.
$( document ).ready(function() {
    if(('#clickbutton').val()=='yes') {

       //use your button id here
       $("#youButtonIdHere").click();
    }
});

A: I finally got it to work by using Selenium WebDriver. I just saw one tutorial on YouTube and within some hours everything was done. Incredible. :)


text:
Q: php multidimensional array I want to create a twodimensional array in php. What is the correct syntax of creating an empty multidimensional array in php.
Secondly I want to create 7 two dimensional array in for

A: Take a look at the PHP online manual. The first example shows you how to create a multi dimensional array.
http://php.net/manual/en/function.array.php
<?php
$twoDimensionalArray = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
?>

To do what you want in a for loop, you can do so like this
// the following creates a 2d array. the first dimension contains 7 arrays of numbers 1 to 10
$firstDimension = array();
for ($i = 0; $i < 7; $i++) {
    $firstDimension[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}

A: Unlike some other langauges (such as standard C), arrays in PHP are "sparse" (i.e.: they only take up the space they need) so you can define a multi-dimensional array simply via:
$testArray = array();

(i.e.: You don't need to reserve the amount of space you're going to require.) However, more usefully, you can add values as follow:
$testArray = array();
$testArray[0][0] = "Hello";
$testArray[0][1] = "World";
...

That said, I'd recommend reading the PHP array manual page, as you might want to use named indexes, etc. and it has better examples.

A: Multi-dimentional arrays are like regular arrays but the value to some (or all) or their keys are arrays.
For example you can create a two dimentional array like this:
$arr = array();
$arr[1] = array(1 => 'one', 2 => 'two');

And you can use it like this:
echo $arr[1][1]; //which prints "one"

A: To create empty multidimensional array in PHP, you can do the following.
$arr_1 = array();

Yes. That's all. You can insert any type of data or array in it. There is no specific declaration of various arrays in PHP.
Now, suppose I want to insert data inside this multidimensional array $arr_1. I need to create an array of addresses. Each address item will have city, state and country.
You can do this as follows:
$arr_1[0] = array(
  'city' => 'Gurgaon',
  'state' => 'Haryana',
  'country' => 'India'
);
$arr_1[1] = array(
  'city' => 'Los Angeles',
  'state' => 'California',
  'country' => 'United States'
);
$arr_1[1] = array(
  'city' => 'Melbourne',
  'state' => 'Victoria',
  'country' => 'Australia'
);

You can create as many arrays as you want in this way.
If you want to learn more about PHP arrays (Indexed, Associative, Multidimensional), visit PHP arrays explained with examples - Webolute Blog

A: <?php
$twoDimensionalArray = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
?>


text:
Q: Getting IP addresses from an MPI program on a supercomputer I have the following MPI Program:
 program hello
    include 'mpif.h'

    integer my_pe_num,errcode
    call MPI_INIT(errcode)
    call MPI_COMM_RANK(MPI_COMM_WORLD,my_pe_num,errcode)
    print *, 'Hello from ', my_pe_num, '.'
    call MPI_FINALIZE(errcode)

 end program hello

It's fine.  Now I would like to get the IP address from each process to go along with the rank.  I looked at MPI_Get_Processor_name, but that's not what I want.
When I run this, it is via batch on a supercomputer.  The actual step that runs the program is:
mpirun -np 4 ./hello


text:
Q: Why use stateless session beans for transaction demarcation I frequently find myself converting an @AppplicationScoped bean into a SLSB bean just so that i can use @TransactionalAttribute.
What are the advantages of doing this over creating a custom CDI interceptor to begin and end transactions that i can use on any bean?

A: Actually there is already implementation of @Transactional in new CDI spec which came together with Java EE 7, so you can apply it to all Managed Beans in your application and it works the same way as the @TransactionalAttribute did. Check the documentation for more info.
CDI vs EJB
Difference is quite easy, always use CDI if you don't need things like scheduling, remote beans, asynchronous behaviour or security. See any kind of tutorial for what are these features and how to implement them. Also note that if you use CDI then every class in your application will effectively turn in Managed Bean including EJB beans.

A: EJB will become an specialized set of services provided by the cdi container.
So, to resolve your question:
EJBs by default are capable of some things where cdi dont:

*

*Timers

*Asynchronous, transactional execution with Future support

*Pooling: important for throttling and prevention of denial of service attacks

*Monitoring - all EJBs are exposed via JMX and can be so monitored with JConsole

*Declarative, "Convention Over Configuration" transactions. Without EJB 3 you will end up in a considerable bloat.

So, if you are only using the transactional aspect, well, there is no really big difference between a cdi+interceptor or a EJB.
source: http://www.adam-bien.com/roller/abien/entry/cdi_with_or_without_ejb


text:
Q: My Angular 10 App deployed in Azure is loosing its styles when refreshed I have started working on an Angular 10 application using DevExtreme UI Widgets. I deployed a demo version in our Azure Cloud but while I was playing with it, I noticed a strange behavior. It seems that I lose my styles when I refresh.
For example, this is how the login page should be displayed:

If I refresh the URL without entering my login credentials, the page changes and gets displayed like this:

When I login, the bad or good styles are carried over. For example, the landing page should be displayed like this:

If I refresh the screen here, I also see the styles being altered. This is how the landing page gets displayed when the styling is lost:

When I lose the styling if I keep refreshing the page over and over again, eventually I regain the styles and my application starts being displayed as intended.
Any idea what causes the styles to be lost? Any suggestion would be greatly appreciated.
Thanks,
Ed

A: Regarding the deployment of Angular projects, I have encountered various problems. I am willing to share it with you and hope it will help you.
Troubleshooting steps:
Solution 1.
You can deploy it via Azure Pipelines CI/CD without using the vscode to deploy webapp.
Maybe smth wrong with VS Code plugin, as it is in preview
Solution 2.
Use github for continuous deployment. It is recommended to create a webapp and choose the Linux operating system.
Solution 3.
It is recommended to use FTP to publish the build folder after the project npm build.

A: This issue was resolved. After further investigation, it turns out that the problem had nothing to do with Azure Cloud deployment. I use DevExtreme UI widgets in my application and the application is based on their Angular Template.
I tried the website using Chrome, Edge and Firefox. The issue described above only happened in Chrome. DevExpress tech support pointed me to this support ticket.
After following the recommendations in the workaround and a redeployment, my app looks fine even in Chrome.
Thanks for everyone trying to help.
Ed


text:
Q: Activity Timeline is not Displaying in Community I've followed this Knowledge Article, and nothing seems to work. https://help.salesforce.com/articleView?id=000350558&type=1&language=en_US&mode=1
Following the KA: I went to Setup -> Record Page Settings -> And have "Activity Timeline" checked. I also went My Avatar -> Record Page Settings -> And have "Activity Timeline" checked.
On an "Activity" tab on a Contact record page I see an Activity Timeline just fine. I can't figure out why it doesn't show in a Community. After the community is published the component is completely absent. I am testing as System Administrator, and have assigned/created tasks and events to myself. Not sure what else to look for. Org Wide Sharing Rules show "private". I changed it to "Controlled by Parent" but nothing helps. This is also "Health Cloud" if that makes a difference.
Fig 1: Works On a record page

Fig 2. Component dragged on to a page

Fig 3 - Org Wide Sharing rules

A: As the error message suggests, there is no relevant data for the "activity" as it is not mapped to any specific record.
You need to add the Activity component to the "record detail" page in the community for it to show the information related to the specific record.
The same applies to other components like Feed, Feed publisher, Feed compact...
Attached a screenshot from my org where I could add the component without the error.


text:
Q: JDK8 for NetBeans 12.2? I'm trying to install JDK8 as a platform on NetBeans 12.2, but I keep getting this error message:
"Cannot detect and install the selected platform. The java or javac may not be executable."
Is there a way around this? Or is there a version of JDK8 that won't yield this error message?
Further: I should have mentioned that I'm on MACOS Big Sur.
Here's what I get with java -version in Terminal:
java version "15.0.2" 2021-01-19 Java(TM) SE Runtime Environment (build 15.0.2+7-27) Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing)
And here's what I get with javac -version:
javac 15.0.2

A: You are probably getting this message because the JDK executables haven't been added to your path as environment variables. Directly from the official java website, here's a guide on how to fix this problem.


text:
Q: Hibernate @ManyToOne violates foreign key constraint I have person class which contains another object Title.
public class Person {

public Person(){
    titleId=new Title();
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private LongId;

@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER,targetEntity=Title.class)
@JoinColumn(name = "titleId", referencedColumnName = "titleId",columnDefinition="int",nullable=false)
private Title title;

...
...
}

@Entity
public class Title {
@Generated(GenerationTime.INSERT)
@Column(columnDefinition = "serial")
private int titleId;

@Id
private String title; }

When I try to insert Person object with below detail.
  Person p=new Person();
  Title t=new Title();
  t.setTitle("Mr.");
  p.setName("abc");
  p.setTitle(t);
  sessionFactory.getCurrentSession().saveOrUpdate(p);

It's working fine and inserting title and person
But when I try to insert another person with same title, it fails
Person p=new Person();
Title t=new Title();
t.setTitle("Mr.");
p.setName("pqr");
p.setTitle(t);
sessionFactory.getCurrentSession().saveOrUpdate(p);

It's giving exception as below

org.postgresql.util.PSQLException: ERROR: insert or update on table
  "person" violates foreign key constraint
  "fk_9s5vdsvlj3nqy8btf3u1wgvqf"   Detail: Key (titleid)=(0)
  is not present in table "title".

I can pass titleId and it will work, however there are chance that I don't have titleId available.

A: This has happened to me because I had meddled with various table names and the database was retaining old foreign key constraints (from previous test builds).
Try to drop the tables from your DB and let Hibernate re-create them.

A: First You have to define OneToMany relation in Title entity something like below
@Entity
public class Title {
   @OneToMany(mappedBy="title", cascade = CascadeType.ALL,     orphanRemoval=true, fetch=FetchType.LAZY)
private List<Person> persons = new ArrayList<Person>();
}

Then to add person and Title you have to add person on title persons field.
Person p=new Person();
p.setName("pqr");
Title t=new Title();
t.setTitle("Mr.");
t.addPersons(p);
p.setTitle(t);
sessionFactory.getCurrentSession().saveOrUpdate(t);

A: You got foreign key violation because you use title as id ( primary key of entity Title). Try this:
 @Entity
 public class Title {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int titleId;

    private String title;
 }

A: You have an error on your definition of the person ID. You have:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private LongId;

I think it should be:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;

Maybe it cames from here ? :)


text:
Q: how to format long string to add a space after each number I have this long string
"Ab1ac2axd3nxn70-00-0-0"
For the life of me I cannot figure out how to separate that string in java to look like this.
"Ab1 ac2 axd3 nxn7 0-0 0-0-0"
I am thinking I need to use delimiters but I don't know the code for the desired format I want and also don't know how to correctly write it.
It might help to know that zeros will only occur as the form "0-0" or "0-0-0" if it is attached to letters it will only be like this ab30-0 now I don't want to put spaces between the dashes and the zeros but if this occurs"0-00-0-0" I want it to be formatted like this "0-0 0-0-0"

A: This will solve your problem.  There may be a more elegant solution, but this definitely works:
public class Delimiter {
  public static void main(String[] args) {
    String input = "Ab1ac2axd3nxn70-00-0-0";
    int l = input.length() - 1;
    char[] inputChars = input.toCharArray();
    StringBuilder output = new StringBuilder();

    for (int i = 0; i < l; i++) {
      char c = inputChars[i];
      output.append(c);

      if (Character.isDigit(c) && inputChars[i+1] != '-')
        output.append(' ');
    }

    output.append(inputChars[l]);
    System.out.println(output.toString());
  }
}


text:
Q: simple inclusion exclusion problem Here is the question.
Each of the 90 students participated in at least one of the three track events A, B and C. If 20 students participated in A, 40 students participated in B, and 60 students participated in C, and if 5 students participated in all three events, how many students participated in at least two of these events?
Now, I applied the simple inclusion exclusion principle here -
$|A \cup B \cup C| = |A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C| \\ |A \cap B| + |A \cap C| + |B \cap C| = |A| + |B| + |C| + |A \cap B \cap C| - |A \cup B \cup C|$
This gives 35 as the result. However the current result is 20 (as per attached explanation). What am I doing wrong here?

A: The problem is that $|A \cap B| + |A \cap C| + |B \cap C|$ isn't the number who participated in at least two events: every student who participated in all three events got counted in $|A\cap B|$, again in $|A\cap C|$, and yet a third time in $|B\cap C|$. Those five students have therefore been counted three times each. In the notation of the attached explanation, $$|A \cap B| + |A \cap C| + |B \cap C|=(b+e)+(d+e)+(f+e)=b+d+f+3e\;.$$
If you want the number who participated in at least two events, you want to count each of those five people once, not three times, so the correct answer is $35-2\cdot5=25$. If you want the number who participated in exactly two events, you don't want to count those five people at all, so the correct answer is $35-3\cdot5=20$. The attached explanation gives the answer to this second question, not to the one that you asked at the beginning of the post.


text:
Q: showing a grandtotal of values in a field good pm. i was thinking is it possible to show the summation or grand total of a selected field in the table and with relation to date:
for example is i want to know the total beer consumption of my hotel every month.
i have here my table on services:
[services_id[pk],
customer_id[fk],
date_in,date_out,room_type,room_number,
extra_ref,
extra_bed,extra_snack,
extra_beer,extra_softdrinks,
extra_pillows,extra_breakfast,
extra_snack_q,
extra_beer_q,
extra_softdrinks_q,
extra_pillows_q,
extra_breakfast_q]

can you give some advice on how can i get it.
thanks in advance:
-renz

A: SELECT SUM(beer_amount) as monthly_beer_amount
FROM [DATABASE].[TABLE]
WHERE beer_sold_date BETWEEN '20110201' AND '20110228'

[EXTRA INFO]
Also I believe that the best way to organize this table is to separate out this table into a few other tables. Store customer info in the first table such as
[customer_id, customer_name, date_in, date_out, room_type, room_number].
1, Bob, 20110101, 20110110, big, 200
2, Joe, 20110101, 20110110, small, 202
....

And have another table named something like room_items which would have the following,
[id, item_name]
1, BEER
2, BED
3, SNACK
...

And then another table named room_purchases which will have the following,
[customer_id, purchase_id, amount, date....]
1, 1, 10, 20110101
2, 3, 5, 20110101
3, 1, 9, 20110101
....

This would help you to do a join on all three tables and they would be more normalized in this way.
SELECT SUM(t2.amount) as beer_amount
FROM customers as t1
LEFT JOIN room_purchases as t2 ON t1.customer_id = t2.customer_id
WHERE t2.purchase_id = 1 AND t2.date BETWEEN 20110101 AND 20110131

A: SELECT DATE_FORMAT(date_in,"%m-%Y") AS month,SUM(extra_beer) AS beers
FROM your_table
GROUP BY month

this will return something like this:
02-2011 | 43
03-2011 | 52

if you want to limit the query depending on the date just add a WHERE constraint before the GROUP BY


text:
Q: Erro system indexoutofrangeexception Dim form As New Form5
    Dim sqlConString As String = "Server=localhost\TESTE;Database=tempTest;User Id=sa;Password=123"
    Form7.clientNIF = DataGridView1.CurrentRow.Cells(0).Value.ToString()
    Try
        Using con = New SqlConnection(sqlConString)
            con.Open()
            Using cmd = con.CreateCommand
                cmd.CommandText = "SELECT * FROM Computador Where NIFcliente = @NIF"
                cmd.Parameters.AddWithValue("@NIF", DataGridView1.CurrentRow.Cells(0).Value.ToString())
                Dim asrow As Boolean
                asrow = False
                Dim reader = cmd.ExecuteReader
                While (reader.Read())
                    asrow = True
                End While
                If asrow = True Then
                    Form7.ShowDialog()
                    Me.Close()
                Else

                    cmd.CommandText = "SELECT * FROM Clientes where NIF = @NIF"
                    cmd.Parameters.AddWithValue("@NIF", DataGridView1.CurrentRow.Cells(0).Value.ToString())
                    form.NIF1.Text = reader.GetString(reader.GetOrdinal("NIF"))
                    form.Nome.Text = reader.GetString(reader.GetOrdinal("Nome"))
                    form.Contato.Text = reader.GetString(reader.GetOrdinal("Contato"))
                    form.Morada.Text = reader.GetString(reader.GetOrdinal("Morada"))
                    form.CP.Text = reader.GetString(reader.GetOrdinal("CP"))
                    form.Cidade.Text = reader.GetString(reader.GetOrdinal("Cidade"))
                    form.Pais.Text = reader.GetString(reader.GetOrdinal("Pais"))
                    form.Email.Text = reader.GetString(reader.GetOrdinal("Email"))
                    form.dtderegisto.Text = reader.GetString(reader.GetOrdinal("dtderegisto"))
                    form.ShowDialog()
                    Me.Close()

                End If

            End Using
        End Using
    Catch ex As SqlException
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
    End Try
    Me.Close()

Erro em

form.NIF1.Text = reader.GetString(reader.GetOrdinal("NIF"))  system indexoutofrangeexception

A: Foi necessário fechar a ligação anterior com o reader e abrir uma nova
Dim form As New Form5
    Dim sqlConString As String = "Server=localhost\TESTE;Database=tempTest;User Id=sa;Password=123"
    Form7.clientNIF = DataGridView1.CurrentRow.Cells(0).Value.ToString()
    Try
        Using con = New SqlConnection(sqlConString)
            con.Open()
            Dim asrow As Boolean
            asrow = False
            Using cmd = con.CreateCommand
                cmd.CommandText = "SELECT * FROM Computador Where NIFcliente = @NIF"
                cmd.Parameters.AddWithValue("@NIF", DataGridView1.CurrentRow.Cells(0).Value.ToString())

                Using reader = cmd.ExecuteReader
                    While (reader.Read())
                        asrow = True
                    End While
                End Using

            End Using
            Using cmd = con.CreateCommand
                If asrow = True Then
                    Form7.ShowDialog()
                    Me.Close()
                Else

                    cmd.CommandText = "SELECT * FROM Clientes where NIF = @NIF"
                    cmd.Parameters.AddWithValue("@NIF", DataGridView1.CurrentRow.Cells(0).Value.ToString())
                    Dim reader = cmd.ExecuteReader()
                    reader.Read()
                    form.NIF1.Text = reader.GetString(reader.GetOrdinal("NIF"))
                    form.Nome.Text = reader.GetString(reader.GetOrdinal("Nome"))
                    form.Contato.Text = reader.GetString(reader.GetOrdinal("Contato"))
                    form.Morada.Text = reader.GetString(reader.GetOrdinal("Morada"))
                    form.CP.Text = reader.GetString(reader.GetOrdinal("CP"))
                    form.Cidade.Text = reader.GetString(reader.GetOrdinal("Cidade"))
                    form.Pais.Text = reader.GetString(reader.GetOrdinal("Pais"))
                    form.Email.Text = reader.GetString(reader.GetOrdinal("Email"))
                    form.dtderegisto.Text = reader.GetString(reader.GetOrdinal("dtderegisto"))
                    form.ShowDialog()
                    Me.Close()

                End If
            End Using
        End Using
    Catch ex As SqlException
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
    End Try
    Me.Close()


text:
Q: VC2005 got slower after installing VC2008 I have installed VS2008 SP1 and now when I compiled solution (a mix of C++ and managed C++ projects) it takes much more time to embed the manifest into .dll.
Is it a known issue? Any workarounds/directions please.

A: This is not a known issue.  Time to defrag your hard drive.


text:
Q: (XNA) Switching Render Target causes performance hit I have the following problem. I'm trying to cut parts of the texture using the Stencil, AlphaTestEffect and RenderTarget, but this causes a huge performance hit for me. Without it, I have close to 30fps, while with it, it drops to 4fps.
I was trying to isolate the root of the problem, and while with it, I noticed that even if I do nothing, but switch the active render target to my custom render target, and then right afterwards if I switch it back to backBuffer, my fps drops by close to 10fps's. All I do is this:
            graphicsDevice.SetRenderTarget(renderTargetA);
            graphicsDevice.SetRenderTarget(null);

While the render target is created that way:
        renderTargetA = new RenderTarget2D(KnightGame.CurrentGame.ScreenManager.GraphicsDevice, 800, 480,
                                           false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8,
                                           0, RenderTargetUsage.PreserveContents);

I tried using DiscardContents, different sizes, but it always drops the fps. I commented all the parts that have to do with cutting off the part of the image and still just with switching the render target it makes a hit to the performance. Can anybody direct me to the cause of this problem?
Lucas


text:
Q: After loop all elements same I want to assign value to elements of my array. after running this, all elements of ListResults are same as last element of ListROI.
ListResults = new DataPoint[nROIrow];
DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
{
   TempRes.X = ListROI[i].X;
   TempRes.Y = ListROI[i].Y;
   TempRes.u = dispROIcorr[i, 0];
   TempRes.v = dispROIcorr[i, 1];

   ListResults[i] = TempRes;

   disp.Xpix = ListResults[i].X;
   disp.Ypix = ListResults[i].Y;
   disp.X = ListResults[i].X;
   disp.Y = ListResults[i].Y;
   disp.U = ListResults[i].u;
   disp.V = ListResults[i].v;

   List.Add(disp);
   bSAVE.Enabled = true;
}

A: You only create a new DataPoint(); one time. So you end up with an array full of references to that same single instance.
The simple fix:
ListResults = new DataPoint[nROIrow];
//DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
{
   DataPoint TempRes = new DataPoint();
   ...

   ListResults[i] = TempRes;

   var disp = new ...
   disp.Xpix = ListResults[i].X;
   ....

   List.Add(disp);
}

A: The problem with your code is that you are reusing the TempRes variable. When you perform the "List.Add" you are just adding a reference to it, and all these references are (obviously) the same. You also modify it, so each identical reference logically points to the same identical data.
Instead, write:
System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
   {
     DataPoint TempRes = new DataPoint();
     ...

Note also that ArrayList is generally considered to be deprecated since .NET 2.0 and you should be using List<T> instead.

A: do
disp = new ... // whatever

before assigning values to disp[i].???
actually what is happening is all the references in your List are referring to disp which is the single object that was created outside the for loop, hence all items in List are pointing to same disp object, hence same values.


text:
Q: ICEfaces: How to pass parameters from one page to another I have this simple scenario which doesn't work: I use icefaces and i have a simple page with some inputTexts and a submit button, this button will redirect to another page that will display the values of these inputTexts... my question is how can i get the values of these inputTexts from the request and display them in another page?
When i use the following API in the other page backbean, i get only the name of the page that holds the inputTexts:
FacesContext.getCurrentInstance().getExternalContext().getRequestMap();

I really did spent alot of time trying to get this thing to work, so any help will be appreciated.. THx
my page code is:
<ice:form id="form1">

            <ice:outputText value="Name"></ice:outputText>

            <ice:inputText id="name" value="#{newContest.name}"></ice:inputText>

            <ice:outputText value="End Date"></ice:outputText>
            <ice:inputText id="endDate" value="#{newContest.endDate}"></ice:inputText>

            <ice:outputText value="private? (only you can see the entries)"></ice:outputText>
            <ice:inputText id="private" value="#{newContest.isPublic}"></ice:inputText>

            <ice:outputText value="Price"></ice:outputText>
            <ice:inputText id="price" value="#{newContest.price}"></ice:inputText>

            <ice:outputText value="Description"></ice:outputText>
            <ice:inputTextarea id="description" value="#{newContest.description}"></ice:inputTextarea>

<ice:commandButton value="proceed to payment" style="color:blue" action="#{newContest.createContest}"></ice:commandButton>

A: You can bind another bean with current one as a managed property in faces-config.xml as follows.
<managed-bean>
        <managed-bean-name>newContest</managed-bean-name>
        <managed-bean-class>com.newContest</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>

        <managed-property>
        <property-name>anotherBackingBean</property-name>
            <property-class>com.AnotherBackingBean</property-class>
            <value>#{anotherBackingBean}</value>
    </managed-property>
    </managed-bean>

<navigation-rule>
          <navigation-case>
             <from-outcome>view-anotherBackingBean</from-outcome>
            <to-view-id>/jsp/another-page.jspx</to-view-id>
        </navigation-case>
    </navigation-rule>

Bean Content
Class NewContest {

public AnotherBackingBean anotherBackingBean;

//-- set/get & other methods

public String redirectToAnotherBackingBean(){

        anotherBackingBean.setSomeObject(object);

        //-- set custom fields

        return "view-anotherBackingBean";
     }

}

Then you can get your fields directly available in other bean which have been set in current bean.


text:
Q: run multiple Jars in a given order with nodejs I want to run two jars one after the other with nodejs but it seems like my program only stars the first jar :
The exec function :
execute a single shell command where "cmd" is a string
exports.exec = function(cmd, cb){
    // this would be way easier on a shell/bash script :P
    var child_process = require('child_process');
    var parts = cmd.split(/\s+/g);
    var p = child_process.spawn(parts[0], parts.slice(1), {stdio: 'inherit'});
    p.on('exit', function(code){
        var err = null;
        if (code) {
            err = new Error('command "'+ cmd +'" exited with wrong status code "'+ code +'"');
            err.code = code;
            err.cmd = cmd;
        }
        if (cb) cb(err);
    });
};

Execute multiple commands in series this could be replaced by any flow control lib :
exports.series = function(cmds, cb){
    var execNext = function(){
        exports.exec(cmds.shift(), function(err){
            if (err) {
                cb(err);
            } else {
                if (cmds.length) execNext();
                else cb(null);
            }
        });
    };
    execNext();
};

My use case :
shell.series([
  `java -jar ${appDir}integration-tests/e2e-tests/tests/perf/uxcast-stub-0.27.0-jar-with-dependencies.jar`,
  `java -jar ${appDir}integration-tests/e2e-tests/tests/perf/uxcast-app-0.27.0.jar`,
], err => {
  if (err !== null) {
    console.log('UXCAST ERROR -> ' + err);
    return;
  }
  expect(startBrowser()).toBe('stuff');
  done();
});

What I'm doing wrong ?


text:
Q: why when i send data to another activity and in other activity i want get it project stop? this is some code of my first class
   result = "ok&rent##18##20000000##80##500000##2##shofaj --- kaf parkeet ....##http://www.studentuniverse.com/student-blog/wp-content/uploads/2013/07/iStock_000017716462Medium-e1374689640445.jpg##http://www.studentuniverse.com/student-blog/wp-content/uploads/2013/07/apps.jpeg## " ;
            String []respon = result.split("&");

                Intent in = new Intent(getApplicationContext(), Show_item_select.class);
                in.putExtra("url", respon[1]);
                in.putExtra("code", Select_Data.get_id());
                in.putExtra("itm",itm);
                in.putExtra("urls", urls);
                startActivity(in);

this is some code of my secend class
   String s= getIntent( ).getStringExtra("url");
            code = getIntent().getStringExtra("code");
            itm =getIntent().getIntExtra("itm",0);
            urls = s.split("##");
            urls_all = getIntent().getStringExtra("urls");

when progrom go to secend class and read first line program stoped and show page that write Source not found and this is topic :
    ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2032.

DalvikVM[localhost:8602]
    Thread [<1> main] (Suspended)
        ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2032
        ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2135
        ActivityThread.access$700(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 140
        ActivityThread$H.handleMessage(Message) line: 1237
        ActivityThread$H(Handler).dispatchMessage(Message) line: 99
        Looper.loop() line: 137
        ActivityThread.main(String[]) line: 4921
        Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
        Method.invoke(Object, Object...) line: 511
        ZygoteInit$MethodAndArgsCaller.run() line: 1038
        ZygoteInit.main(String[]) line: 805
        NativeStart.main(String[]) line: not available [native method]
    Thread [<10> Binder_2] (Running)
    Thread [<9> Binder_1] (Running)
    Thread [<11> Binder_3] (Running)
    Thread [<12> AsyncTask #1] (Running)
    Thread [<13> AsyncTask #2] (Running)
    Thread [<14> AsyncTask #3] (Running)

anyone khnow why this happen ?

A: Try and change
String s = getIntent().getStringExtra("url");

for
String s = getIntent().getExtras().getString("url");

It's also a good practice to check that the extras bundle is initialized, like this.-
String s = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
    s = extras.getString("url");
}

Finally, you should consider using constants for your extras names, just to make sure you don't have typo issues in the future.


text:
Q: Profiling spark executor memory I have been wanting to find a good way to profile a spark application's executor when its run from a jupyter notebook interface. I basically want to see details like what is the heap memory usage, young  and perm gen memory usage etc through time for a particular executor(ones that fail atleast).
I see many solutions out there but nothing that seems mature and easy to install/use.
Are there any good tools that let me do this easily?


text:
Q: creating template/custom User Control in winforms custom user control may not be the correct wording as it brings me to placing something in the toolbox. What I think I am really looking for is some option that allows me to do an add new item but instead of selecting "User Control" I would select "Menu Panel"
Say I wanted to create a new user control that I name NetworkConnectionView the code currently look like this:
public partial class NetworkConnectionView : UserContrl

however what I am hoping for is to use the "add new item" option to get a class signature that would look like this:
public partial class NetworkConnectionView : MenuPanel

The main reason for doing this is to inherit the transparency, size and other elements that are used repeatedly but also so I can have a function that has a parameter of MenuPanel. So something like this:
    private void InsertMenuOption(MenuPanel curMenuPanel, string name){
        curMenuPanel.Name = name
        Button menuOptionBtn = new Button()
        // initialization of menuOptionBtn parameters...
        menuOptionsPanel.controls.Add(menuOptionBtn )
        // ...
    }

EDIT:
based on Jimi's comment I was able to export a template however when I do an add item I am still seeing that it is inheriting directly from UserControl. With that said, it loads into my project with the expected size, backcolor etc. I am just not showing that it inherits from MenuPanel instead of UserControl.
Image of the template that is added to the project via "Add Item"
Image of added item signature
Desired signature then MenuPanel inherits from UserControl

A: I was way over complicating this. What I ended up needing to do was to create a "template" user control that I named MenuPanelView which inherited from user control. after setting all the desired parameters (i.e. size, transparency, etc) I then when into any object that I wanted to inherit from MenuPanelView and simply overwrote the UserControl with MenuPanelView.
So this:
public partial class TestUserControl : UserControl
{
    public TestUserControl()
    {
         InitializeComponent();
    }
}

Would just become this (and work as desired):
public partial class TestUserControl : MenuPanelView
{
    public TestUserControl()
    {
         InitializeComponent();
    }
}


text:
Q: Tensorflow Object Detection API - Get Coordinates of Boxes detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(MODEL_PATH, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

gameWindow = [0, 0, 200, 300]

while True:
    image = np.array(ImageGrab.grab(bbox=(gameWindow[0], gameWindow[1], gameWindow[2], gameWindow[3])))
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image_expanded = np.expand_dims(image_rgb, axis=0)

    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: image_expanded})

    vis_util.visualize_boxes_and_labels_on_image_array(
        image,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.60)

    frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # print("Made it ")
    cv2.imshow('Detect the dumb trees', frame)

    if cv2.waitKey(1) == 27:
        break
cv2.destroyAllWindows()

I'm trying to get the x1, y1, x2, y2 coordinates of the boxes that the API draws using vis_util.visualize_boxes_and_labels_on_image_array()
I've tried looking into detection_boxes but i get a bunch of values which I have no idea what they mean.
Could someone provide me a solution please? Thanks

A: The numbers in detection_boxes are [ymin, xmin, ymax, xmax] and they are normalised to the size of your image since "use_normalized_coordinates=True" in your script.
Each index in the detection_boxes correspond to the same index in the detection_scores and Detection_classes. So you have to find what is the object you want at what threshold score in order to get the index for the detection_box.
Example:
boxes=[]
    for i in range(len(detection_boxes)):
        if detection_classes[i]=3 and detection_scores[i]>0.9:
             boxes.append(detection_boxes[i])

The score threshold set here is 0.9 and the class i am looking for is 3. Those box that match are stored in an array call boxes.

A: This question seems similar to yours:
How to find bounding boxes coordinates in Tensorflow Object Detection API
And someone has posted a simple code solution.
There is a another way, where you can manipulate the visualize_boxes_and_labels_on_image_array() function to return the coordinates
Something like:
coordinates_list = []
for box, color in box_to_color_map.items():
  ymin, xmin, ymax, xmax = box
  height, width, channels = image.shape
  ymin = int(ymin*height)
  ymax = int(ymax*height)
  xmin = int(xmin*width)
  xmax = int(xmax*width)
  coordinates_list.append([xmin, ymin, xmax, ymax])

return coordinates_list


text:
Q: cocoon, nested can't create and remove In Rails 4 I want to create an order including product in a devise seller, I use gem "cocoon"
class Seller < ActiveRecord::Base
has_many :orders

class Order < ActiveRecord::Base
belongs_to :seller
has_many :products
accepts_nested_attributes_for :products, allow_destroy: true

class Product < ActiveRecord::Base
belongs_to :order

and I want to create in new.html but the seller don't need to sign in, I hope it can via URL
 new.html
<%- model_class = Order -%>
<%= simple_form_for @order, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.simple_fields_for :products do |product| %>
<%= render 'product_fields', :f => product %>
<% end %>
<%= link_to_add_association 'add product', f, :products %>
<%= f.button :submit, :class => 'btn-primary' %>
<% end %>

in product_fields

<%= f.input :name %>
<%= f.input :description %>
<%= link_to_remove_association 'remove product', f %>

def new
 current_seller = Seller.find{|person|person.store==params[:store]}
 @order = current_seller.orders.new
end

def create
@seller = current_seller
@order = @seller.orders.new(order_create_params)

respond_to do |format|
  if @order.save
    format.html { redirect_to @order, notice: 'Order was successfully created.' }
    format.json { render action: 'show', status: :created, location: @order }
  else
    format.html { render action: 'new' }
    format.json { render json: @order.errors, status: :unprocessable_entity }
  end
end

end
the URL like /orders/new?store=test03
def order_create_params
  params.require(:order).permit(products_attributes: [:id, :name, :description, :_destroy]).merge(:seller_id => @seller.id)
end

I tried a lots way to build but now "remove product" didn't work and If I use Order.new to create only the first one product can save in order(which displays in the beginning) and can't get seller_id and now will cause undefined method `orders' for nil:NilClass when I create
how can I def my create actioin to create order can link seller and add remove product can work

A: Your product_fields partial needs to be surrounded with a div with class nested-fields for the remove to work.


text:
Q: Read current running activity from service I have created an app that runs a service to read which app/activity user have opened and using it at the current time. The problem is that the service reads only the launcher application. It doesn't return me the cirrently open app/activity. Can you help? The code i write is below. Thanks in advance.
@Override
public void onStart(Intent intent, int startId) {
    // For time consuming an long tasks you can launch a new thread here...
    Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

    Runnable runable = new Runnable() {

        public void run() {
            try{
                ActivityManager am2 = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
                String packageName = am2.getRunningTasks(1).get(0).topActivity
                        .getPackageName();

                    Log.w("RunningTask", packageName);

                handler.postDelayed(this, 8000);
            }
            catch (Exception e){

            }

        }
    };
    handler.postDelayed(runable, 8000);

}

A: If you use Android 5.0 or above, getRunningTasks() is deprecated and will only return a small subset, including the caller's own tasks, and possibly some other tasks such as home.
You may check out getRunningAppProcesses() which worked before Android 5.1.1. See Cannot get foreground activity name in Android Lollipop 5.0 only and Android 5.1.1 and above - getRunningAppProcesses() returns my application package only
Example using getRunningAppProcesses:
ActivityManager am2 = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
String processName = am2.getRunningAppProcesses().get(0).processName;
Log.w("Running process", processName);


text:
Q: array_agg with distinct works in postgres 9.4 but not in postgres 9.6 I have a query that use array_agg with distinct as an argument and is not accepted on postgres 9.6.
I created this sample to illustrate the issue:
create table numbers (id integer primary key, name varchar(10));
insert into numbers values(1,'one');
insert into numbers values(2,'two');

postgres 9.4
select array_agg(distinct(id)) from numbers;
 array_agg
-----------
 {1,2}

postgres 9.6
ERROR:  function array_agg(integer) is not unique
LINE 1: select array_agg(distinct(id)) from numbers;
               ^
HINT:  Could not choose a best candidate function.
You might need to add explicit type casts.

What do I need to change in order to get this result on postgres 9.6?
Thanks.
This is what I get checking the functions:
nspname | proname | proargtypes
------------+-----------+---------------------
pg_catalog | array_agg | [0:0]={anyarray}
public | array_agg | [0:0]={anyelement}
pg_catalog | array_agg | [0:0]={anynonarray

Now, I found the issue thanks to the comment by pozs.  I remove the public definition of the aggregated function and it worked.
The issue was just on the database that I was working on, as I found some people saying that the sample worked for them I created a new database an run the example.  And then the only change there was the aggregate function definitions.

A: Now, I found the issue thanks to the comment by pozs. I remove the public definition of the aggregated function and it worked.
The issue was just on the database that I was working on, as I found some people saying that the sample worked for them I created a new database an run the example. And then the only change there was the aggregate function definitions.
So I drop the function public | array_agg | [0:0]={anyelement}  and it worked.
Thanks a lot.

A: It works exactly like that as demonstrated by this dbfiddle on PostgreSQL 9.6.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit.


text:
Q: Is it possible to remove vector elements by enumeration in Java? I am aware about Vector API of remove method as well as concept of Iterator.
But my question is can we use enumeration for this?Is there any minute possibility for this?

A: Enumeration is a Java 1.0 class, and as many classes from that time it's less than optimal. The javadoc lists the flaws as follows

The functionality of this interface is duplicated by the Iterator
  interface. In addition, Iterator adds an optional remove operation,
  and has shorter method names.

If you don't have access to the underlying collection, there's no possibility of removing an element with just an Enumeration.


text:
Q: Transpose / reshape dataframe without "timevar" from long to wide format I have a data frame that follows the below long Pattern:
   Name          MedName
  Name1    atenolol 25mg
  Name1     aspirin 81mg
  Name1 sildenafil 100mg
  Name2    atenolol 50mg
  Name2   enalapril 20mg

And would like to get below (I do not care if I can get the columns to be named this way, just want the data in this format):
   Name   medication1    medication2      medication3
  Name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
  Name2 atenolol 50mg enalapril 20mg             NA

Through this very site I have become familiarish with the reshape/reshape2 package, and have went through several attempts to try to get this to work but have thus far failed.
When I try dcast(dataframe, Name ~ MedName, value.var='MedName') I just get a bunch of columns that are flags of the medication names (values that get transposed are 1 or 0) example:
 Name  atenolol 25mg  aspirin 81mg
Name1              1             1
Name2              0             0

I also tried a dcast(dataset, Name ~ variable) after I melted the dataset, however this just spits out the following (just counts how many meds each person has):
 Name  MedName
Name1        3
name2        2

Finally, I tried to melt the data and then reshape using idvar="Name" timevar="variable" (of which all just are Mednames), however this does not seem built for my issue since if there are multiple matches to the idvar, the reshape just takes the first MedName and ignores the rest.
Does anyone know how to do this using reshape or another R function? I realize that there probably is a way to do this in a more messy manner with some for loops and conditionals to basically split and re-paste the data, but I was hoping there was a more simple solution. Thank you so much!

A: @thelatemail's solution is similar to this one.  When I generate the time variable, I use rle in case I'm not working interactively and the Name variable needs to be dynamic.
# start with your example data
x <-
    data.frame(
        Name=c(rep("name1",3),rep("name2",2)),
        MedName=c("atenolol 25mg","aspirin 81mg","sildenafil 100mg",
            "atenolol 50mg","enalapril 20mg")
    )

# pick the id variable
id <- 'Name'

# sort the data.frame by that variable
x <- x[ order( x[ , id ] ) , ]

# construct a `time` variable on the fly
x$time <- unlist( lapply( rle( as.character( x[ , id ] ) )$lengths , seq_len ) )

# `reshape` uses that new `time` column by default
y <- reshape( x , idvar = id , direction = 'wide' )

# done
y

A: One clean solution involves the very useful pivot_wider function from the tidyr package version 1.1.0. With this you can also directly specify the column names by using the argument names_glue.
library(tidyr)
library(dplyr)

dataframe %>%
  group_by(Name) %>%
  mutate(row_n = row_number()) %>%
  pivot_wider(id_cols = Name, names_from = row_n, values_from = MedName, names_glue = "medication{row_n}")

Output
# A tibble: 2 x 4
# Groups:   Name [2]
#   Name  medication1   medication2    medication3
#   <chr> <chr>         <chr>          <chr>
# 1 Name1 atenolol 25mg aspirin 81mg   sildenafil 100mg
# 2 Name2 atenolol 50mg enalapril 20mg NA

A: With the data.table package, this could easily be solved with the new rowid function:
library(data.table)
dcast(setDT(d1),
      Name ~ rowid(Name, prefix = "medication"),
      value.var = "MedName")

which gives:

   Name    medication1     medication2       medication3
1 Name1  atenolol 25mg    aspirin 81mg  sildenafil 100mg
2 Name2  atenolol 50mg  enalapril 20mg              <NA>

Another method (commonly used before version 1.9.7):
dcast(setDT(d1)[, rn := 1:.N, by = Name],
      Name ~ paste0("medication",rn),
      value.var = "MedName")

giving the same result.

A similar approach, but now using the dplyr and tidyr packages:
library(dplyr)
library(tidyr)
d1 %>%
  group_by(Name) %>%
  mutate(rn = paste0("medication",row_number())) %>%
  spread(rn, MedName)

which gives:

Source: local data frame [2 x 4]
Groups: Name [2]

    Name   medication1    medication2      medication3
  (fctr)         (chr)          (chr)            (chr)
1  Name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
2  Name2 atenolol 50mg enalapril 20mg               NA

A: Assuming your data is in the object dataset:
library(plyr)
## Add a medication index
data_with_index <- ddply(dataset, .(Name), mutate,
                         index = paste0('medication', 1:length(Name)))
dcast(data_with_index, Name ~ index, value.var = 'MedName')

##    Name   medication1    medication2      medication3
## 1 Name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
## 2 Name2 atenolol 50mg enalapril 20mg             <NA>

A: You could always generate a unique timevar before using reshape. Here I use ave to apply the function seq_along 'along' each "Name".
test <- data.frame(
Name=c(rep("name1",3),rep("name2",2)),
MedName=c("atenolol 25mg","aspirin 81mg","sildenafil 100mg",
          "atenolol 50mg","enalapril 20mg")
)

# generate the 'timevar'
test$uniqid <- with(test, ave(as.character(Name), Name, FUN = seq_along))

# reshape!
reshape(test, idvar = "Name", timevar = "uniqid", direction = "wide")

Result:
   Name     MedName.1      MedName.2        MedName.3
1 name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
4 name2 atenolol 50mg enalapril 20mg             <NA>

A: This seems to actually be a fairly common problem, so I have included a function called getanID in my "splitstackshape" package.
Here's what it does:
library(splitstackshape)
getanID(test, "Name")
#     Name          MedName .id
# 1: name1    atenolol 25mg   1
# 2: name1     aspirin 81mg   2
# 3: name1 sildenafil 100mg   3
# 4: name2    atenolol 50mg   1
# 5: name2   enalapril 20mg   2

Since "data.table" is loaded along with "splitstackshape", you have access to dcast.data.table, so you can proceed as with @mnel's example.
dcast.data.table(getanID(test, "Name"), Name ~ .id, value.var = "MedName")
#     Name             1              2                3
# 1: name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
# 2: name2 atenolol 50mg enalapril 20mg               NA

The function essentially implements a sequence(.N) by the groups identified to create the "time" column.

A: Here's a shorter way, taking advantage of the way unlist deals with names:
library(dplyr)
df1 %>% group_by(Name) %>% do(as_tibble(t(unlist(.[2]))))
# # A tibble: 2 x 4
# # Groups:   Name [2]
#      Name      MedName1       MedName2         MedName3
#     <chr>         <chr>          <chr>            <chr>
#   1 name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
#   2 name2 atenolol 50mg enalapril 20mg             <NA>

A: A tidyr solution with chop() and unnest_wider().
library(tidyr)

df %>%
  chop(-Name) %>%
  unnest_wider(MedName, names_sep = "")

# # A tibble: 2 x 4
#   Name  MedName1      MedName2       MedName3
#   <chr> <chr>         <chr>          <chr>
# 1 Name1 atenolol 25mg aspirin 81mg   sildenafil 100mg
# 2 Name2 atenolol 50mg enalapril 20mg NA

The argument names_sep = "" is necessary; otherwise, the new column names will be ..1, ..2, and ..3.

Data
df <- structure(list(Name = c("Name1", "Name1", "Name1", "Name2", "Name2"
), MedName = c("atenolol 25mg", "aspirin 81mg", "sildenafil 100mg",
"atenolol 50mg", "enalapril 20mg")), class = "data.frame", row.names = c(NA, -5L))

A: In base you can use split or unstack to split up MedName by Name. Then set the length of each list element to the same length and rbind them.
. <- split(x$MedName, x$Name)
#. <- unstack(x[2:1]) #Alternative

do.call(rbind, lapply(., `length<-`, max(lengths(.))))
#do.call(rbind, lapply(., "[", 1:max(lengths(.)))) #Alternative
#t(sapply(., "[", 1:max(lengths(.)))) #Alternative

#      [,1]            [,2]             [,3]
#Name1 "atenolol 25mg" "aspirin 81mg"   "sildenafil 100mg"
#Name2 "atenolol 50mg" "enalapril 20mg" NA

Note that the result is a matrix. In case a data.frame is needed use in addition as.data.frame.matrix.
Data
x <- read.table(header=TRUE, text="
  Name          MedName
  Name1    'atenolol 25mg'
  Name1     'aspirin 81mg'
  Name1 'sildenafil 100mg'
  Name2    'atenolol 50mg'
  Name2   'enalapril 20mg'")

Benchmark
bench::mark(check=FALSE,
Jaap1 = dcast(setDT(y), Name ~ rowid(Name, prefix = "medication"), value.var = "MedName"),
Jaap2 = x %>%  group_by(Name) %>%  mutate(rn = paste0("medication",row_number())) %>% spread(rn, MedName),
mnel = {data_with_index <- ddply(x, .(Name), mutate, index = paste0('medication', 1:length(Name)))
  dcast(setDT(data_with_index), Name ~ index, value.var = 'MedName') },
thelatemail = reshape(within(x, uniqid <- ave(as.character(Name), Name, FUN = seq_along)), idvar = "Name", timevar = "uniqid", direction = "wide"),
a5c1d2h2i1m1n2o1r2t1 = dcast.data.table(getanID(y, "Name"), Name ~ .id, value.var = "MedName"),
"Anthony Damico" = {. <- x[order(x[, "Name"]),]
  .$time <- unlist( lapply( rle( as.character( .[ , "Name" ] ) )$lengths , seq_len ) )
  reshape( . , idvar = "Name" , direction = 'wide' ) },
"Ric S" = x %>%  group_by(Name) %>%  mutate(row_n = row_number()) %>%
  pivot_wider(id_cols = Name, names_from = row_n, values_from = MedName, names_glue = "medication{row_n}"),
"Darren Tsai" = x %>% chop(-Name) %>% unnest_wider(MedName, names_sep = ""),
moodymudskipper = x %>% group_by(Name) %>% do(as_tibble(t(unlist(.[2])))),
GKi = {. <- split(x$MedName, x$Name)
  do.call(rbind, lapply(., "[", 1:max(lengths(.)))) },
GKi2 = {. <- split(x$MedName, x$Name)
  do.call(rbind, lapply(., `length<-`, max(lengths(.))))}
)

Result
   expression                min   median `itr/sec` mem_al…¹ gc/se…² n_itr  n_gc
   <bch:expr>           <bch:tm> <bch:tm>     <dbl> <bch:by>   <dbl> <int> <dbl>
 1 Jaap1                910.83µs    1.5ms     645.   274.5KB    8.32   310     4
 2 Jaap2                  9.64ms  11.53ms      86.9   16.5KB    9.15    38     4
 3 mnel                   4.69ms   5.91ms     164.   280.1KB    6.31    78     3
 4 thelatemail          619.74µs 898.36µs     959.        0B   12.6    458     6
 5 a5c1d2h2i1m1n2o1r2t1   1.36ms   2.18ms     426.   291.4KB    8.70   196     4
 6 Anthony Damico       565.34µs 794.76µs    1123.        0B   12.5    537     6
 7 Ric S                 13.51ms  15.59ms      62.4   64.2KB    6.69    28     3
 8 Darren Tsai            3.75ms   5.02ms     199.    22.7KB    8.54    93     4
 9 moodymudskipper       12.88ms  15.88ms      63.5   26.5KB    6.81    28     3
10 GKi                   31.58µs  35.73µs   21448.        0B   17.2   9992     8
11 GKi2                  29.41µs  32.77µs   23717.        0B   16.6   9993     7

GKi is in this case about 15 times faster than the second and is in the group which is allocating no additional memory.


text:
Q: Android: What's the best way to implement the BaseAdapter if item content in ListView is dynamic? In most case, we need to implement the BaseAdapter's getItemViewType() and getViewTypeCount() for dynamic item content of the listview, as this post says. But I think this solution is only suitable for finite number and knowing beforehand, such as listview item with sending layout and receving layout.
What about the case that the listview with its item content impossible knowing beforehand?
For example, I need to show a contact list from server, the contact list size is about several thousand. For each item, I need to show, for example, the hobby "list". It is a small range of 0 to tens of string. So in this case:

*

*The item types is relatively bigger than normal case using "getItemViewType"

*Though each item may be different, but similar to a certain degree: the item content is different in the number of views, but common in view type. Item A is different from item B only because it have more TextViews.

For each time in the getView, the convertview is hard to simply reuse because they are different, but if we create new TextView and added to the convertView, it will impact the scrolling of the listview. I don't think it's appropriate such way. What should i do in such case?

A: Unfortunately you cannot easily change the number of item view types on the fly.  The getViewTypeCount() method is only invoked when the adapter is set on the ListView.  That means, were you to dynamically change it, then you would have to call setAdapter() again.  This is a huge performance hit as the ListView will toss out all the recycled views and re-generate everything from scratch again.
Honestly, it looks like you should be using an ExpandableListView instead.  It allows you to displays lists of items under groups.  The only difference is the groups are placed on top of the list.  So where you have A, B, C, D on the left side in your picture...in the ExpandableListView it'll sit on top.
The ExpandableListView can easily handle your situation where a given grouping could have any variable number of items within it.  You mentioned needing to store a contact list. I'd suggest taking a look at a RolodexArrayAdapter for use with the ExpandableListView. It may be of help.


text:
Q: Calculating number on normal distribution curve Can someone please let me know if I have this question correct:
Ron drives a transport truck across North America. The average number of
kilometers a driving tire will last is 83000 km with a standard deviation of
12000 km. Ron likes to replace his tires before the lifespan is likely to be
passed. If he wishes to replace tires so that there is at most a 20% likelihood
that the tires are passed their lifespan, at what distance should he replace the
tires? Report your answer to the nearest hundred km.

I drew a normal distribution curve like so to represent what I'm trying to find:

I figured the area for $Z_1$ is $70 \%$ because from the left to the middle is $50\%$ and than another $20\%$ on the right side, so $0.50 + 0.20 = 0.70$ or $70\%$. The inverse of the area of $0.70$ is $0.5244$, thus:
$$Z_1 = 0.5244$$
$$\mu = 83000$$
$$\sigma = 12000$$
Then using
$$Z_1 = \frac{x - \mu}{\sigma} $$
I did:
$$0.5244 = \frac{x - 83000}{12000}$$
$$0.5244 \times 12000 = x - 83000$$
$$6292.81 + 83000 = x$$
$$x = 89292.81 \approx 89300$$
Therefore, Ron would change his tires after driving about 89300km.

Is this correct?

A: The picture is not correct. We want a probability of $20\%$ in the left tail.
If Ron replaces at $83000$, then with probability $0.5$ the tire is by then  "unsafe." If later, as in your answer, then the probability the tire is unsafe by the time it is replaced is $70\%$.


text:
Q: Android show spinner in toolbar when user navigates to a particular fragment(3rd tab fragment) I have three tabs like Tab1, Tab2, Tab3 and i have viewpager in MainFragment to display these three tabs. How can i display a spinner in toolbar only when user navigates to Tab3.

A: Insert spinner in toolbar custom view, implement ViewPager callbacks to receive current pager position and make some logic:
@Override
public void onPageSelected(int position) {
    super.onPageSelected(position);
    if (position == 0 || position == 1)
        spinner.setVisibility(View.GONE); // hide spinner
    else if (position == 2)
        spinner.setVisibility(View.VISIBLE); // show spinner
}


text:
Q: Validate only few properties of a model class using Data Annotations from a Console application in c# I have a model class with several properties like below and each property have Data Annotations for the validation
Class User{

[Required]
public string First Name{get;set;}

[Required]
public string Last Name {get;set;}

[Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]
public string Email {get;set;}

[Required, MaxLength(20), DataType(DataType.Password), Display(Name ="Password")]
public string Pasword {get;set;}
}

Now, in the Console app I ask user to give me an email address and password to Login. How can I validate if a given email and password satify the conditions. Since it is login, I dont want to validate First Name and Last Name
var context = new ValidationContext(user);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(user, context, results, true);

TryValidateObject takes an instance as a first parameter, so when I do this it also returns me error for First Name and Last Name
Can someone please suggest how can I validate only Email and password using the same User class?

A: If you have a different part of the app that requires a different set or properties and validation rules, then you should be using a completely distinct model for that purpose. So you could have a new model like this:
public class UserCredentials
{
    [Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]
    public string Email {get;set;}

    [Required, MaxLength(20), DataType(DataType.Password), Display(Name ="Password")]
    public string Password {get;set;}
}

Now your code that looks something like this will work:
UserCredentials userCredentials = .... //Get the credentials from somewhere

var context = new ValidationContext(userCredentials);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(userCredentials, context, results, true);

Also, if you want to share this code with the user class, you could make use of inheritance:
public class User : UserCredentials
{
    [Required]
    public string FirstName{ get; set; }

    [Required]
    public string LastName { get; set; }
}

A: I would split the class up into a base class for the user name and password and the create a class off of it to hold the user name and password.
Something like this:
Class User : AuthUser {

    [Required]
    public string First Name{get;set;}

    [Required]
    public string Last Name {get;set;}

}

Class AuthUser {
    [Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]
    public string Email {get;set;}

    [Required, MaxLength(20), DataType(DataType.Password), Display(Name ="Password")]
    public string Pasword {get;set;}
}


text:
Q: Filter Angular Material Table with Dropdown I have created an angular table and i want to apply filter based on a specific column. i have defined mat-select with mat-options but the problem is when i select from a dropdown data disappears and nothing filters.
here is my markup

          <mat-form-field >
              <mat-select [(value)]="filterValue" placeholder="Type">
                <mat-option *ngFor="let type of types" [value]="type" (click)="applyFilter(type)">
                  {{type}}
                </mat-option>
              </mat-select>
            </mat-form-field>

in typescrip i have written
types = ["All", "Income","Expense"]

applyFilter(filterValue: string) {
      this.dataSource.filter = filterValue.trim().toLowerCase();
  }

here i want to filter on Type column (Income and Expense)

and also i want to know how to how to retrieve all data by selectin "All" option

A: Try this

          <mat-form-field >
              <mat-select [(value)]="filterValue" placeholder="Type" (click)="applyFilter($event)">
                <mat-option *ngFor="let type of types" [value]="type" >
                  {{type}}
                </mat-option>
              </mat-select>
            </mat-form-field>

and
applyFilter(event) {
      this.dataSource.filter = event.value.toLowerCase();
  }


text:
Q: Download from URL on ssh connection I've a ssh connection between my pc(linux) and a server(linux).
I want to download a file from URL inside the server.
I tried with the command  :
   firefox URL
And i get :
   Error: no display specified
Thank you in advance!

A: If you are on ssh, use the following command-
curl -O http://website/filetodownload.txt
or use wget command

A: Try out with wget http://example.com/xyz.txt
it will work


text:
Q: What do you call individual "subcakes" of a multi-layered cake? What do you call those flat pieces of baked dough with cream in between that make up a cake? In Russian, we would say "корж" (singular)

A: Those would be called "cake layers".
For example, this article on How to Build a Layered Cake includes the following instructions:

To assemble, first place a cooled/chilled cake layer top side-down on a cardboard round

Another article advises on how to get perfect flat cake layers.

A: They are called layers. That type of cake is often called a layer cake. The material of the layers, separated by creamy stuff, is called 'cake', which can be used an an uncountable or mass noun.
Cake is:

a sweet food made from flour, eggs, fat, and sugar mixed together and
baked

Cake (Cambridge Dictionary)

More generally, a layer is:

a level of material ... that is different from the material above or below it

Layer (Cambridge Dictionary)

A: They are tiers:
AHD tier
n.

*

*One of a series of rows placed one above another: a stadium with four tiers of seats.

*A rank or class.
tr. & intr.v. tiered, tier·ing, tiers
To arrange (something) into or rise in tiers: tier a wedding cake; balconies that tier upward.

(as Esther points out, tiered cakes usually have smaller upper layers.)
Or just layers.
AHD layer
a. A single thickness of a material covering a surface or forming an overlying part or segment: a layer of dust on the windowsill; a cake with four layers.


text:
Q: How can I simplify these mySQLi queries? I have 5 similar queries which output a single number. The payment_type determines the output. Basically it will show how many transactions were done with Cash, Check, Credit, or Autopay for the year.
$getTxnX = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%'");
$getTxnC = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='C'");
$getTxnK = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='K'");
$getTxnO = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='O'");
$getTxnA = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='A'");

I am outputing the numbers using
if ( $row = $getTxnX->fetch_assoc() ) {
    echo $row['num'];
}
if ( $row = $getTxnC->fetch_assoc() ) {
    echo $row['num'];
}
if ( $row = $getTxnK->fetch_assoc() ) {
    echo $row['num'];
}
if ( $row = $getTxnO->fetch_assoc() ) {
    echo $row['num'];
}
if ( $row = $getTxnA->fetch_assoc() ) {
    echo $row['num'];
}

It works fine, but is there a way to simplify the queries into one, then use something like the following?:
if ( $row = $getNewTxnQueryHere->fetch_assoc() ) {
    echo $row['X'];
    echo $row['C'];
    echo $row['K'];
    echo $row['O'];
    echo $row['A'];
}

I plan to wrap if ( $row = $getNewTxnQueryHere->fetch_assoc() ) { ... } around my entire results area and use the echo $row['X']; in various places within.

A: Why not use a single grouped query?
SELECT payment_type, count(*)
FROM transaction
WHERE payment_type IN ('X', 'C', 'K', 'O', 'A')
    AND YEAR(paid_on) = YEAR(curdate())
GROUP BY payment_Type

A: You can use one query
$query = $con->query("SELECT payment_type, COUNT(*) as cnt AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' group by payment_type");
$data = array();
while($row = $query->fetch_assoc()) {
    $data[$row['payment_type']] = $row['cnt'];
}

all data will be in array $data, ex: echo $data['C']; or echo $data['A']; or for total echo array_sum($data);


text:
Q: Куда уходят папки и файлы при смене ветки Git или переход на другой комит, в локальном репозитории? Интересно, куда уходят папки и файлы при смене ветки Git или переход на другой комит, в локальном репозитории?

A: В репозитории есть два типа файлов, назовем их файлы проекта и файлы системы управления версиями (т.е. в нашем случае git). Файлы проекта - те файлы, с которыми напрямую работает разработчик, и файлы git - файлы, которая лежат в папке .git, и разработчик с ними дела не имеет.
Начнем со вторых, т.к. там проще.
В папке .git содержится информация о всех коммитах репозитория. При переходе по коммитам или смене веток (что в принципе тоже переход на другой коммит) с файлами в папке .git совершенно ничего не происходит (кроме разве что содержимого файла HEAD и пары других, но это нас не интересует).
С файлами проекта происходит следующее: файлы, отсутствующие в том коммите/ветке, куда мы переключаемся, просто удаляются (не в корзину!). Файлы, имеющее другое содержание, перезаписываются. Идентичные файлы не трогаются.

A: Вопрос, конечно, интересный
Я думаю, git перезаписывает файлы, а если необходимо - удаляет/создаёт их


text:
Q: Finding Network overshoots under a certain distance we have a large contiguous network that will have legitimate overshoots (like a dead end street), but may or may not have illegitimate overshoots.  Using FME, I can't seem to manufacture a way to find these overshoots.  It is new to me, but I cannot work out how to do it.  A long lunch yesterday for Mothering Sunday may have removed a large number of brain cells, but I can't work out a way to do it.
Any ideas?  Thanks in advance.

A: I have used SmartCleaner (get transformer from here) When fixing dangles. Another option would be MRFClener it's very good but costs.


text:
Q: Neutrinos always travel at same speed? Neutrinos have mass, and only interact with gravitional and weak force, what make it very difficult to detect.
Neutrinos is known to travel very closer to speed of light and have very small mass altought neither have a precise measure.
Particles with no mass like photons and gluons (altought there is no free gluon) must travel at speed of light (vacuum).
Particles that have mass must travel in any velocity lower than speed of light.
Dark matter can have hot particles (near speed of light) and cold particles (non relativistic velocity).
My questions are:

*

*Does neutrinos have always the same velocity?

*Is it possible to have neutrinos travelling with non-relativistic speeds?

*Why only referred neutrinos as possible hot dark matter and not to cold dark matter?

A: It is known, through the observation of the phenomenon of flavor oscillations, that neutrinos definitely have nonzero mass.
Therefore there's a definite answer to your answer: neutrinos most assuredly do not always travel at the same speed.
Probably what is causing you to have doubts is that neutrinos aren't observed to have speeds other than $c$, to within experimental error. So what's going on?
It is instructive to plot the momentum four-vector norm equation $E^2/c^2-p^2 = m^2 c^2$ for a particle in normalized co-ordinates so that it shows normalized speed $\frac{v}{c}$ against normalized momentum $\tilde{p} = \frac{p}{m\,c}$:

There is always behavior like this: for very massive particles, the region where $v$ differs significantly from $c$ is wide: for very light particles, the same region is very concentrated around $p=0$, but its the same shapen curve, just stretched or shrunken in $p$-scale. More details in my answer here.
We see therefore that for a particle with a very low rest mass, such as  a neutrino, the momentum has to be very small to observe the particle at a speed less than $c$. However, this means a particle with an impossibly long wavelength, which means it is very hard to prepare in such a state, and a neutral particle without much momentum will not trigger detection events. So, from a practical point of view, the particle becomes almost impossible to observe at a speed very different from $c$: the conditions whereunder it has different motion make it "invisible".

A: It is possible for neutrinos to have non relativistic velocities. There is no reason why that shouldn't be the case because velocity  depends on the frame of reference of the observer.
They also can change their velocity due to the gravitational field for example.

A: We can start this off best, if we take a look at the relativistic relationship between total energy $E$, rest mass $m_\nu$ and momentum $p$:
$E^2 = m_\nu^2 + p^2 $ (in natural units of SR)
Since momentum is a kind of a measure for velocity (since rest mass is fixed), we formulate this as
$p = \sqrt{E^2 + m_\nu^2}$
So the velocity of a particle is obviously dependent on the energy with which the particle is created. If you now take a look on your average solar neutrino with about 10 MeV, you will notice really quickly that kinetic energy does not differ so much from total energy if a neutrino mass is $m_\nu < 1$ eV. Therefore almost all energy is kinetic energy, which leads to ultra-relativistic velocities.

A: The 25 detected neutrinos from supernova 1987A--168,000 light years away--arrived over a span of 13 seconds [Wikipedia, which is never wrong]. Not all neutrinos are this energetic, though.