text:
Q: loading a page in visualforce using jquery I'm trying to embed a website in my visualforce page, but the code isn't working.
<apex:page >
   <apex:includeScript value="{$Resource.jQuery}"  />
   <script>
      $j = jQuery.noConflict();
      function LoadPage(){
      $.get('http://google.com, function(data) {
      $('#siteloader').html(data);
  });
}
   </script>

<body>
onload=LoadPage();
</body>

</apex:page>

A: Why you want to use AJAX to display the site?
Did you tried an iframe tag?


text:
Q: Websphere Liberty authentication with iv-user from F5 Actual situation:
I have a Liberty Server where my JEE - Application is running. If you enter the application liberty runs a Login Form where you can enter your userid and password, which will be checked by Ldap-Registry and eventually you´ll be authenticated and liberty create a Session with your credentials. Now you can see the App and the app can use the SessionContext and knows - who you are...
As my company now has changed its security philosophy, we gotta use a F5 APM.
So far:
on entering the Application you´ll be redirected to the F5 APM which will redirect to a IDP where you can login. Afterwards its redirecting back to the App with an IV-User in Http-Header. Good news is, i can still use the Lioberty Formlogin from here - but this is kinda stupid, cause you gotta login twice...
Now my Question is, how can i use this IV-User to create the UserSession with liberty or maybe to check against the LdapRegistry?

A: If you dont want to query registry you need to create full subject. So instead of this:
return TAIResult.create(HttpServletResponse.SC_OK, userid);

you need to do this in your TAI:
// stash in hashtable
Hashtable hashtable = new Hashtable();
hashtable.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID,uniqueid);
hashtable.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME,userid);
hashtable.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupList);
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, "myCustomAttribute" + uniqueid);
Subject subject = new Subject();
subject. getPublicCredentials().add(hashtable);
return TAIResult.create(HTTPServletResponse.SC_OK, "userid", subject);

For more information check these pages:

*

*Trust association interceptor support for Subject creation

*Configuring inbound identity mapping
Successful authentication should create LTPA cookie and not require additional authentications, so if you dont see such behavior something is still misconfigured.
I did a very quick look at the F5 APM and it looks like it supports OIDC so you should at least also consider that option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to have latest UI components in Android? I noticed that with every iteration of the Android platform, the buttons and UI components keep looking slicker and slicker.
Besides API changes I want to be able to adopt the latest buttons (such as spinners with the bottom-right corner as an arrow), or Jelly bean icons, across all versions of Android where my application is used. How is this usually accomplished?

A:
I want to be able to adopt the latest buttons across all versions of Android where my application is used.

The Holo Everywhere library is a popular choice to do this.


text:
Q: cakephp where do I call a global function which each page needs I'm using CakePHP (2.2 I think) and am struggling to know where to put a function. It's a function  which is called on each page load. The basic logic is
Page is requested
loads page template
loads included header
 to check if a cookie has been set.
If cookie is set, use values in that
if cookie hasn't been set, load a value from the database and save in the cookie
save cookie values in a config value to use across the page
continue loading page
Basically the function is to set the config values. I have tried to create a helper which worked nicely as I called it on the header view - but as soon as I try to access the cookie helper it didn't work.
I moved the code in to the app controller and called it on the beforefilter() function, but it seems to get called several times on the one page (even though this does actually all work ok).
So - where would I place a function to do this to get called before ANY html is drawn to the screen and is called only once?
Many thanks,
Matt.

A: beforeFilter of your AppController.php is the right place. beforeRender should also work, as @zynder mentioned.
beforeFilter should definitely only be called once per request by Cake. If it's working in beforeFilter, but it's being called more than once, you've probably done something wrong, and you should look into that. Or, maybe you could be mistaken in thinking it's executed more than once per request.
Why do you think beforeFilter is being called more than once?


text:
Q: Proper use of cudaMalloc3D with cudaMemcpy I'd like to send a 3D array src of size size in each dimension, flattened into a 1D array of size length = size * size * size, into a kernel, compute a result and store it in dst.  However, at the end, dst improperly contains all 0s.  Here is my code:
int size = 256;
int length = size * size * size;
int bytes = length * sizeof(float);

// Allocate source and destination arrays on the host and initialize source array

float *src, *dst;
cudaMallocHost(&src, bytes);
cudaMallocHost(&dst, bytes);
for (int i = 0; i < length; i++) {
    src[i] = i;
}

// Allocate source and destination arrays on the device

struct cudaPitchedPtr srcGPU, dstGPU;
struct cudaExtent extent = make_cudaExtent(size*sizeof(float), size, size);
cudaMalloc3D(&srcGPU, extent);
cudaMalloc3D(&dstGPU, extent);

// Copy to the device, execute kernel, and copy back to the host

cudaMemcpy(srcGPU.ptr, src, bytes, cudaMemcpyHostToDevice);
myKernel<<<numBlocks, blockSize>>>((float *)srcGPU.ptr, (float *)dstGPU.ptr);
cudaMemcpy(dst, dstGPU.ptr, bytes, cudaMemcpyDeviceToHost);

I've left out my error checking of cudaMallocHost(), cudaMalloc() and cudaMemcpy() for clarity.  No error is triggered by this code in any case.
What is the correct use of cudaMalloc3D() with cudaMemcpy()?
Please let me know if I should post a minimal test case for the kernel as well, or if the problem can be found in the code above.

A: EDIT: the extent takes the number of elements if using a CUDA array, but effectively takes the number of bytes if not using a CUDA array (e.g. memory allocated with some non-array variant of cudaMalloc)
From the Runtime API CUDA documentation:

The extent field defines the dimensions of the transferred area in elements. If a CUDA array is participating in the copy, the extent is defined in terms of that array's elements. If no CUDA array is participating in the copy then the extents are defined in elements of unsigned char

Also, cudaMalloc3D returns a pitched pointer, meaning that it'll have at least the dimensions of your supplied extent, but possibly more for alignment reasons. You have to take this pitch into account when accessing and copying to and from your device memory. See here for the documentation on the cudaPitchedPtr struct
As for using cudaMalloc3D with cudaMemcpy, you might want to take a look at using cudaMemcpy3D (documentation here), it might make your life a bit easier in taking the pitch of your host and device memory into account. To use cudaMemcpy3D you have to create a cudaMemcpy3DParms struct with the appropriate information. It's members are:
cudaArray_t dstArray
struct cudaPos dstPos
struct cudaPitchedPtr dstPtr
struct cudaExtent extent
enumcudaMemcpyKind kind
cudaArray_t srcArray
struct cudaPos srcPos
struct cudaPitchedPtr srcPtr

and you must specify one of srcArray or srcPtr and one of dstArray or dstPtr. Also the docs recommend to initialize the struct to 0 before using it, e.g.
cudaMemcpy3DParms myParms = {0};
Also, you might be interested in taking a look at this other SO question


text:
Q: While using Elastic SIP Trunking will Twilio still charge though the call was not received or answered? We've built a softphone system with Twilio Rest API and quickstart.js. But we are facing now a vital issue that Twilio is charging us for just an established call though it is not received! And we got the answer here LINK . So we searched for the solution and found out "Elastic SIP Trunking" that need some VoIP system or IP-PBX configurations.
But we are still confused and the question arises here, "While using Elastic SIP Trunking will Twilio still charge as the same though the call was not received  or answered?" .

A: For Programmable Voice, there are usually 2 call legs. With the Twilio client, you have the leg into Twilio (where you tell Twilio via TwiML what to do next) and another leg to the PSTN (your TwiML told Twilio to dial the PSTN). Twilio bridges the two call legs together. Each call leg has a per minute cost associated with it.
In your example, the call leg from the Twilio client to Twilio is always successful/answered. The leg to the PSTN may or may not be successful. If the PSTN leg is busy or not answered, there is no charge for that call leg, only the Twilio client to Twilio leg incurs a cost.
How Much am I Charged for Call Forwarding with Twilio?
For the most part, Elastic SIP Trunking does not have call legs. You do need a call server/PBX to use Elastic SIP Trunks. The call server/PBX handles all the application functionality vs. Twilio with Programmable Voice.


text:
Q: Calculate measure involving dates on a factTable with DAX I have this problem:
given a "Movements" factTable that holds a list of warehouse transactions.
I want to know how many items arrived, how many were shipped (and this is trivial) but also how many are "In Order" at a particular time (and this is the difficult part)
So, each line can either be a receipt (it has a positive "qIn" value) or a shipment (positive qOut)
For example a very simple list of records could be:
ID  Item    TransactionDate OrderDate   qIn qOut
1   A       2019-01-30      2019-01-10  5   0
2   A       2019-02-20      2019-01-15  3   0
3   A       2019-03-12      2019-01-20  0   6
4   A       2019-03-30      2019-02-20  20  0

That means:
On TransactionDate  2019-01-30 Items A has arrived in quantity 5.
The order for this had been created on 2019-01-10: so for that 20 days there was 5 quantity of Item A "ordered".
However, when I watch at the end of January, I should see 0 for this transaction in the "ordered" measure because it arrived on January 30.
Instead, for the second record, at the end of January I should see that a quantity of 3 was "in order", because the actual arrival has been on 2019-02-20.
So, at the end of the line, the Excel pivot table should show a situation similar to this:
    Year    2019
    Month   January         February        March
            IN | Ord        IN | Ord        IN | Ord
Item
A           5      3         3    20        20   0

The simple measure of qIn is:
qIN := SUM(Transactions[qtaIn])

The measure of ordered quantity I have elucubrated at the moment (that does nothing!):
orderedQty :=
CALCULATE (
    SUMX ( Transactions; Transactions[qIn] );
    DATESBETWEEN (
        Transactions[TransactionDate];
        MINX ( Transactions; Transactions[OrderDate] );
        MAXX ( Transactions; Transactions[TransactionDate] )
    )
)

EDIT
The "InOrder" measure should be "additive" in the sense that it should not only take into account what has happened in the current month, but also how much of the InOrder from past months is yet to be received.
With a picture (but that would be to do...) the whole thing would be clearer, at least from a logic perspective. However, also with a picture, I can't see how to extract "direct measures" from that logic.
Instead, exploiting the measures already provided by @Olly, the problem could be reformulated as:
InOrderFromOtherMonths :=  Sum (qIn) where Order Month <> Current Month

(i.e. how many are arrived in current month that comes from orders taken in past months)
InOrder := Total sum of (ORDER measure)  -  InOrderFromOtherMonths

PS.
I have created an Excel file with a little more interesting example.

In that file, using the "direct measure picture" the InOrder for January would be:
ID 2 + ID 5 + ID 6 (orders yet opened at end of January).
In values = 3+9+17=29
With the "indirect" measure would be:
Total sum of ORDER = 15+23+12=50
InOrderFromOtherMonths = 6+15=21
InOrder = Total sum of ORDER - InOrderFromOtherMonths = 50 - 21 = **29**

A: Create a Calendar table, including a YYYY-MM field. If you don't already have a calendar table, you can automatically create one in PowerPivot: Design > Date Table > New
Create an ACTIVE relationship between Calendar[Date] and Transactions[TransactionDate]
Create an INACTIVE relationship between Calendar[Date] and Transactions[OrderDate]

Now create your measures:
Measure IN:
IN:=SUM ( Transactions[qIn] )

Measure ORDERS:
ORDERS:=
CALCULATE (
    SUM ( Transactions[qIn] ),
    USERELATIONSHIP ( 'Calendar'[Date], Transactions[OrderDate] )
)

Measure ORDER:
ORDER:=
IF (
    HASONEVALUE ( 'Calendar'[YYYY-MM] ),
    CALCULATE (
        [ORDERS],
        FORMAT ( Transactions[TransactionDate], "YYYY-MM" ) <>  VALUES ( 'Calendar'[YYYY-MM] )
    )
)

And pivot to suit:

EDIT
After your question edit, I'm finding some of your labels confusing - but try creating the following measures:
Measure: Ordered
Ordered:=
CALCULATE (
    SUM ( Movements[qIn] ),
    USERELATIONSHIP ( 'Calendar'[Date], Movements[OrdDate] )
)

Measure: Received
Received:= SUM ( Movements[qIn] )

Measure: Outstanding
Outstanding:=
VAR EOMaxDate =
    EOMONTH ( LASTDATE ( 'Calendar'[Date] ), 0 )
RETURN
    IF (
        ISBLANK ( [Ordered] ) && ISBLANK ( [Received] ),
        BLANK(),
        CALCULATE (
            [Ordered] - [Received],
            FILTER (
                ALL ( 'Calendar'),
                'Calendar'[Date] <= EOMaxDate
            )
        )
    )

Now use those three measures in your pivot:

Or, more clearly:

See https://excel.solutions/so_55596609-2/ for example XLSX file


text:
Q: Async SQLalchemy: accessing eagerly-loaded empty relationship triggers new lazy-load, raising error I am using sqlalchemy + asyncpg, and 'selectin' eager loading.
I have Person items that have one-to-many relationships with Friends.
I insert a Person into my database, with no related Friend entries. If in the same session I try and get that Person from the database, I can access their static (non-relationship) columns fine, but cannot access the friends relationship.
I think trying to access person.friends is triggering a lazy load, despite it being enforced previously as a selectin load. Why is this? How can I avoid it?
# Create the ORM model
class Person(Base):
    __tablename__ = 'items'
    id_ = Column(POSTGRES_UUID(as_uuid=True), primary_key=True)
    name = Column(String(32))
    friends = relationship('Friend', lazy='selectin')

# Create an instance
person_id = uuid4()
person = Person(id_=person_id, name='Alice') # Note that this Person's friends are not set

# Add to database
async with AsyncSession(engine, expire_on_commit=False) as session:
    try:
        session.begin()
        session.add(person)
        await session.commit()
    except:
        await session.rollback()
        raise
    # Get the added person from the database
    created_person = await session.get(person, person_id)
    print(created_person.id_) # Works fine
    print(created_person.friends) # Raises error

Error:
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here.
Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)

A: The solution is to use the populate_existing parameter in get:

populate_existing – causes the method to unconditionally emit a SQL query and refresh the object with the newly loaded data, regardless of whether or not the object is already present.

Replace
created_person = await session.get(person, person_id)

with
created_person = await session.get(person, person_id, populate_existing=True)

session.get documentation
See also: https://github.com/sqlalchemy/sqlalchemy/issues/7176

A: @theo-brown's answers goes straight to the point, but wanted to add some interesting information here.
Adding extra context on lazy loading and async SQLAlchemy:
When you fetch data using async SqlAlchemy, every model being queried spawns a coroutine. If you don't eager load your relationships, you'll end up with partially populated models.
Imagine this use case that I'm working on: I have a batch_job object, that relates to a batch_file and batch_job entries, all of which are tables in my database. When I don't eager load them, see what happens in the debugger:

The Traceback that I get when returning the object from an endpoint is this one:
greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)

The reason is that I didn't await these values, and that's what eager loading does for you in async sqlalchemy.
However, you might not have to eager load if you're working inside the application scope and you'll want to use these values later, and hence you could await them.
For those who are using the ORM, you could do it with the good old loading options:
results = await db_session.execute(select(YourModel).options(joinedload(YourModel.relationshipcolumn)).all()


text:
Q: How to have a placeholder text for every new line of Textarea I have created a form having a "textarea" which has a "placeholder" attribute.
  <textarea placeholder="Enter Your Text"></textarea>

What I want is, I want to display this placeholder text on every line after 'Enter' key is pressed. So that I can use it for a good UI.
Ex.
         |Enter Your Text

As if I entered "Hello" and pressed Enter key, It should be like:
         Hello
         |Enter Your Text

Or
As if I entered "Hello" and pressed Enter key thrice,It should be like:
         Hello

         |Enter Your Text

Can Anyone give solution for this!!
Thank You!

A: If I'm not wrong and I've understood what you want, you can do something like this (jsFiddle):
// this example needs to be improved if you want to use in production, but I think this is a way to achieve it
$('textarea').on('keypress', function(e){

    // store the placeholder
    var ph = $(this).attr('placeholder');

    // store the current value
    var current_value = $(this).val();

    // delete the placeholder from the current value (if exists)
    $(this).val(function(){ return arguments[1].replace(ph, ''); });

    // when pressing enter
    if( e.keyCode === 13 ) {

        // if there are line breaks, remove any existing placeholder and append the new one
        if( /\n/g.test(current_value) ) $(this).val(current_value.replace(ph, '') + ph);

        // otherwise just append the value with the placeholder
        else $(this).val(current_value + ph);

        // now move the cursor to the last position less the placeholder length
        var mv = $(this).val().length - ph.length;
        $(this)[0].setSelectionRange(mv, mv);

    }

});

A: You can use \n for new line:
$('textarea').prop('placeholder','Enter\n|Your Text');

demo
If you want to repeat, then you can use ES6 repeat method:
$('textarea').prop('placeholder','Enter\n|Your Text\n'.repeat(5));

demo


text:
Q: React Router v6 - how to handle nested routes but with only current page showing instead of previous pages I am trying to understand how to handle nested routes but with different pages using react-router v6.
For instance, say the "/" path returns a list of companies. ":companyId" takes you to the company page and ":/productId" takes you to the product of that company.
What I would like to know is how to only show the content page for that product instead of showing the list of products and the list of companies too.
I think this should be nested as I need the underlying params of both company id and product id to know where I am. How do I properly use Outlet in this case?
Companies has a list of companies. Company has a list of products.
My routes currently:
const routes = [
  {
    path: "/",
    element: <Companies />,
    children: [
      {
        path: ":companyId",
        element: <Company />,
        children: [{ path: ":productId", element: <Product /> }],
      },
    ],
  },
]

const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        children: [
          { index: true, element: <Company /> },
          { path: ":productId", element: <Product /> },
        ],
      },
    ],
  },
];

A: If I understand your question/issue correctly, it seems that Companies is rendered as a layout component, in other words, it is rendered along with the nested children routes, but you want one or the other.
If you want to render one or the other then move Companies down into a child route, specifically as an index route, so it is rendered when the path is exactly "/" but not when another nested route matches.
const routes = [
  {
    path: "/",
    children: [
      {
        index: true,
        element: <Companies />,
      },
      {
        path: ":companyId",
        element: <Company />,
        children: [
          {
            path: ":productId",
            element: <Product />
          }
        ],
      },
    ],
  },
]


text:
Q: Retrofitting existing code with a floating point arbitrary precision C++ library, any chance of success? Let say I have a snippet of code like this:
typedef double My_fp_t;

My_fp_t my_fun( My_fp_t input )
{
// some fp computation, it uses operator+, operator- and so on for type My_fp_t
}

My_fp_t input = 0.;
My_fp_t output = my_fun( input );

Is it possible to retrofit my existing code with a floating point arbitrary precision C++ library?
I would like to simple add #include <cpp_arbitrary_precision_fp>, change my typedef double My_fp_t; into typedef arbitrary_double_t My_fp_t; and let the operator overloading of C++ doing its job...
My main problem is that actually my code do NOT have the typedef :-( and so maybe my plan is doomed to failure.
Assuming that my code had the typedef, what other problems would I face?

A: This might be tough. I used a template approach in my PhD thesis code do deal with different numerical types. You might want to take a look at it to see the problems I encountered.
The thing is you are fine if all you do with your numbers is use the standard arithmetic operators. However, as soon as you use a square root or some other non operator function you need to create helper objects to detect your object's type (at compile time as it is too slow to do this at run time; see the boost metaprogramming library for help on that) and then call the correct function and return it as the correct type. It is all totally doable, but is likely to take longer than you think and will add considerably to the complexity of your code.
In my experience, (I was using GMP which must be the fastest arbitrary precision library available for C++) after all of the effort and complexity I had introduced, I found that GMP was just too slow for the sorts of computation that I was doing; so it was academically interesting, but practically useless. Before you start on this do some speed tests to see whether your library will still be usable if you use arbitrary precision arithmetic.

A: If the library defines a type that correctly overloads the operators you use, I don't see any problem...


text:
Q: how do I call JSON multiple array functions together? Here I have array numbers like [0] [1] [2] [3] .....
I have API like this
nodes: [

    {
    id: "1",
    kasus: "1",
    provinsi: "DKI Jakarta",
    provinsiid: "1",
    umur: "31",
    umurtext: "31",
    gender: "Perempuan",
    genderid: "1",
    status: "Sembuh",
    statusid: "1",
    wn: "WNI",
    wnid: "1",
    pengumuman: "2 Maret 2020",
    penularan: "Bertemu dengan WN Jepang yang dikonfirmasi positif di Malaysia (kasus #24)",
    rs: "RSPI Sulianto Saroso, Jakarta",
    rsid: "1"
    },

Here is an example of the JSON data when im var_dump
array(2) {
  ["nodes"]=>
  array(450) {
    [0]=>
    array(16) {
      ["id"]=>
      string(1) "1"
      ["kasus"]=>
      string(1) "1"
      ["provinsi"]=>
      string(11) "DKI Jakarta"
      ["provinsiid"]=>
      string(1) "1"
      ["umur"]=>
      string(2) "31"
      ["umurtext"]=>
      string(2) "31"
      ["gender"]=>
      string(9) "Perempuan"
      ["genderid"]=>
      string(1) "1"
      ["status"]=>
      string(6) "Sembuh"
      ["statusid"]=>
      string(1) "1"
      ["wn"]=>
      string(3) "WNI"
      ["wnid"]=>
      string(1) "1"
      ["pengumuman"]=>
      string(12) "2 Maret 2020"
      ["penularan"]=>
      string(74) "Bertemu dengan WN Jepang yang dikonfirmasi positif di Malaysia (kasus #24)"
      ["rs"]=>
      string(29) "RSPI Sulianto Saroso, Jakarta"
      ["rsid"]=>
      string(1) "1"
    }
    [1]=>
    array(16) {
      ["id"]=>
      string(1) "2"
      ["kasus"]=>
      string(1) "2"
      ["provinsi"]=>
      string(11) "DKI Jakarta"
      ["provinsiid"]=>
      string(1) "1"
      ["umur"]=>
      string(2) "64"
      ["umurtext"]=>
      string(2) "64"
      ["gender"]=>
      string(9) "Perempuan"
      ["genderid"]=>
      string(1) "1"
      ["status"]=>
      string(6) "Sembuh"
      ["statusid"]=>
      string(1) "1"
      ["wn"]=>
      string(3) "WNI"
      ["wnid"]=>
      string(1) "1"
      ["pengumuman"]=>
      string(12) "2 Maret 2020"
      ["penularan"]=>
      string(40) "Terhubung dengan kasus #1 (Ibu kasus #1)"
      ["rs"]=>
      string(29) "RSPI Sulianto Saroso, Jakarta"
      ["rsid"]=>
      string(1) "1"
    }

Then I tried to call all the arrays with the logic of the script that I made.
This is the code that I made from the reference that I got.
<?php
$ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'http://example.api/URL');

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  $content = curl_exec($ch);

  curl_close($ch);

  $result = (array) json_decode($content,true);

  $count= count($result);
  foreach ($result as $value) {
    for ($i=0; $i < $count; $i++)
    {
    echo $value[$i]["rs"] . "
";
    echo $value[$i]["umur"] . "
";
    echo $value[$i]["gender"] . "

";
    }
  }
  ?>

When I run the code, I get output like this
RSPI Sulianto Saroso, Jakarta
31
Perempuan

RSPI Sulianto Saroso, Jakarta
64
Perempuan

    Notice: Undefined index: rs in C:\xampp\htdocs\CORONA\kemkes.php on line 18
Notice: Undefined index: umur in C:\xampp\htdocs\CORONA\kemkes.php on line 19
    Notice: Undefined index: gender in C:\xampp\htdocs\CORONA\kemkes.php on line 20

This API has 450 arrays, but only 2 arrays came out, namely [0] and [1]

A: That's because you loop through the number of entries in the outer array which has the element nodes and probably another one that you cut off from the sample above. So, count($result) is 2 (you can even see in your output above: array(2) for the outermost array!). It seems you forgot to take the outermost 2-element array around the 450-element array into account! Or actually, you half did, because you instead of two loops inside of each other, but you are using the outer count in the inner loop which doesn't make sense.
You just need to access the inner nodes array directly:
  foreach ($result['nodes'] as $value) {
    echo $value["rs"] . "
";
    echo $value["umur"] . "
";
    echo $value["gender"] . "

";
  }


text:
Q: Facebook Graph API-Fetching status messages I am fetching walls of friends using the graph API in my .NET application.. For some friends i get there complete wall..but for the others few posts are missing...
For some friends status messages set by them on their wall are not coming with the JSON data...while messages posted by others on their wall are being retrieved correctly. When i look at their walls from the facebook website, all the posts are visible. But for some reason they are not being retrieved when i use the API.
What could be the cause of it?

A: Since the Graph API respects user privacy settings, it is possible that the friends who are posting to your friends' wall have changed their application privacy settings so that their posts are not accessible by third-party applications.


text:
Q: Can't display image with kivy I wanted to make a kivy program with two screens.
On the first screen there is only one button allowing you to go to the next screen.
On thesecond screen there are two buttons, one for going back to the first screen, and the other one is supposed to display an image on the whole screen.
I did this by making a function, that creates an image and adds it to the Box Layout.
I know, that the Image would not be displayed fullscreen, but I did not know a better solution.
But when I clicked the button, the whole program crashed.
Here is the source code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image

class Manager(ScreenManager):
    pass
class FirstScreen(Screen):

    def change_text(self):

        self.manager.current = 'second'
class SecondScreen(Screen):
    def display_image(self):
        bild = Image(source='Bild1.png')
        box1.add_widget(bild)
root_widget = Builder.load_string('''
Manager:
    FirstScreen:
    SecondScreen:
<FirstScreen>:
    name: 'first'
    BoxLayout:
        orientation: 'vertical'
        Button:
            id: b1
            text: 'Go to next Screen'
            on_release: root.change_text()
<SecondScreen>:
    name: 'second'
    BoxLayout:
        id: box1
        orientation: 'vertical'

        Button:
            id: b2
            text: 'Go back'
            on_release: app.root.current = 'first'
        Button:
            id: b3
            text: 'suprise'
            on_release: root.display_image()
''')
class Caption(App):
    def build(self):
        return root_widget

Caption().run()

And here is the error message:
File "<string>", line 26, in <module>
File "img.py", line 18, in display_image
   box1.add_widget(bild)
NameError: global name 'box1' is not defined

A: In order to use ids you need to access them via the ids object on the root rule widget. So instead of box1.add_widget(bild) you should use self.ids.box1.add_widget(bild).


text:
Q: iOS: Notification Center - What's the max length? I am sending a push notification to our app. I would like to know the max length of characters that can be shown when you pull down the notification center (I know that the payload is up to 256 bytes, but characters seem to be truncated after a certain number of characters. Also, I know the AlertView can have up to 107 characters. I am asking for the limit in the notification center).

A: Other way to go around of this limit, this is are using a
loc-key
loc-args
features of APNS.
See here at Localized Formatted Strings block


text:
Q: Craftcms does not send local emails using mailhog I need to send emails with craftcms, mailhog and containers ddev, but i don't receive emails in my inbox gmail, hotmail... I already configured my .env for local credentials according to the documentation, and I tried to configure it inside config/app.php but without success.
I need send e-mails with craftcms and mailhog.
localhost: 127.0.0.1  port: 1025


text:
Q: Can you catch in a using block? Can exceptions be caught inside a using block, and if so what is the syntax?
So, something like the following:
using (var creatingThing = new MyCreatingThing())
{
    creatingThing.CreateSomething();

    catch()
    {
        creatingThing.Rollback();
    }
}

Can this be done? Or do I need to write this code manually (ie without a using)?

A: You cannot implicitly enlist in the try...finally block that the compiler generates (for the using statement). You have to add another try statement, which will be nested within the generated block:
using (var creatingThing = new MyCreatingThing())
{
    try
    {
        creatingThing.CreateSomething();
    }
    catch
    {
        creatingThing.Rollback();
    }
}

A: Note, the a using is really a try/finally under the covers, so it may be easier the code it that way:
MyCreatingThing creatingThing = null;
try
{
    creatingThing = new MyNCreatingThing())
    creatingThing.CreateSomething();
}
catch()
{
      Console.WriteLine("An Exception happened");
      if (creatingThing !=null)
          creatingThing.Rollback();
}
finally
{
      if (creatingThing !=null)
           creatingThing.Dispose();
}

A: Sure, just add the try inside the using:
using (var creatingThing = new MyCreatingThing())
{
    try
    {
    creatingThing.CreateSomething();
    }
    catch(Exception ex)
    {
        creatingThing.Rollback();
    }
}

A: You can put a try/catch inside the using statement, or outside:
using (...)
{
    try
    {
        ...
    }
    catch
    {
        ...
    }
}

Or...
try
{
   using (...)
   {
       ...
   }
}
catch
{
    ...
}

However, you can't just put a catch block without a try block.
Choose the right one based on what whether you need to catch exceptions which are thrown by the resource acquisition expression, whether you want the resource to be disposed before your catch block is executed, and whether you need access to the resource variable within the catch block.


text:
Q: Is it possible to have pixelated graphics on a MacBook Pro due to a defunct trackpad?
had availed of the logic board replacement scheme for 2011 MacBook Pro's with faulty (AMD) graphics cards. The laptop came back from servicing with a new (refurbished as I understand) logic board. But while running a benchmarking test (Unigine Valley) the on screen graphics are extremely pixelated.
The service center suggested it was due to a faulty RAM. So I purchased new identical RAM. Same issue. After months of struggling with AppleCare and Apple Exec relations, they first asked me to get a clean install of the latest OS. Once that was done, the feedback from their engineering team is now that it "could be" due to the defunct trackpad (condition since before the repair, and I use a USB or bluetooth replacement, instead of replacing it out of warranty).
Is it at all possible that the screen graphics are pixelated because of a defunct trackpad?
I fear I am being scammed by Apple to pay for a pointless hardware repair...
The trackpad is actually not connected - the cable connecting it to the logic board is gone, so it is just out of service / disconnected. I am running stock OS and it works fine. The benchmarking tool works fine on other MacBook Pros. The trackpad has been out of service since before the repair, and this problem with the benchmarking test is after the repair. So I believe it is unrelated.

A: It's very common for one component it's connected electrically to another component to cause noise and other issues. Whether it's the most likely cause is debatable, but Apple's service centers have direct access to engineering and a huge wealth of repair data so they would be my first authority to go to determine what is likely and what is not.
Without the detailed diagnostics from your specific repairs as well as the actual service manuals it's hard to second-guess Apple.
Apple provides a nice (IMO) warranty of 90 days and any repair, so it's hard to see how they would be scamming you.  If you set down and catalog each interaction with AppleCare, have you spoken with them 10 or 20 times?
Also you need to collect all of the written estimates and repair details to know what components have and have not been examined by a technician.
The only time I've known Apple executive relations to be unable to resolve A customer issue is when Apple has already bent over backwards to accommodate their responsibilities and person requesting the repair is the one being unreasonable.  I certainly wouldn't accuse you of that with the little data presented, but if you really still unsure collect the facts and data you have and give it to someone who is somewhat impartial and have them give you their opinion.
Also, a final note - unless you are running stock OS or an apple benchmark, I've seen all sorts of gfx card mods and graphics tools cause exactly what you see. My guess is Apple knows other parts to be good and is guessing the trackpad is the most likely of the ones that remain in tested.
I would ask them the cost of a depot repair, and you'll have to be Ok with paying for it if they replace parts - even if the benchmark fails to run. If your Mac boots the normal OS fine, I would not pursue further repairs till the situation deteriorates.


text:
Q: Acessing Navigation Class properties in MVC4 View My Class is
public partial class Team
    {
        public Team()
        {
            this.Trials = new HashSet<Trials>();
            this.Users = new HashSet<Users>();
        }

        public int TeamId { get; set; }
        public string TeamName { get; set; }
        public string TeamDescription { get; set; }
        public virtual ICollection<Trials> Trials { get; set; }
    }

and in the view I am trying to accessthe attirbutes of Trial class like
@model Project.Classes.Team

         @for (int i = 0; i < Model.Trials.Count; i++ )
         {
                @Html.DisplayFor(x => Model.Trials.ElementAt(i).Name)
                @Html.HiddenFor(x => Model.Trials.ElementAt(i).Name)
                @Html.HiddenFor(x => Model.Trials.ElementAt(i).TrialID)
                @Html.CheckBoxFor(x => Model.Trials.ElementAt(i).isChk)

         }

When view is displayed it shows the Trials objects in the model and displays on the form but when form is posted then in the controller I dont get any value for Trials it shows 0 Trials...I think I am doing some thing wrong in the binding loop ...
Any help appreciated......

A: Got it working by changing the Team calss. Instead using
 public virtual ICollection<Trials> Trials { get; set; }

I changed it to IList
public virtual IList<Trials> Trials { get; set; }

and commented the
 //this.Trials = new HashSet<Trials>();

and in the View

         @for(int i=0; i<Model.Trials.Count; i++)
         {

                @Html.DisplayFor(x =>  x.Trials[i].Name)
                @Html.HiddenFor(x => x.Trials[i].Name)
                @Html.HiddenFor(x => x.Trials[i].TrialID)
                @Html.CheckBoxFor(x => x.Trials[i].isChk)

         }

Now I am getting the true model binging value for Team and Trials inside the team........


text:
Q: R: reshape elements of a data frame keeping order of variables in sequence I'm struggling with reshaping 12 separate list elements [which are in data frame format] and having the values stay in the right sequential order. These are measurements by day, with value 1 corresponding to the first day of the month measurement, and so on until value 31, the maximum possible days/month. This is in a horizontal. For missing measurements/months where there are fewer than 31 days, -9999 appears. The -9999 is not the problem here.
> myplist[[1]]
     COOPID YEAR MONTH ELEMENT value 1 value 2 value 3 value 4 value 5 value 6
3    170100 1982     9    PRCP       0      70      15       0       0       0
8    170100 1982    10    PRCP       0      10       0       0       0       0
13   170100 1982    11    PRCP       2      13       0     170       0       5
18   170100 1982    12    PRCP       0       0       0       0       2       5
23   170100 1983     1    PRCP       2       0       0       0       0      10
28   170100 1983     2    PRCP   -9999       0       0      52       6       0

My goal is to have the list elements oriented vertically so that each day has its own row, so it would look like this:
> myplist[[1]]
    YEAR MONTH DAY PRCP
    1982     9   1    0
    1982     9   2   70
    1982     9   3   15

I tried this code:
melt(myplist[[1]], id.vars = c("COOPID", "YEAR", "MONTH", "ELEMENT"))

But it listed the value 1 of each month rather than the desired sequence of value 1, value 2, ..., value 31.
      COOPID YEAR MONTH ELEMENT variable value
1     170100 1982     9    PRCP  value 1     0
2     170100 1982    10    PRCP  value 1     0
3     170100 1982    11    PRCP  value 1     2
4     170100 1982    12    PRCP  value 1     0
5     170100 1983     1    PRCP  value 1     2

And this code returned this undesired output and error:
> reshape(myplist[[1]], idvar = c("YEAR","MONTH"),varying =print(paste0("value",1:31)),sep = "",
+         timevar = c("YEAR","MONTH"),direction = "long")
 [1] "value1"  "value2"  "value3"  "value4"  "value5"  "value6"  "value7"  "value8"  "value9"  "value10"
[11] "value11" "value12" "value13" "value14" "value15" "value16" "value17" "value18" "value19" "value20"
[21] "value21" "value22" "value23" "value24" "value25" "value26" "value27" "value28" "value29" "value30"
[31] "value31"
Error in `[.data.frame`(data, , varying.i) : undefined columns selected

I also tried dcast to no avail, and other asked questions on the this and other sites don't seem to get at the issue I'm having. I think the root of the problem is that my range of years has variable length days per month (goes to the actual last day of a given month), but each month in my measurement data has 31 day values regardless.

A: Using a tidy approach, I would gather the value columns into long format and then gsub to be day of the month.
library(tidyr)
library(dplyr)

df <- read.table(text = "
     COOPID YEAR MONTH ELEMENT 'value 1' 'value 2' 'value 3' 'value 4' 'value 5' 'value 6'
     170100 1982     9    PRCP         0        70        15         0         0         0
     170100 1982    10    PRCP         0        10         0         0         0         0
     170100 1982    11    PRCP         2        13         0       170         0         5
     170100 1982    12    PRCP         0         0         0         0         2         5
     170100 1983     1    PRCP         2         0         0         0         0        10
     170100 1983     2    PRCP     -9999         0         0        52         6         0
                 ", header = TRUE, stringsAsFactors = FALSE) %>% as_tibble

df %>%
  select(-ELEMENT) %>%
  gather(DAY, PRCP, -c(COOPID, YEAR, MONTH)) %>%
  mutate(DAY = as.integer(gsub("value\\.", "", DAY))) %>%
  arrange(COOPID, YEAR, MONTH, DAY)

# # A tibble: 36 x 5
#    COOPID  YEAR MONTH   DAY  PRCP
#     <int> <int> <int> <int> <int>
#  1 170100  1982     9     1     0
#  2 170100  1982     9     2    70
#  3 170100  1982     9     3    15
#  4 170100  1982     9     4     0
#  5 170100  1982     9     5     0
#  6 170100  1982     9     6     0
#  7 170100  1982    10     1     0
#  8 170100  1982    10     2    10
#  9 170100  1982    10     3     0
# 10 170100  1982    10     4     0
# # ... with 26 more rows


text:
Q: Modify a particular row/column of a NumPy array How do I modify particular a row or column of a NumPy array?
For example I have a NumPy array as follows:
P = array([[1, 2, 3],
           [4, 5, 6]])

How do I change the elements of first row, [1, 2, 3], to [7, 8, 9] so that the P will become:
P = array([[7, 8, 9],
           [4, 5, 6]])

Similarly, how do I change second column values, [2, 5], to [7, 8]?
P = array([[1, 7, 3],
           [4, 8, 6]])

A: Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python.
To select a row in a 2D array, use P[i]. For example, P[0] will return the first row of P.
To select a column, use P[:, i]. The : essentially means "select all rows". For example, P[:, 1] will select all rows from the second column of P.
If you want to change the values of a row or column of an array, you can assign it to a new list (or array) of values of the same length.
To change the values in the first row, write:
>>> P[0] = [7, 8, 9]
>>> P
array([[7, 8, 9],
       [4, 5, 6]])

To change the values in the second column, write:
>>> P[:, 1] = [7, 8]
>>> P
array([[1, 7, 3],
       [4, 8, 6]])

A: In a similar way if you want to select only two last columns for example but all rows you can use:
print P[:,1:3]

A: If you have lots of elements in a column:
import numpy as np
np_mat = np.array([[1, 2, 2],
                   [3, 4, 5],
                   [5, 6, 5]])
np_mat[:,2] = np_mat[:,2] * 3
print(np_mat)

It is making a multiplied by 3 change in third column:
    [[ 1  2  6]
     [ 3  4 15]
     [ 5  6 15]]


text:
Q: Sorting and subsorting a variant array I would like to code the following in VBA, a function of signature
Public Function MySort( v as Variant) as Variant

that takes a variant v having names in its first columns and notes in its second, checks if it has two columns, throws an error if it hasn't, and if it has two rows, does the following : it sorts v's rows according to v's second column in decreasing, and then, inside a group of same note, sorts it alphabetically. For instance, the function MySort will send the variant
A   14
D    3
B   14
E    3
C    3

to the variant
A   14
B   14
C    3
D    3
E    3

from teh OP's comment below
I have tried this, without success :
Public Function MySort(r As Range) As Range
    Dim r1 As Range
    Dim r2 As Range

    Set r1 = r.Columns(1)
    Set r2 = r.Columns(2)

    r.Sort Key1:=r1, Order1:=xlDescending, DataOption1:=xlSortNormal
    r.Sort Key2:=r2, Order2:=xlAscending, DataOption2:=xlSortNormal

    Tri = r
End Function

A: VBA Functions do not modify the values or structure on a worksheet other than the cell that they reside in. A function could be used to sort a variant array and pass the reordered results back to a sub which returns the values back into the worksheet but you are better off just using a sub to perform the sort unless you have some custom sort criteria that cannot be handled conventionally.
Sub sort_A1CR(Optional ws As Variant) 'expect a worksheet object, not a worksheet name

    If IsMissing(ws) Then Set ws = ActiveSheet
    With ws.Cells(1, 1).CurrentRegion
        .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                    Key2:=.Columns(2), Order2:=xlDescending, _
                    Orientation:=xlTopToBottom, Header:=xlYes
    End With

End Sub

Your sample code contradicted your results. This sorts with column A as the primary key in an ascending order. If duplicate values are found in column A then column B is used as the sub-sort in a descending manner.


text:
Q: Do I need to use volatile keyword if I declare a variable between mutexes and return it? Let's say I have the following function.
std::mutex mutex;

int getNumber()
{
    mutex.lock();
    int size = someVector.size();
    mutex.unlock();
    return size;
}

Is this a place to use volatile keyword while declaring size? Will return value optimization or something else break this code if I don't use volatile? The size of someVector can be changed from any of the numerous threads the program have and it is assumed that only one thread (other than modifiers) calls getNumber().

A: No. But beware that the size may not reflect the actual size AFTER the mutex is released.
Edit:If you need to do some work that relies on size being correct, you will need to wrap that whole task with a mutex.

A: You haven't mentioned what the type of the mutex variable is, but assuming it is an std::mutex (or something similar meant to guarantee mutual exclusion), the compiler is prevented from performing a lot of optimizations. So you don't need to worry about return value optimization or some other optimization allowing the size() query from being performed outside of the mutex block.
However, as soon as the mutex lock is released, another waiting thread is free to access the vector and possibly mutate it, thus changing the size. Now, the number returned by your function is outdated. As Mats Petersson mentions in his answer, if this is an issue, then the mutex lock needs to be acquired by the caller of getNumber(), and held until the caller is done using the result. This will ensure that the vector's size does not change during the operation.

Explicitly calling mutex::lock followed by mutex::unlock quickly becomes unfeasible for more complicated functions involving exceptions, multiple return statements etc. A much easier alternative is to use std::lock_guard to acquire the mutex lock.
int getNumber()
{
    std::lock_guard<std::mutex> l(mutex); // lock is acquired
    int size = someVector.size();
    return size;
} // lock is released automatically when l goes out of scope

A: Volatile is a keyword that you use to tell the compiler to literally actually write or read the variable and not to apply any optimizations. Here is an example
int example_function() {
int a;
volatile int b;
a = 1; // this is ignored because nothing reads it before it is assigned again
a = 2; // same here
a = 3; // this is the last one, so a write takes place
b = 1; // b gets written here, because b is volatile
b = 2; // and again
b = 3; // and again
return a + b;
}

What is the real use of this?  I've seen it in delay functions (keep the CPU busy for a bit by making it count up to a number) and in systems where several threads might look at the same variable.    It can sometimes help a bit with multi-threaded things, but it isn't really a threading thing and is certainly not a silver bullet


text:
Q: How do you concatenate several arrays into one? const sumAll = function (min, max) {
  const allSums = [];
  const initialValue = 0;

  for (let i = min; i <= max; i++) {
    allSums.push([i]);
  }
  console.log(allSums); //

  let sumTotal = allSums.reduce(function (acc, curr) {
    acc += curr;
    return acc;
  }, initialValue);

  console.log(sumTotal);
};

sumAll(1, 4) returns 01234 instead of 10.
I can see that allSums is 4 arrays inside of an array. How would I go about concatenating them? Thank you for the help!

A: Realised this could easily be achieved by adding a spread operator before pushing to allSums.
for (let i = minNumber; i <= maxNumber; i++) {
    allSums.push(...[i]);
  }

A: No need to create an array at all, you can Array#push the value directly. That's the goal, right? So,
allSums.push([i]); //or allSums.push(...[i]);

Should be:
allSums.push( i );


text:
Q: two-sum algorithm complexity Below code checks if the sum of any pairs of numbers on an array equals to zero. I'm trying to workout the complexity by considering how many times major operations such as variable declarations, value assignments, comparisons, increments, array accesses etc. Normally the complexity would be O(N^2) but I'm very confused when I have to consider the operations specified above. How should I approach this?
int count = 0;
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
if(a[i] + a[j] == 0)
count++;

A: I'm going to indent the code and highlight each operation explicitly:
int count = 0; // <-- 1 operation

for(int i=0; i<N; i++) // <-- 2 operations per iteration
    for(int j=i+1; j<N; j++) // <-- 2 operations per iteration
        if(a[i] + a[j] == 0) // <-- 4 operations
            count++; // <-- impossible to tell without knowing a. Counting as 1 operation

Here is how you would compute the total number of operations:

That expression simplifies to:

Which is your answer. Note that this is O(N^2), which is consistent with your earlier observation.


text:
Q: date command not found in shell script my shell script backup.sh as below, when i execute this script, i got the error "date: command not found". I have checked that there are no space between = and the parameters.
Could anydody give an explain about this error.
Thanks.
x00004:/home/ # cat backup.sh
#!/bin/sh
set +x

source ./conf.sh

if [ $# != 2 ] ; then
    echo " Usage: $0 [sftp user] [sftp pwd]"
    exit 1;
fi

DATE=`date +%y-%m-%d--%H:%M:%S`
echo "${DATE}"
file=test.tar.gz
echo "Starting to backup files..."

#to backup files to sftp server

x00004:/home/ # ./backup.sh usr pwd
./backup.sh: line 11: date: command not found

Starting to backup files...
x00004:/home/poc/src #

A: Shells can't find commands if the commands aren't in directories in $PATH. Quick fix: replace date with /bin/date. However, a similar problem might occur in conf.sh or backup.sh, so a more global solution is to echo "$PATH" at the beginning of your script, figure out what's missing, and and fix it, e.g., PATH=/bin:$PATH.

A: Best way is to use the bash/shell command called command -v to dynamically check where is your date path.
DATE_BIN=$(command -v date)
DATE=`${DATE_BIN} +%y-%m-%d--%H:%M:%S`


text:
Q: How do I use 'git filter-branch' to update the SHA of a submodule? Let's assume that I have two Git repositories, A and B. B is a submodule of A.
For the sake of simplicity, let's also assume that I have a magic function, get_sha_B that, given an SHA commit from A, returns the desired SHA commit of B.
How do I run filter-branch on repo A such that each commit of repo A is rewritten to point to the desired commit of repo B, as returned by get_sha_B?
Thank you!

A: Figured it out! I'm going to answer my own question here:
I can use git update-index in conjunction with git filter-branch --index-filter.
Here's how to call update-index to modify the commit SHA of a submodule:
git update-index --cacheinfo 160000 88e6a302c42840440f9faac73f27efc6a3e0c1a6 pathto/mysubmodule

As best as I understand it, the 160000 is a magic number in Git used to identify a submodule.


text:
Q: Possible incorrect usage of custom eval_metric in MXNet I am working on a problem and were trying to solve using MXNet. I was trying to use a custom metric in the code.
The code for the same is:
def calculate_sales_from_bucket(bucketArray):
    return numpy.asarray(numpy.power(10, calculate_max_index_from_bucket(bucketArray)))

def calculate_max_index_from_bucket(bucketArray):
    answerArray = []
    for bucketValue in bucketArray:
        index, value = max(enumerate(bucketValue), key=operator.itemgetter(1))
        answerArray.append(index)
    return answerArray

def custom_metric(label, bucketArray):
    return numpy.mean(numpy.power(calculate_sales_from_bucket(label)-calculate_sales_from_bucket(bucketArray),2))

model.fit(
    train_iter,         # training data
    eval_data=val_iter, # validation data
    batch_end_callback = mx.callback.Speedometer(batch_size, 1000),    # output progress for each 1000 data batches
    num_epoch = 10,     # number of data passes for training
    optimizer = 'adam',
    eval_metric = mx.metric.create(custom_metric),
    optimizer_params=(('learning_rate', 1),)
)

I am getting the output as:
INFO:root:Epoch[0] Validation-custom_metric=38263835679935.953125
INFO:root:Epoch[1] Batch [1000]      Speed: 91353.72 samples/sec        Train-custom_metric=39460550891.057487
INFO:root:Epoch[1] Batch [2000]        Speed: 96233.05 samples/sec  Train-custom_metric=9483.127650
INFO:root:Epoch[1] Batch [3000] Speed: 90828.09 samples/sec   Train-custom_metric=57538.891485
INFO:root:Epoch[1] Batch [4000] Speed: 93025.54 samples/sec   Train-custom_metric=59861.927745
INFO:root:Epoch[1] Train-custom_metric=8351.460495
INFO:root:Epoch[1] Time cost=9.466
INFO:root:Epoch[1] Validation-custom_metric=38268.250469
INFO:root:Epoch[2] Batch [1000]     Speed: 94028.96 samples/sec       Train-custom_metric=58864.659051
INFO:root:Epoch[2] Batch [2000]     Speed: 94562.38 samples/sec       Train-custom_metric=9482.873310
INFO:root:Epoch[2] Batch [3000]      Speed: 93198.68 samples/sec        Train-custom_metric=57538.891485
INFO:root:Epoch[2] Batch [4000]      Speed: 93722.89 samples/sec        Train-custom_metric=59861.927745
INFO:root:Epoch[2] Train-custom_metric=8351.460495
INFO:root:Epoch[2] Time cost=9.341
INFO:root:Epoch[2] Validation-custom_metric=38268.250469

In this case, irrespective of change in train-custom_metric for batches, the train-custom_metric is still the same.
Like in case of batch 1000 for epoch 1 and epoch 2.
I believe that this is an issue as the Train-custom_metric and Validation-custom_metric is not changing irrespective of the value of epoch steps.
I am a beginner in MXNet and I might be wrong in this assumption.
Can you confirm if I am passing eval_metric in the correct way?

A: Not sure I understand the problem. Your output shows train-custom-metric giving different values, it just happens to have given the same result for the last two batches of each epoch. That may just be a quirk of how your model is converging.
One thing to be clear on is that eval_metric is only used to give debug output -- it's not actually used as the loss function during learning:
https://github.com/apache/incubator-mxnet/issues/1915


text:
Q: How to avoid double space between items when using RecyclerView with StaggeredGridLayoutManager? I'm using RecyclerView with StaggeredGridLayoutManager to make a two-column list. But how to set a right margin between left column and right column. I have used this code to make right margin from top, but how to solve double space between to columns.
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public SpacesItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;

        // Add top margin only for the first or second item to avoid double space between items
        // Add top margin only for the first or second item to avoid double space between items
        if((parent.getChildCount() > 0 && parent.getChildPosition(view) == 0)
            || (parent.getChildCount() > 1 && parent.getChildPosition(view) == 1))
        outRect.top = space;
}

And in Activity:
recyclerView.addItemDecoration(new SpacesItemDecoration(20));

I've tried to use view.getX(), it always return 0.
Can anyone help me? Many thanks!

A: In your case you can setting the both margin to the RecyclerView .But in my case there is a image match the screen width in the RecyclerView ,and I use the ItemDecoration to solve the problem.
  class ViewItemDecoration extends RecyclerView.ItemDecoration {

    public ViewItemDecoration() {
    }

    @Override
    public void getItemOffsets(Rect outRect, final View view, final RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
        int type = adapter.getItemViewType(position);
        switch(type){
          case YOUR_ITEMS:
                if (spanIndex == 0) {
                    outRect.left = 10;
                    outRect.right = 5;
                } else {//if you just have 2 span . Or you can use (staggeredGridLayoutManager.getSpanCount()-1) as last span
                    outRect.left = 5;
                    outRect.right = 10;
                }
        }
    }

}

A: public class EqualGapItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;

    public EqualGapItemDecoration(int spanCount, int spacing) {
        this.spanCount = spanCount;
        this.spacing = spacing;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();

        if (layoutParams.isFullSpan()) {
            outRect.set(0, 0, 0, 0);
        } else {
            int spanIndex = layoutParams.getSpanIndex();
            int layoutPosition = layoutParams.getViewLayoutPosition();
            int itemCount = parent.getAdapter().getItemCount();

            boolean leftEdge = spanIndex == 0;
            boolean rightEdge = spanIndex == (spanCount - 1);

            boolean topEdge = spanIndex < spanCount;
            boolean bottomEdge = layoutPosition >= (itemCount - spanCount);

            int halfSpacing = spacing / 2;

            outRect.set(
                    leftEdge ? spacing : halfSpacing,
                    topEdge ? spacing : halfSpacing,
                    rightEdge ? spacing : halfSpacing,
                    bottomEdge ? spacing : 0
            );
        }
    }
}

A: I solved it myself by setting item margin and RecyclerView padding. Both margin and padding are half of expected space, so the problem disappeared.

A: The following code will handle StaggeredGridLayoutManager, GridLayoutManager, and LinearLayoutManager.
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

    private int halfSpace;

    public SpacesItemDecoration(int space) {
        this.halfSpace = space / 2;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        if (parent.getPaddingLeft() != halfSpace) {
            parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
            parent.setClipToPadding(false);
        }

        outRect.top = halfSpace;
        outRect.bottom = halfSpace;
        outRect.left = halfSpace;
        outRect.right = halfSpace;
    }
}

A: It is possible to set padding to the two sides of the RecyclerView:
myRecyclerView.setPadding(10,0,10,0);

In this way you can equalize the space on the sides and between the columns.

A: I would slightly change and modify both of the answer for relative question
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private final int mSpace;

    public SpacesItemDecoration(int space) {
        this.mSpace = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, final View view, final RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
        if (spanIndex == 0) {
            outRect.left = 30;
            outRect.right = 15;
        } else {//if you just have 2 span . Or you can use (staggeredGridLayoutManager.getSpanCount()-1) as last span
            outRect.left = 15;
            outRect.right = 30;
        }
        outRect.bottom = 30;
        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = 30;
            outRect.right = 30;
        }
    }
}

A: Set different left/right space in ItemDecoration according to spanindex only works well for item view has fixed size.
If the item view contain image view set wrap_content in height, the item view may change span position, but span index not updated as you wish, the margin will be a mess.
My way is, using the symmetrical left/right space for view item.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // init
    recyclerView = (RecyclerView) rv.findViewById(R.id.img_waterfall);
    layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(new MyAdapter(getContext()));
    recyclerView.addItemDecoration(new SpacesItemDecoration(
        getResources().getDimensionPixelSize(R.dimen.space)));
}

private static class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private final int space;
    public SpacesItemDecoration(int space) {
        this.space = space;
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        outRect.bottom = 2 * space;
        int pos = parent.getChildAdapterPosition(view);
        outRect.left = space;
        outRect.right = space;
        if (pos < 2)
            outRect.top = 2 * space;
    }
}

Then set the same padding for RecylerView(left/right)
android:paddingLeft="@dimen/space"
android:paddingRight="@dimen/space"
    <android.support.v7.widget.RecyclerView
        android:id="@+id/img_waterfall"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/space"
        android:paddingRight="@dimen/space"/>

A: I solved this in 3 steps by the following way:

*

*Add marginStart and marginEnd to the parent (RecyclerView) with the same value

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="@dimen/margin_small"
    android:layout_marginEnd="@dimen/margin_small"
    app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
    app:spanCount="2" />

*Create a custom ItemDecorator class and extend of RecyclerView.ItemDecoratior. Get marigns parent and then modifying the internal margins in a half of each child according to the case

class SpaceItemDecorator : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)

        val layoutParams = view.layoutParams as StaggeredGridLayoutManager.LayoutParams
        val spanIndex = layoutParams.spanIndex

        if (spanIndex == 0) {
            val marginParentEnd = parent.marginEnd
            layoutParams.marginEnd = marginParentEnd / 2
        } else {
            val marginParentStart = parent.marginStart
            layoutParams.marginStart = marginParentStart / 2
        }

        view.layoutParams = layoutParams
    }
}

*Add the custom ItemDecorator to the recyclerView

recyclerview.addItemDecoration(SpaceItemDecorator())

That is all, without margins/paddings hardcode and in Koltin xD
note: It is important not to establish any horizontal margin in the child's view layout

A: The following code handles StaggeredGridLayout without problems(at least from my experience). You only need to give spacing to SpaceItemDecorator.
class SpaceItemDecoration(private val spacing: Int) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {

        val lm = parent.layoutManager as StaggeredGridLayoutManager
        val lp = view.layoutParams as StaggeredGridLayoutManager.LayoutParams

        val spanCount = lm.spanCount
        val spanIndex = lp.spanIndex
        val positionLayout = lp.viewLayoutPosition
        val itemCount = lm.itemCount
        val position = parent.getChildAdapterPosition(view)

        outRect.right = spacing / 2
        outRect.left = spacing / 2
        outRect.top = spacing / 2
        outRect.bottom = spacing / 2

        if (spanIndex == 0) outRect.left = spacing

        if (position < spanCount) outRect.top = spacing

        if (spanIndex == (spanCount - 1)) outRect.right = spacing

        if (positionLayout > (itemCount - spanCount)) outRect.bottom = spacing
    }
}

You can get spacing in pixels like this:
 val spacingInPixels = resources.getDimensionPixelSize(R.dimen.grid_layout_margin)

And then you just need to assign item decoration to your recycler view:
recycler_view.addItemDecoration(
                  SpaceItemDecoration(
                        spacingInPixels
                    )
                )


text:
Q: Twitter API - Getting list of users who favorited a status I want to get a list of users who favorited a specific status through the Twitter API.
I can see that each statuses have the amount of favorites it got but I need the list of users who made the favorite.
Any ideas how this can be achieved?

A: Here is a workaround or hack implemented in Python 2.7.x:
import urllib2
import re

def get_user_ids_of_post_likes(post_id):
    try:
        json_data = urllib2.urlopen('https://twitter.com/i/activity/favorited_popup?id=' + str(post_id)).read()
        found_ids = re.findall(r'data-user-id=\\"+\d+', json_data)
        unique_ids = list(set([re.findall(r'\d+', match)[0] for match in found_ids]))
        return unique_ids
    except urllib2.HTTPError:
        return False

# Example:
# https://twitter.com/golan/status/731770343052972032

print get_user_ids_of_post_likes(731770343052972032)

# ['13520332', '416273351', '284966399']
#
# 13520332 +> @TopLeftBrick
# 416273351 => @Berenger_r
# 284966399 => @FFrink


text:
Q: How to get Hot Module Replacement work on Async Reducers? I'm working on a Redux project with dynamic routes and async reducers. I simply inject reducers with Dan's method in this question. It becomes quite tricky when I'm trying to write the module.hot.accept function for my project. This is what my configureStore function is like

function configureStore(initialState = {}) {
  let store = createStore(createReducer(), initialState, compose(
    applyMiddleware(
      thunk
    )
  ))

  store.asyncReducers = {}

  if (process.env.NODE_ENV == 'development') {
    if (module.hot) {
      module.hot.accept('./routes/root', () =>
        store.replaceReducer(createReducer(store.asyncReducers))
      )
    }
  }

  return store
}

After I change some code inside of one of the child routes' reducer, I got a warning says the modules which have changed (and their parents) do not know how to hot reload themselves. I think the problem is that injectAsyncRecuder has not been called since I change the code of the reducer.
How can I make HMR work for async reducers?
=====
Update:
After some research, please let me rephrase my question. Let's say there are 3 levels of routes, A, B and C. A requires B, B requires C. B requires reducer1. C requires reducer2 and reducer3.
.
├── Route A
│   ├── Route B
│   |   ├── Reducer 1
│   |   ├── Route C
│   |   |   ├── Reducer 2
│   |   |   ├── Reducer 3

When Reducer 3 becomes outdated, Route C and Route B will also become outdated. Let's suppose I put hot.module.accept in a file which requires Routes A as hot.module.accept('./routesA', cb). I'm wondering how can I check the outdated module stack to find the outdated reducer. In that case, I can put update methods in all of the reducers so that they can know hot to inject themselves when becoming outdated.


text:
Q: longlistselector header/footer click I'm very new in WindowsPhone development and at this moment I'm facing a problem that I couldn't find a way to fix. I'm using a LongListSelector to show some information on the device screen and also a Header and a Footer with some static information. Everything looks right, but I can't handle the Click/Tap on the Header and on the Footer (the other items are working properly).
Someone know how to do it? Is there any event that tells my .cs that someone clicked on the footer or on the header view?
Thanks!

A: Implement ListFooter and ListHeader in your xaml.
Example :
 <phone:LongListSelector x:Name="myLongListSelector"
                         Background="Transparent"
                         IsGroupingEnabled="True"
                         HideEmptyGroups="True">
           <phone:LongListSelector.ListFooter>
                  <Grid Height="70" Tap="Grid_Tap">
                       <TextBlock Text="Texxt" Foreground="White"
                                       VerticalAlignment="Center"
                                       FontWeight="Bold"
                                       FontSize="20"/>
                   </Grid>
            </phone:LongListSelector.ListFooter>
 </phone:LongListSelector>

Now in your cs file, you have :
private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{

}


text:
Q: How to close a frame in Java without closing the cmd prompt? Here is the frame (i.e. java.awt.Frame) code. When I click the close button on the window it doesn't close and every time I have to close the the cmd prompt from where I launch this program. How to make it close?
import java.awt.*;

public class FrameExample {

private Frame f;

public FrameExample () {
    f=new Frame("Hi its Harish");
}

public void launchFrame() {
    f.setSize(470,470);
    f.setVisible(true);
}

public static void main(String args[]) {
    FrameExample guiWindow=new FrameExample();
    guiWindow.launchFrame();
}
}

A: add this listener into your code
f.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent we){
      System.exit(0);
   }
});

A: implement window listener....
inside windowClosed call System.exit(0)

A: AWT frame doesn't support setDefaultCloseOperation(). Use,
f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        f.dispose();
    }
});

A: If you were using JFrame (swing) rather than Frame (awt), you would use JFrame.setDefaultCloseOperation(int) and specify EXIT_ON_CLOSE.
f.setDefaultCloseOperation(EXIT_ON_CLOSE);

Since you are not, the WindowListener is the way to go.

A:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

It's explained here:
http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

A: You can change the close operation:
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


text:
Q: html body scrollbar position I am working on a page with a menu bar.
the height of the menu bar is 40px
and I set the top of the body tag to 40px too.
However, the scrollbar of the body tag is still at top=0px.

A: To do this approach you can use flex display. you should wrap your main content in another section and scroll the wrapper inside itself.
here an example :
<body>
   <nav class="nav">
      <!-- *********** your nav items ******************* -->
   </nav>
   <main class="content">
      <!-- your content should be placed here ****************-->
   </main>
</body>

and the CSS code :
body {
   display: flex;
   height: 100vh;
   width: 100vw;
   flex-direction: column;
   overflow: hidden;
}
.nav {
   height: 40px;
  background: red;
}
.content {
   flex: 1;
   overflow-y: auto;
   overflow-x: hidden;
  background: blue;
}


text:
Q: Kivy RecycleView: Get indices of all data items that are currently in view I need to get the indices of all data items that are currently in view in a Kivy RecycleView widget. I want to display many Image widgets for which I render a texture and apply it to them. To save memory I need to delete these textures if they are not in view any more. I tried using the Kivy RecycleView example and modify it for my needs:
class SelectableImage(RecycleDataViewBehavior, Image):
    def refresh_view_attrs(self, rv, index, data):
        #Catch and handle the view changes
        #print in view
        print(index)
        #call initial function of image class
        return super(SelectableImage, self).refresh_view_attrs(rv, index, data)

The problem here is that refresh_view_attrs() only fires when a new Image widget gets added to the view. Thus I can only know what that last Image is, but not if there are any other in view. For this I'd also need to know which widget disappeared from the view. Is there any function in the RecycleView widget that I can use to obtain such information? Maybe there is a function that gets called whenever the view changes?

A: Okay, I found three possible solutions for my issue:
1. Solution
Calculate the position of all the Image widgets yourself and compare it with the position of the scrollbar to get the widgets that are currently displayed.
This is quite hacky and the RecycleView already does this internally. Thus I'd save the unnecessary computing and avoid this approach.
2. Solution
Use the get_visible_view(index) function of the view_adapter property of a RecycleView. This returns the currently visible view associated with index. If it return None, the view associated with index is not visible right now. This is how it's called for example:
self.myRecycleView.view_adapter.get_visible_view(index)

You could loop through the entire length of your data list and check for each item (the index in the list) if it is currently displayed or not.
3. Solution
My favourite approach: Use get_view_index_at(pos) of the layout_manager property to check what view index is at the given coordinates. This way you could check which item is at the top of the RecycleLayout widget and which one is at the bottom. You need to use coordinate transformation though. Example:
#get position at top center of RecycleView (upper limit)
pos = self.myRecycleView.to_local(self.myRecycleView.center_x, self.myRecycleView.height)
#check which items collides with the given position
print(self.myRecycleView.layout_manager.get_view_index_at(pos))

I hope this clears some things up!


text:
Q: Why is my hasNextLine() while loop only working one time? I have been working on this for hours and can't find the problem by myself or online. I dont know why the first loop does work and the second does not proceed past the first itteration.
File adjacencies = new File(adjacenciesFile);
Scanner adjacenciesScanner = new Scanner(adjacencies);
//idk why this works and the while loop after doesn't
/*
while(adjacenciesScanner.hasNextLine()){
        System.out.println(adjacenciesScanner.nextLine());
    }
*/

while(adjacenciesScanner.hasNextLine()){
    ArrayList<Country> adjacentCountries = new ArrayList<Country>();
    String[] adjacenciesNames = adjacenciesScanner.nextLine().split(",");

    for(String countryName : adjacenciesNames){
        adjacentCountries.add(this.countries.get(countryName));
    }
    System.out.println(adjacentCountries);
    adjacentCountries.remove(0);
    this.countries.get(adjacenciesNames[0]).addAdjacencies(adjacentCountries);
}

This is the file that I am reading in:
Alaska,Alberta,Northwest Territory,Kamchatka
Alberta,Alaska,Northwest Territory,Ontario,Western United States
Central America,Western United States,Venezuela
Eastern United States,Western United States,Ontario,Quebec
Greenland,Northwest Territory,Ontario,Quebec,Iceland
Northwest Territory,Alaska,Greenland,Ontario,Alberta

There is no exception, it just doesn't run more than once

A: If you set a break point and run it in debug mode, you should see exactly why it's exiting the loop. Looks fine to me, if anything, you may be getting an exception on your split().


text:
Q: Linq: help me to make this work I have this column:
    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.
i can do with a foreach, but not a good idea for performance.
u guys can help me?
if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory
and i cant see a way to do this without a foreach

A: You should group all person skills by person id, and then select only those groups, which contain both given category and sub category:
unitOfWork.PersonSkillsRepository.GetAll()
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)

For optimization, you can filter out skills which do not match any of given categories before grouping.
unitOfWork.PersonSkillsRepository.GetAll()
          .Where(p => p.IdCategory == ids.IdCategory
                   || p.IdSubCategory == ids.IdSubCategory)
          .GroupBy(p => p.PersonId)
          .Where(g => g.Any(p => p.IdCategory == ids.IdCategory)
                   && g.Any(p => p.IdSubCategory == ids.IdSubCategory))
          .Select(g => g.Key)

A: entities.Where(z => z.categoryId == 47 || z.subCategoryId == 424)
    .GroupBy(z => z.personId)
    .Where(z => z.Count() == 2)
    .SelectMany(z => z.ToList());

will likely get you the data that you need.
That query says 'filter the data and only return those where categoryId is 47 or subCategoryId = 424'. Then it groups them together and checks that there are two of them (i.e. one row for the categoryId and one for the subCategoryId).

A: I just Showed the data of yours in Image
The issue is that you don't have any value against CategoryId=47 in column SubCategoryId thats why when you search both of them together it gives nothing.
Try it by adding any value in SubCategoryId against CategoryId=47...

A: EDIT:
After the question is more clarified the following code should work
        if (ids.IdCategory != null && ids.IdSubCategory != null)
        {
            query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => (m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory) && m.IdPerson != 101);
        }

Firstly your data will return null for your search criteria. Following are some example of linq that might help this scenario.
You can do different kind of linq.
    List<CollectionObject> ColObj = CollectionObject.GetListCollectionObj();

    List<CollectionObject> LinqResult = ColObj.Where(x => x.CategoryID == 47 && x.SubcategoryID == null).ToList();

The following code works fine with the linq statements above.
    class CollectionObject
    {
        public int PersonID { get; set; }
        public int? CategoryID { get; set; }
        public int? SubcategoryID { get; set; }

    public static List<CollectionObject> GetListCollectionObj()
    {
        List<CollectionObject> LColObj = new List<CollectionObject>();

        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 425 });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = null, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = null, SubcategoryID = 424 });

        return LColObj;
    }
}

A: The following would do, but you should be aware your way of storing data is quite odd.
(I mean, aren't all your subcategories related to a category ?)
// gets all the Ids of people of category 47
var personIds = entities
               .Where(x => x.categoryId == 47)
               .Select(x => x.PersonId)
               .Distinct()
               .ToList();
// gets all rows of people of category 47 and subcategory 424
var result = entities
            .Where(x => personIds.Contains(x.PersonId) && x.subCategoryId == 424)
            .ToList();

Linked dotnetfiddle.

A: Well, while I was working on mine, it seems 3 other people came up with the same thing, so I'll throw in mine --- with the critical addition the OP needs....
Func<IGrouping<int, CollectionObject>, bool> query  =
        gp=>
              gp.Any(g=>g.CategoryID == 47) &&
              gp.Any(g=>g.SubcategoryID == 424);

var q = (from p in ColObj
        group p by p.PersonID)
        .Where(query);

You'll need to replace  query with your one-field versions on occasion.


text:
Q: How to tweak the following purely numerical code I am using the following numerical function in my program and I would like to speed it up.
calculate[mm_, nn_, pp_, ff_, quiet_] :=
  Module[{n, y, m, z, f, k, p, l, τ},
   h[0, 0, 0] = 1;
   h[n_, 0, y_] := If[Mod[n, 2] == 0,
     n!*y^(n/2)/((n/2)!),
     0];

   If[quiet != 1,
    If[Simplify[h[4, 0, -1] - HermiteH[4, 0]] === 0, ,
     Print["Bogus definition of h[n_,0,y_]"]]];
   If[quiet != 1,
    If[Simplify[h[3, 0, -1] - HermiteH[3, 0]] === 0, ,
     Print["Bogus definition of h[n_,0,y_]"]]];

   hh[m_, n_, 0, y_, 0, z_, τ_] :=
    Sum[m!*n!/((m - k)!*(n - k)!*k!)*(τ)^k*h[m - k, 0, y]*
      h[n - k, 0, z], {k, 0, Min[m, n]}];

   r[m_, n_, k_, f_] := (1/f)^k*
     Sum[Binomial[k, l]* m!*n!/((m - l)!*(n - k + l)!)*
       hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0, k}];

   integral[m_, n_, p_, f_] :=
    Sqrt[N[Pi]/f]*
     Sum[Binomial[p, k]*h[p - k, 0, 1/(4*f)]*r[m, n, k, f], {k, 0, p}];

   Return[integral[mm, nn, pp, ff]];
   ];

Performance isn't too bad at the moment,
Timing[Table[calculate[n, n, 0, f, 0], {n, 0, 100}]]
{0.096000, {....}}

but the function is called millions of times.
All the input to the function will be solemnly numeric. I don't need any symbolic evaluation and machine precision would be just fine. So I figured that there would be plenty of room for improvement, but I am fairly new to Mathematica and especially to its numerical capabilities.
I would greatly appreciate any suggestions on speeding up that code. Thanks so much.
Note: after taking into account the comments, this is my current code:
h[0., 0., 0.] = 1;
h[n_, 0., y_] := If[Mod[n, 2] == 0, n!*y^(n/2)/((n/2)!), 0];

hh[m_, n_, 0, y_, 0, z_, τ_] :=
  Sum[m!*n!/((m - k)!*(n - k)!*k!)*(τ)^k*h[m - k, 0., y]*
    h[n - k, 0., z], {k, 0., Min[m, n]}];

r[m_, n_, k_, f_] := (1/f)^k*
   Sum[Binomial[k, l]*m!*n!/((m - l)!*(n - k + l)!)*
     hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0.,
     k}];

calculate[m_, n_, p_, f_] :=
  Sqrt[N[Pi]/f]*
   Sum[Binomial[p, k]*h[p - k, 0., 1/(4*f)]*r[m, n, k, f], {k, 0.,
     p}];

and the performance is
f = 1.;
Timing[Table[integrateGaussAndTwoHermite[n, n, 0, f], {n, 0, 100}]]
{0.080000, {...}}

Note: After taking into account even more comments, my code is
h[0., 0., 0.] = 1;
h[n_, 0., y_] :=
  If[Mod[n, 2] == 0, Gamma[n + 1.]*y^(n/2.)/((n/2.)!), 0];

hh[m_, n_, 0., y_, 0., z_, τ_] :=
  Sum[Binomial[m, k]*Gamma[n + 1.]/(Gamma[n - k + 1.])*(τ)^k*
    h[m - k, 0., y]*h[n - k, 0., z], {k, 0., Min[m, n]}];

r[m_, n_, k_, f_] := (1./f)^k*
   Sum[Binomial[k, l]*Gamma[m + 1.]*
     Gamma[n + 1.]/(Gamma[m - l + 1.]*Gamma[n - k + l + 1.])*
     hh[m - l, n - k + l, 0., -1. + 1./f, 0., -1. + 1./f, 2./f], {l,
     0., k}];

integrateGaussAndTwoHermite[m_, n_, p_, f_] :=
  Sqrt[N[Pi]/f]*
   Sum[Binomial[p, k]*h[p - k, 0., 1./(4.*f)]*r[m, n, k, f], {k, 0.,
     p}];

and the execution time is
{0.0720000, {...}}


text:
Q: Wrong width calculation for words in PDF I have a PDF, which has WinAnsiEncoding(Times) and it do not have any toUnicode or differences encoding.
When I try to select or highlight text, width of text is not calculated properly.
I have all the widths but somehow width is calculated incorrectly. What can be the problem? How can I get correct CID of character in order to find correct width of the glyph?  I have attached screenshots for the same. "EXPLANATIONS" word is not selected completely. This can happen only if the widths of glyph are calculated incorrectly.


text:
Q: ComboBox.setValue(T) not calling updateItem(T,boolean) when using cell factory I've overridden ListCell.updateItem(T, boolean) to provide a custom renderer for my ComboBox items (as per Oracle ComboBox tutorial) and this is working fine except when I programmatically set an item using ComboBox.setValue(T).
Instead the toString() method of T is being called. The item being set is already in the ObservableList which backs the ComboBox.
comboBox.setCellFactory(new Callback<ListView<MyType>, ListCell<MyType>>()
{
  @Override
  public ListCell<MyType> call(ListView<MyType> arg0)
  {
    return new ListCell<MyType>()
    {
      @Override
      protected void updateItem(MyType item, boolean empty)
      {
        super.updateItem(item, empty);

        if (item == null || empty)
        {
          setText("");
        }
        else
        {
          setText(item.myCustomRenderMethod());
        }
      }
    };
  }
});

Is there another method I need to override?
JavaFX2 on JDK1.7.0_45.
Thanks.

A: OK, found the answer here: JavaFx Editable ComboBox : Showing toString on item selection
You also need to override ComboBox.setConverter() to ensure that the selected object shows the correct text. This is not in the Oracle tutorial and violates the principle of least surprise for me as it duplicates some of the code from ListCell.updateItem()
 comboBox.setConverter(new StringConverter<MyType>() {
  @Override
  public String toString(MyType obj) {
    if (obj == null)
    {
      return "";
    }
    else
    {
      return obj.myCustomRenderMethod();
    }
  }

  @Override
  public MyType fromString(String s)
  {

      return null;
  }
});

A: In my case using Platform.runLater() solved the issue:
Platform.runLater(() -> comboBox.setValue(value));

My best guess is that setting a value before the ComboBox is part of a Scene causes the problem. Also, be sure to use the setButtonCell(...) method of ComboBox.


text:
Q: Why does this non-linear function make the matrix rank arbitrarily large? I was reading a paper, and came across this argument:
H and W are matrices here, and $\Pi_k$ is a scalar. I am not able to understand what makes the rank of A arbitrarily high rank? I don't follow the logic that log_sum_exp is a non-linear function so $\hat{A}_{MoS}$ is arbitrarily high rank.
A is basically a sum of matrices here, each of those matrices have a bounded rank. How come A has infinite rank then?
The equation is taken from this paper: https://arxiv.org/abs/1711.03953 (sec 2.4)


text:
Q:  Solving Cox Proportional Hazard after creating interaction variable with time I am using lifelines package to do Cox Regression. After trying to fit the model, I checked the CPH assumptions for any possible violations and it returned some problematic variables, along with the suggested solutions.
One of the solution that I would like to try is the one suggested here:
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html#Introduce-time-varying-covariates
However, the example written here is using CoxTimeVaryingFitter which, unlike CoxPHFitter, does not have concordance score, which will help me gauge the model performance. Additionally, CoxTimeVaryingFitter does not have check assumption feature. Does this mean that by putting it into episodic format, all the assumptions are automatically satisfied?
Alternatively, after reading a SAS textbook on survival analysis, it seemed like their solution is to create the interaction term directly (multiplying the problematic variable with the survival time) without changing the format to episodic format (as shown in the link). This way, I was hoping to just keep using CoxPHFitter due to its model scoring capability.
However, after doing this alternative, when I call check_assumptions again on the model with the time-interaction variable, the CPH assumption on the time-interaction variable is violated.
Now I am torn between:

*

*Using CoxTimeVaryingFitter without knowing what the model performance is (seems like a bad idea)

*Using CoxPHFitter, but the assumption is violated on the time-interaction variable (which inherently does not seem to fix the problem)

Any help regarding to solve this confusion is greatly appreciated

A: Here is one suggestion:

*

*If you choose the CoxTimeVaryingFitter, then you need to somehow evaluate the quality of your model. Here is one way. Use the regression coefficients B and write down your model. I'll write it as S(t;x;B), where S is an estimator of the survival, t is the time, and x is a vector of covariates (age, wage, education, etc.). Now, for every individual i, you have a vector of covariates x_i. Thus, you have the survival function for each individual. Consequently, you can predict which individual will 'fail' first, which 'second', and so on. This produces a (predicted) ranking of survival. However, you know the real ranking of survival since you know the failure times or times-to-event. Now, quantify how many pairs (predicted survival, true survival) share the same ranking. In essence, you would be estimating the concordance.

*If you opt to use CoxPHFitter, I don't think it was meant to be used with time-varying covariates. Instead, you could use two other approaches. One is to stratify your variable, i.e., cph.fit(dataframe, time_column, event_column, strata=['your variable to stratify']). The downside is that you no longer obtain a hazard ratio for that variable. The other approach is to use splines. Both of these methods are explained in here.